///|
priv struct FrameFailure {
  status : FrameStatus
  detail : String
}

///|
fn FrameFailure::from_error(error : Error) -> FrameFailure {
  let status = match error {
    CrashError::MissingArtifact(_) => MissingSymbols
    CrashError::IdentityMismatch(_) => IdentityMismatch
    CrashError::IntegrityMismatch(_) => IntegrityMismatch
    _ => Unresolved
  }
  { status, detail: error.to_string(), }
}

///|
priv struct LoadedArtifacts {
  images : Map[String, Result[Bytes, FrameFailure]]
  symbols : Map[String, Result[Bytes, FrameFailure]]
}

///|
async fn cached_artifact(
  bundle : Bundle,
  cache : Map[String, Result[Bytes, FrameFailure]],
  entry : ManifestEntry,
  is_image~ : Bool,
) -> Result[Bytes, FrameFailure] {
  if cache.get(entry.build_id) is Some(result) {
    return result
  }
  let result = Ok(bundle.read_artifact(entry, is_image~)) catch {
    error => Err(FrameFailure::from_error(error))
  }
  cache[entry.build_id] = result
  result
}

///|
fn normalized_name(platform : Platform, path : String) -> String {
  let name = basename(path)
  if platform is Windows {
    name.to_lower()
  } else {
    name
  }
}

///|
fn Bundle::find_entry(
  self : Bundle,
  platform : Platform,
  path : String,
  id : String,
) -> Result[ManifestEntry, FrameFailure] {
  if self.entries.get(artifact_prefix(platform.name(), id)) is Some(entry) {
    return Ok(entry)
  }
  let name = normalized_name(platform, path)
  for entry in self.manifest.entries {
    if entry.platform == platform.name() &&
      normalized_name(platform, entry.module_name) == name {
      return Err({
        status: IdentityMismatch,
        detail: "no entry for \{name} with build identity \{id}",
      })
    }
  }
  Err({ status: MissingSymbols, detail: "no symbol bundle entry for \{id}", })
}

///|
async fn windows_unwind_images(
  bundle : Bundle,
  modules : ArrayView[@model.Module],
  images : Map[String, Result[Bytes, FrameFailure]],
) -> Array[Bytes] {
  let seen = Map([])
  let verified = []
  for loaded in modules {
    if loaded.build_id is Some(id) && !seen.contains(id) {
      seen[id] = ()
      if bundle.entries.get(artifact_prefix("windows", id)) is Some(entry) &&
        cached_artifact(bundle, images, entry, is_image=true) is Ok(image) {
        verified.push(image)
      }
    }
  }
  verified
}

///|
async fn resolve_frame(
  bundle : Bundle,
  cache : LoadedArtifacts,
  platform : Platform,
  entry : ManifestEntry,
  offset : UInt64,
) -> Result[@model.Location, FrameFailure] {
  let image = match
    cached_artifact(bundle, cache.images, entry, is_image=true) {
    Ok(image) => image
    Err(failure) => return Err(failure)
  }
  let symbols = match
    cached_artifact(bundle, cache.symbols, entry, is_image=false) {
    Ok(symbols) => symbols
    Err(failure) => return Err(failure)
  }
  try {
    let location = match platform {
      Linux => @linux.symbolize(image, symbols, offset)
      Windows => @windows.symbolize(image, symbols, offset)
    }
    if location.function is Some(_) ||
      (location.file is Some(_) && location.line is Some(_)) {
      Ok(location)
    } else {
      Err({
        status: Unresolved,
        detail: "matching symbols contain no location for this address",
      })
    }
  } catch {
    error => Err(FrameFailure::from_error(error))
  }
}

///|
async fn analyze_frame(
  bundle : Bundle?,
  cache : LoadedArtifacts,
  platform : Platform,
  modules : ArrayView[@model.Module],
  frame : @model.Frame,
) -> FrameReport {
  let loaded = modules
    .iter()
    .find_first(loaded => {
      frame.lookup_address >= loaded.base &&
      loaded.ranges.any(range => {
        range.start <= frame.lookup_address && frame.lookup_address < range.end
      })
    })
  let offset = loaded.map(loaded => frame.lookup_address - loaded.base)
  let result = match (loaded, offset) {
    (Some(loaded), Some(offset)) =>
      match (loaded.build_id, bundle) {
        (Some(id), Some(bundle)) =>
          match bundle.find_entry(platform, loaded.path, id) {
            Ok(entry) => resolve_frame(bundle, cache, platform, entry, offset)
            Err(failure) => Err(failure)
          }
        (None, _) =>
          Err({
            status: IdentityUnavailable,
            detail: "build identity is absent from the dump",
          })
        (Some(_), None) =>
          Err({
            status: MissingSymbols,
            detail: "no symbol bundle was provided",
          })
      }
    _ =>
      Err({
        status: NoModule,
        detail: "instruction is outside the recorded module mappings",
      })
  }
  let base : FrameReport = {
    address: frame.address,
    lookup_address: frame.lookup_address,
    kind: frame.kind,
    module_path: loaded.map(loaded => loaded.path),
    module_offset: offset,
    build_id: loaded.bind(loaded => loaded.build_id),
    status: Resolved,
    function: None,
    file: None,
    line: None,
    detail: None,
  }
  match result {
    Ok(location) =>
      {
        ..base,
        function: location.function,
        file: location.file,
        line: location.line,
      }
    Err(failure) =>
      { ..base, status: failure.status, detail: Some(failure.detail), }
  }
}

///|
/// Analyze the faulting thread of a Windows x64 Minidump or Linux x64 ELF core.
pub async fn analyze(dump_bytes : Bytes, bundle? : Bundle) -> Report {
  let platform = dump_platform(dump_bytes)
  let cache = { images: Map([]), symbols: Map([]), }
  let dump = match platform {
    Linux => @linux.read_dump(dump_bytes)
    Windows => {
      let initial = @windows.read_dump(dump_bytes)
      let images = match bundle {
        Some(bundle) =>
          windows_unwind_images(bundle, initial.modules, cache.images)
        None => []
      }
      if images.is_empty() {
        initial
      } else {
        @windows.read_dump(dump_bytes, unwind_images=images)
      }
    }
  }
  build_report(dump, platform, cache, bundle)
}

///|
async fn build_report(
  dump : @model.Dump,
  platform : Platform,
  cache : LoadedArtifacts,
  bundle : Bundle?,
) -> Report {
  let frames = []
  for frame in dump.frames {
    frames.push(analyze_frame(bundle, cache, platform, dump.modules, frame))
  }
  let modules = ReadOnlyArray::from_iter(
    dump.modules
    .iter()
    .map(loaded => {
      let ranges = ReadOnlyArray::from_iter(
        loaded.ranges
        .iter()
        .map(range => { start: range.start, end: range.end, }),
      )
      {
        path: loaded.path,
        base: loaded.base,
        build_id: loaded.build_id,
        ranges,
      }
    }),
  )
  {
    platform,
    architecture: "x64",
    thread_id: dump.thread_id,
    exception: dump.exception,
    modules,
    frames: ReadOnlyArray::from_array(frames),
  }
}

///|
pub async fn analyze_file(dump_path : String, bundle? : Bundle) -> Report {
  let file = @fs.open(dump_path, mode=ReadOnly)
  defer file.close()
  let size = file.size()
  guard size >= 4L else {
    raise UnsupportedFormat("expected ELF core or Windows Minidump")
  }
  let magic = file.read_exactly_at(4, position=0L)
  match dump_platform(magic) {
    Linux => {
      let dump = @linux.read_dump_file(file)
      build_report(dump, Linux, { images: Map([]), symbols: Map([]), }, bundle)
    }
    Windows => analyze(read_sized_file(file, size), bundle?)
  }
}