///|
#derive(Debug, ToJson)
pub struct CertificateVerification {
  status : String
  verification_scope : String
  trust_source : String
  detail : String
}

///|
#derive(Debug, ToJson)
pub struct CertificateInfo {
  subject : String
  issuer : String
  not_before : String
  not_after : String
  sha256_fingerprint : String
  dns_names : Array[String]
  ip_addresses : Array[String]
  verification : CertificateVerification
}

///|
fn parse_certificate_metadata(
  text : String,
  verification : CertificateVerification,
) -> CertificateInfo raise InputError {
  guard text.length() <= 262144 else {
    raise InputError("certificate metadata exceeds limit")
  }
  let values : Map[String, String] = Map([])
  let dns_names = []
  let ip_addresses = []
  for line in text.split("\n") {
    if line.split_once("=") is Some((key, value)) {
      let key = ascii_lower(key)
      if !values.contains(key) {
        values[key] = value.trim().to_owned()
      }
    }
    for entry in line.split(",") {
      let entry = entry.trim()
      if entry.has_prefix("DNS:") {
        dns_names.push(entry[4:].to_owned())
      }
      if entry.has_prefix("IP Address:") {
        ip_addresses.push(entry[11:].to_owned())
      }
    }
  }
  guard values.get("subject") is Some(subject) &&
    values.get("issuer") is Some(issuer) &&
    values.get("notbefore") is Some(not_before) &&
    values.get("notafter") is Some(not_after) &&
    values.get("sha256 fingerprint") is Some(fingerprint) else {
    raise InputError("incomplete OpenSSL certificate metadata")
  }
  let octets = fingerprint.split(":").collect()
  guard octets.length() == 32 else {
    raise InputError("invalid SHA-256 fingerprint")
  }
  for octet in octets {
    guard octet.length() == 2 else {
      raise InputError("invalid SHA-256 fingerprint")
    }
    ignore(hex_number(octet, 255))
  }
  {
    subject,
    issuer,
    not_before,
    not_after,
    sha256_fingerprint: fingerprint,
    dns_names,
    ip_addresses,
    verification,
  }
}

///|
/// Parse a collected leaf certificate and optionally verify it offline with
/// OpenSSL 3+. No chain fetching, OCSP, CRL downloads or additional TLS connections.
/// The verification scope is leaf-only, not the server-supplied full chain.
pub async fn inspect_certificate(
  der : Bytes,
  target : String,
  verify~ : Bool = false,
  ca_file? : String,
  openssl~ : String = "openssl",
) -> CertificateInfo {
  guard der.length() > 0 && der.length() <= 65536 else {
    raise InputError("certificate must be in 1..65536 bytes")
  }
  guard ca_file is None || verify else {
    raise InputError("certificate trust file requires verification")
  }
  let directory = @fs.tmpdir(prefix="mscan-certificate-")
  defer @fs.remove(directory, recursive=true)
  let input = directory + "/leaf.der"
  @fs.write_binary(input, der, create_mode=CreateNew, permission=0o600)
  let metadata = @process.run(
    openssl,
    [
      "x509", "-inform", "DER", "-in", input, "-noout", "-subject", "-issuer", "-dates",
      "-dateopt", "iso_8601", "-nameopt", "RFC2253", "-sha256", "-fingerprint", "-ext",
      "subjectAltName",
    ],
    stdin=Empty,
    stdout=Collect,
    stderr=Collect,
    cancel_handler=@process.hard_cancel(),
    accepted_exit_code=code => code == 0,
  )
  let mut verification : CertificateVerification = {
    status: "not_checked",
    verification_scope: "openssl_offline_leaf",
    trust_source: "none",
    detail: "",
  }
  if verify {
    let pem = directory + "/leaf.pem"
    ignore(
      @process.run(
        openssl,
        ["x509", "-inform", "DER", "-in", input, "-outform", "PEM", "-out", pem],
        stdin=Empty,
        stdout=Discard,
        stderr=Collect,
        cancel_handler=@process.hard_cancel(),
        accepted_exit_code=code => code == 0,
      ),
    )
    let args = ["verify", "-purpose", "sslserver"]
    if ca_file is Some(path) {
      args.append(["-CAfile", path, "-no-CApath", "-no-CAstore"])
    }
    try @socket.IpAddr::parse(target) catch {
      _ => args.append(["-verify_hostname", target])
    } noraise {
      ip =>
        args.append([
          "-verify_ip",
          ip.to_string().trim(chars="[]").split("%").next().unwrap().to_owned(),
        ])
    }
    args.push(pem)
    let checked = @process.run(
      openssl,
      args,
      stdin=Empty,
      stdout=Collect,
      stderr=Collect,
      accepted_exit_code=_ => true,
      cancel_handler=@process.hard_cancel(),
    )
    verification = {
      status: if checked.exit_code == 0 {
        "verified"
      } else {
        "failed"
      },
      verification_scope: "openssl_offline_leaf",
      trust_source: ca_file.unwrap_or("openssl_default"),
      detail: if checked.exit_code == 0 {
        ""
      } else {
        checked.stderr_text()[:4096].to_owned()
      },
    }
  }
  parse_certificate_metadata(metadata.stdout_text(), verification)
}