///|
const MANIFEST_SCHEMA : String = "moonbit-native-crash/symbol-bundle/v1"

///|
#derive(Debug, Eq)
pub(all) enum Platform {
  Linux
  Windows
}

///|
pub fn Platform::name(self : Platform) -> String {
  match self {
    Linux => "linux"
    Windows => "windows"
  }
}

///|
#derive(Debug, ToJson)
pub struct Manifest {
  schema : String
  entries : ReadOnlyArray[ManifestEntry]
}

///|
#derive(FromJson)
priv struct ManifestDocument {
  schema : String
  entries : Array[ManifestEntry]
}

///|
#derive(Debug, FromJson, ToJson)
pub struct ManifestEntry {
  platform : String
  architecture : String
  build_id : String
  module_name : String
  image : String
  image_sha256 : String
  symbols : String
  symbols_sha256 : String
}

///|
#derive(Debug)
pub(all) suberror CrashError {
  InvalidManifest(String)
  UnsupportedFormat(String)
  IdentityMismatch(String)
  IntegrityMismatch(String)
  MissingArtifact(String)
  InvalidArtifact(String)
  InvalidInput(String)
}

///|
pub impl Show for CrashError with fn to_string(self) {
  match self {
    InvalidManifest(detail) => "Invalid manifest: \{detail}"
    UnsupportedFormat(detail) => "Unsupported format: \{detail}"
    IdentityMismatch(detail) => "Build identity mismatch: \{detail}"
    IntegrityMismatch(detail) => "SHA-256 mismatch: \{detail}"
    MissingArtifact(detail) => "Missing artifact: \{detail}"
    InvalidArtifact(detail) => "Invalid artifact: \{detail}"
    InvalidInput(detail) => "Invalid input: \{detail}"
  }
}

///|
fn image_platform(image : Bytes) -> Platform raise CrashError {
  if image.has_prefix(b"\x7fELF") {
    Linux
  } else if image.has_prefix(b"MZ") {
    Windows
  } else {
    raise UnsupportedFormat("expected ELF or PE image")
  }
}

///|
fn dump_platform(dump : Bytes) -> Platform raise CrashError {
  if dump.has_prefix(b"\x7fELF") {
    Linux
  } else if dump.has_prefix(b"MDMP") {
    Windows
  } else {
    raise UnsupportedFormat("expected ELF core or Windows Minidump")
  }
}

///|
fn image_identity(platform : Platform, image : Bytes) -> String raise {
  match platform {
    Linux => @linux.image_identity(image)
    Windows => @windows.image_identity(image)
  }
}

///|
fn symbol_identity(platform : Platform, symbols : Bytes) -> String raise {
  match platform {
    Linux => @linux.symbol_identity(symbols)
    Windows => @windows.symbol_identity(symbols)
  }
}

///|
fn is_hex(value : StringView) -> Bool {
  value
  .code_units()
  .all(unit => (unit >= 48 && unit <= 57) || (unit >= 97 && unit <= 102))
}

///|
fn valid_build_id(platform : Platform, id : String) -> Bool {
  match platform {
    Linux => id.length() is (2..<=128) && id.length() % 2 == 0 && is_hex(id)
    Windows =>
      match id.split("-").collect() {
        [a, b, c, d, e, age] => {
          if a.length() != 8 ||
            b.length() != 4 ||
            c.length() != 4 ||
            d.length() != 4 ||
            e.length() != 12 ||
            !is_hex(a) ||
            !is_hex(b) ||
            !is_hex(c) ||
            !is_hex(d) ||
            !is_hex(e) {
            return false
          }
          try @string.parse_uint(age).to_string()[:] == age catch {
            _ => false
          }
        }
        _ => false
      }
  }
}

///|
fn artifact_prefix(platform : String, id : String) -> String {
  "\{platform}-\{id}"
}

///|
fn basename(path : String) -> String {
  // Accept both separators when reading paths embedded by a different host.
  let slash = path.rev_find_code_unit(47).unwrap_or(-1)
  let backslash = path.rev_find_code_unit(92).unwrap_or(-1)
  let offset = if slash > backslash { slash + 1 } else { backslash + 1 }
  path[offset:].to_owned()
}

///|
fn validate_entry(entry : ManifestEntry) -> Unit raise CrashError {
  let platform = match entry.platform {
    "linux" => Linux
    "windows" => Windows
    name => raise InvalidManifest("unsupported platform \{name}")
  }
  guard entry.architecture == "x64" else {
    raise InvalidManifest("unsupported architecture \{entry.architecture}")
  }
  guard valid_build_id(platform, entry.build_id) else {
    raise InvalidManifest("invalid \{entry.platform} build identity")
  }
  guard !entry.module_name.is_empty() &&
    basename(entry.module_name) == entry.module_name &&
    entry.module_name != "." &&
    entry.module_name != ".." else {
    raise InvalidManifest("expected a module basename")
  }
  let prefix = artifact_prefix(entry.platform, entry.build_id)
  guard entry.image == "\{prefix}.image" && entry.symbols == "\{prefix}.symbols" else {
    raise InvalidManifest("invalid artifact path for \{entry.build_id}")
  }
  guard entry.image_sha256.length() == 64 &&
    is_hex(entry.image_sha256) &&
    entry.symbols_sha256.length() == 64 &&
    is_hex(entry.symbols_sha256) else {
    raise InvalidManifest("invalid SHA-256 for \{entry.build_id}")
  }
}

///|
fn index_manifest(
  manifest : Manifest,
) -> Map[String, ManifestEntry] raise CrashError {
  guard manifest.schema == MANIFEST_SCHEMA else {
    raise InvalidManifest("unsupported schema \{manifest.schema}")
  }
  guard !manifest.entries.is_empty() else {
    raise InvalidManifest("symbol bundle is empty")
  }
  let entries = Map([])
  for entry in manifest.entries {
    validate_entry(entry)
    let key = artifact_prefix(entry.platform, entry.build_id)
    guard !entries.contains(key) else {
      raise InvalidManifest("duplicate identity \{key}")
    }
    entries[key] = entry
  }
  entries
}