///|
const REPORT_SCHEMA : String = "moonbit-native-crash/report/v1"

///|
#derive(Debug, Eq)
pub(all) enum FrameStatus {
  Resolved
  Unresolved
  NoModule
  MissingSymbols
  IdentityUnavailable
  IdentityMismatch
  IntegrityMismatch
}

///|
pub fn FrameStatus::name(self : FrameStatus) -> String {
  match self {
    Resolved => "resolved"
    Unresolved => "unresolved"
    NoModule => "no_module"
    MissingSymbols => "missing_symbols"
    IdentityUnavailable => "identity_unavailable"
    IdentityMismatch => "identity_mismatch"
    IntegrityMismatch => "integrity_mismatch"
  }
}

///|
#derive(Debug)
pub struct AddressRange {
  start : UInt64
  end : UInt64
}

///|
#derive(Debug)
pub struct LoadedModule {
  path : String
  base : UInt64
  build_id : String?
  ranges : ReadOnlyArray[AddressRange]
}

///|
#derive(Debug)
pub struct FrameReport {
  address : UInt64
  lookup_address : UInt64
  kind : String
  module_path : String?
  module_offset : UInt64?
  build_id : String?
  status : FrameStatus
  function : String?
  file : String?
  line : Int32?
  detail : String?
}

///|
#derive(Debug)
pub struct Report {
  platform : Platform
  architecture : String
  thread_id : UInt64
  exception : String
  modules : ReadOnlyArray[LoadedModule]
  frames : ReadOnlyArray[FrameReport]
}

///|
fn hex_address(value : UInt64) -> String {
  "0x\{value.to_string(radix=16)}"
}

///|
fn[T : ToJson] nullable_json(value : T?) -> Json {
  match value {
    Some(value) => @json.to_json(value)
    None => @json.null
  }
}

///|
pub impl ToJson for AddressRange with fn to_json(self) {
  {
    "start": @json.to_json(hex_address(self.start)),
    "end": @json.to_json(hex_address(self.end)),
  }
}

///|
pub impl ToJson for LoadedModule with fn to_json(self) {
  {
    "path": @json.to_json(self.path),
    "base": @json.to_json(hex_address(self.base)),
    "build_id": nullable_json(self.build_id),
    "ranges": @json.to_json(self.ranges),
  }
}

///|
pub impl ToJson for FrameReport with fn to_json(self) {
  {
    "address": @json.to_json(hex_address(self.address)),
    "lookup_address": @json.to_json(hex_address(self.lookup_address)),
    "kind": @json.to_json(self.kind),
    "module": nullable_json(self.module_path),
    "module_offset": nullable_json(self.module_offset.map(hex_address)),
    "build_id": nullable_json(self.build_id),
    "status": @json.to_json(self.status.name()),
    "function": nullable_json(self.function),
    "file": nullable_json(self.file),
    "line": nullable_json(self.line),
    "detail": nullable_json(self.detail),
  }
}

///|
pub impl ToJson for Report with fn to_json(self) {
  {
    "schema": @json.to_json(REPORT_SCHEMA),
    "platform": @json.to_json(self.platform.name()),
    "architecture": @json.to_json(self.architecture),
    "thread_id": @json.to_json(hex_address(self.thread_id)),
    "exception": @json.to_json(self.exception),
    "modules": @json.to_json(self.modules),
    "frames": @json.to_json(self.frames),
  }
}