///|
/// An image and its corresponding ELF debug file or PDB from one build.
#derive(Debug)
pub(all) struct SymbolPair {
  image : String
  symbols : String
}

///|
pub struct Bundle {
  priv directory : String
  priv entries : Map[String, ManifestEntry]
  manifest : Manifest
}

///|
async fn read_bytes(path : String) -> Bytes {
  let file = @fs.open(path, mode=ReadOnly)
  defer file.close()
  read_sized_file(file, file.size())
}

///|
async fn read_sized_file(file : @fs.File, size : Int64) -> Bytes {
  guard size >= 0L && size <= 0x7fff_ffffL else {
    raise InvalidInput("file exceeds the size limit for in-memory reads")
  }
  let content : &@io.Data = file.read_all()
  content.binary()
}

///|
fn sha256(content : Bytes) -> String {
  @crypto.bytes_to_hex_string(@crypto.sha256(content))
}

///|
async fn pack_pair(directory : String, pair : SymbolPair) -> ManifestEntry {
  let image = read_bytes(pair.image)
  let symbols = read_bytes(pair.symbols)
  let platform = image_platform(image)
  let build_id = image_identity(platform, image)
  let actual_id = symbol_identity(platform, symbols)
  guard build_id == actual_id else {
    raise CrashError::IdentityMismatch(
      "\{pair.image} has \{build_id}, \{pair.symbols} has \{actual_id}",
    )
  }
  let prefix = artifact_prefix(platform.name(), build_id)
  let entry : ManifestEntry = {
    platform: platform.name(),
    architecture: "x64",
    build_id,
    module_name: basename(pair.image),
    image: "\{prefix}.image",
    image_sha256: sha256(image),
    symbols: "\{prefix}.symbols",
    symbols_sha256: sha256(symbols),
  }
  validate_entry(entry)
  @fs.write_file("\{directory}/\{entry.image}", image, create_mode=CreateNew)
  @fs.write_file(
    "\{directory}/\{entry.symbols}",
    symbols,
    create_mode=CreateNew,
  )
  entry
}

///|
/// Build and publish a bundle at a new directory on the same filesystem as its staging files.
pub async fn pack(directory : String, pairs : ArrayView[SymbolPair]) -> Bundle {
  guard !pairs.is_empty() else {
    raise InvalidInput("provide at least one image and symbol pair")
  }
  let directory = directory.trim_end(chars="/\\").to_owned()
  guard !directory.is_empty() && !@fs.exists(directory) else {
    raise InvalidInput("bundle destination must be a new directory")
  }
  let nonce = @env.rand(12).unwrap_or_error(
    InvalidInput("could not generate staging directory name"),
  )
  let stage = "\{directory}.pack-\{@crypto.bytes_to_hex_string(nonce)}"
  @fs.mkdir(stage)
  errdefer (@fs.rmdir(stage, recursive=true) catch { _ => () })
  let entries = []
  for pair in pairs {
    entries.push(pack_pair(stage, pair))
  }
  let manifest : Manifest = {
    schema: MANIFEST_SCHEMA,
    entries: ReadOnlyArray::from_array(entries),
  }
  let index = index_manifest(manifest)
  @fs.write_file(
    "\{stage}/manifest.json",
    @json.to_json(manifest).stringify(indent=2) + "\n",
  )
  @fs.rename(stage, directory, replace=false)
  { directory, manifest, entries: index, }
}

///|
/// Load the manifest. Artifact checks run on demand during analysis or through `verify`.
pub async fn Bundle::open(directory : String) -> Bundle {
  let content = @fs.read_file("\{directory}/manifest.json").text()
  let document : ManifestDocument = @json.from_json(
    @json.parse(content, reject_duplicate_keys=true),
  ) catch {
    error => raise InvalidManifest(error.to_string())
  }
  let manifest : Manifest = {
    schema: document.schema,
    entries: ReadOnlyArray::from_array(document.entries),
  }
  { directory, manifest, entries: index_manifest(manifest), }
}

///|
async fn Bundle::read_artifact(
  self : Bundle,
  entry : ManifestEntry,
  is_image~ : Bool,
) -> Bytes {
  let (name, hash) = if is_image {
    (entry.image, entry.image_sha256)
  } else {
    (entry.symbols, entry.symbols_sha256)
  }
  let path = "\{self.directory}/\{name}"
  guard @fs.exists(path) else { raise MissingArtifact(name) }
  guard @fs.kind(path, follow_symlink=false) is Regular else {
    raise InvalidArtifact("\{name} must be a regular file")
  }
  let content = read_bytes(path)
  let platform = if entry.platform == "linux" { Linux } else { Windows }
  let actual_id = try {
    if is_image {
      image_identity(platform, content)
    } else {
      symbol_identity(platform, content)
    }
  } catch {
    error => raise InvalidArtifact("\{name}: \{error}")
  }
  guard actual_id == entry.build_id else {
    raise CrashError::IdentityMismatch(
      "\{name} has \{actual_id}, expected \{entry.build_id}",
    )
  }
  guard sha256(content) == hash else {
    raise CrashError::IntegrityMismatch(name)
  }
  content
}

///|
/// Verify both artifact identities and SHA-256 checksums for every manifest entry.
pub async fn Bundle::verify(self : Bundle) -> Unit {
  for entry in self.manifest.entries {
    ignore(self.read_artifact(entry, is_image=true))
    ignore(self.read_artifact(entry, is_image=false))
  }
}