///|
/// A point in time, in milliseconds since 1970-01-01T00:00:00Z.
#derive(Eq, Compare, Hash, Debug)
struct Instant {
  millis : Int64
}

///|
pub fn Instant::of_millis(millis : Int64) -> Instant {
  { millis, }
}

///|
pub fn Instant::millis(self : Instant) -> Int64 {
  self.millis
}

///|
/// Days since 1970-01-01 for a proleptic Gregorian date.
fn days_from_civil(year : Int32, month : Int32, day : Int32) -> Int64 {
  let y = if month <= 2 { year - 1 } else { year }
  let era = (if y >= 0 { y } else { y - 399 }) / 400
  let yoe = y - era * 400
  let mp = (month + 9) % 12
  let doy = (153 * mp + 2) / 5 + day - 1
  let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy
  (era * 146097 + doe - 719468).to_int64()
}

///|
fn digits(text : String, start : Int32, count : Int32) -> Int32? {
  if start + count > text.length() {
    return None
  }
  let mut value = 0
  for i in start..<(start + count) {
    let c = text[i]
    if c < '0' || c > '9' {
      return None
    }
    value = value * 10 + (c.to_int() - '0'.to_int())
  }
  Some(value)
}

///|
fn days_in_month(year : Int32, month : Int32) -> Int32 {
  match month {
    2 =>
      if (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 {
        29
      } else {
        28
      }
    4 | 6 | 9 | 11 => 30
    _ => 31
  }
}

///|
/// Parses an RFC 3339 `date-time` with an explicit offset, such as
/// `2026-06-30T14:00:00Z` or `2026-06-30T14:00:00.250+02:00`. With
/// `date_only=true`, an RFC 3339 `full-date` (`YYYY-MM-DD`) is the start of
/// that day in UTC.
pub fn Instant::parse(text : String, date_only~ : Bool = false) -> Instant? {
  let text = text.trim(chars=" \t").to_owned()
  guard digits(text, 0, 4) is Some(year) &&
    text.length() >= 10 &&
    text[4] == '-' &&
    text[7] == '-' &&
    digits(text, 5, 2) is Some(month) &&
    digits(text, 8, 2) is Some(day) else {
    return None
  }
  guard month >= 1 &&
    month <= 12 &&
    day >= 1 &&
    day <= days_in_month(year, month) else {
    return None
  }
  let days = days_from_civil(year, month, day)
  if text.length() == 10 {
    return if date_only { Some({ millis: days * 86400000L, }) } else { None }
  }
  guard (text[10] == 'T' || text[10] == 't') &&
    text.length() >= 20 &&
    digits(text, 11, 2) is Some(hour) &&
    text[13] == ':' &&
    digits(text, 14, 2) is Some(minute) &&
    text[16] == ':' &&
    digits(text, 17, 2) is Some(second) else {
    return None
  }
  let mut i = 19
  let mut millis = 0
  if i < text.length() && text[i] == '.' {
    i += 1
    let mut frac_digits = 0
    let mut scale = 100
    while i < text.length() && text[i] >= '0' && text[i] <= '9' {
      millis += (text[i].to_int() - '0'.to_int()) * scale
      scale /= 10
      frac_digits += 1
      i += 1
    }
    guard frac_digits > 0 else { return None }
  }
  guard hour <= 23 && minute <= 59 && second <= 60 else { return None }
  guard i < text.length() else { return None }
  let offset_minutes = if text[i] == 'Z' || text[i] == 'z' {
    guard i + 1 == text.length() else { return None }
    0
  } else if text[i] == '+' || text[i] == '-' {
    guard i + 6 == text.length() &&
      digits(text, i + 1, 2) is Some(oh) &&
      text[i + 3] == ':' &&
      digits(text, i + 4, 2) is Some(om) &&
      oh <= 23 &&
      om <= 59 else {
      return None
    }
    let sign = if text[i] == '-' { -1 } else { 1 }
    sign * (oh * 60 + om)
  } else {
    return None
  }
  let total = days * 86400000L +
    (hour * 3600 + minute * 60 + second - offset_minutes * 60).to_int64() *
    1000L +
    millis.to_int64()
  Some({ millis: total, })
}

///|
/// Parses a calendar date written exactly as `YYYY-MM-DD`, such as `2026-10-23`,
/// as the start of that day in UTC. Other forms and dates that do not exist
/// give `None`.
pub fn Instant::parse_date(text : String) -> Instant? {
  if text.length() == 10 {
    Instant::parse(text, date_only=true)
  } else {
    None
  }
}

///|
/// True when `text` is a valid RFC 3339 date-only value (`YYYY-MM-DD`).
pub fn Instant::is_date_only(text : String) -> Bool {
  Instant::parse_date(text.trim(chars=" \t").to_owned()) is Some(_)
}

///|
/// The lifecycle status of a concept (OKF v0.3, section 5.4).
#derive(Eq, Debug)
pub(all) enum Status {
  Draft
  Stable
  Deprecated
  /// Any other status word.
  Unknown(UnknownStatus)
}

///|
/// A status word that is not draft, stable or deprecated. Only `Status::parse`
/// makes one, so it is never blank and never a known word.
#derive(Eq, Hash, Debug)
struct UnknownStatus {
  text : String
}

///|
pub fn UnknownStatus::to_string(self : UnknownStatus) -> String {
  self.text
}

///|
pub impl Show for UnknownStatus with fn output(self, logger) {
  logger.write_string(self.text)
}

///|
/// Parses a status word, ignoring letter case and surrounding white space. A
/// blank text has no status.
pub fn Status::parse(text : String) -> Status? {
  let t = text.trim(chars=" \t").to_owned()
  match t.to_lower() {
    "" => None
    "draft" => Some(Draft)
    "stable" => Some(Stable)
    "deprecated" => Some(Deprecated)
    _ => Some(Unknown({ text: t, }))
  }
}

///|
pub fn Status::to_string(self : Status) -> String {
  match self {
    Draft => "draft"
    Stable => "stable"
    Deprecated => "deprecated"
    Unknown(word) => word.text
  }
}

///|
/// True when the status represents current knowledge (`stable` or `draft`).
/// `deprecated` and unknown values are not current (OKF v0.3, section 5.4).
pub fn Status::is_current(self : Status) -> Bool {
  self is (Stable | Draft)
}

///|
fn is_scheme_char(c : Char, first : Bool) -> Bool {
  (c >= 'a' && c <= 'z') ||
  (c >= 'A' && c <= 'Z') ||
  (!first && ((c >= '0' && c <= '9') || c == '+' || c == '-' || c == '.'))
}

///|
fn is_valid_scheme(text : String) -> Bool {
  let chars = text.to_array()
  if chars.is_empty() {
    return false
  }
  for i, c in chars {
    if !is_scheme_char(c, i == 0) {
      return false
    }
  }
  true
}

///|
fn has_space(text : String) -> Bool {
  text.iter().any(is_space_char)
}

///|
/// Who produced, authored or verified knowledge (OKF v0.3, section 7). Only
/// `Actor::parse` makes one, so no case holds an empty ID.
#derive(Eq, Debug)
pub enum Actor {
  /// An automated producer, `/`.
  Producer(name~ : String, version~ : String)
  /// A person, `human:`, with a non-empty ID.
  Human(String)
  /// A group of people, `team:`, with a non-empty ID (non-human).
  Team(String)
  /// An automated process, `process:`, with a non-empty ID.
  Process(String)
  /// Another `:` actor with a valid scheme and non-empty ID.
  Scheme(scheme~ : String, id~ : String)
  /// Any other non-blank text that does not match the OKF actor convention.
  Other(String)
}

///|
/// Parses an actor per OKF v0.3 section 7. A blank text names no actor.
pub fn Actor::parse(text : String) -> Actor? {
  let text = text.trim(chars=" \t").to_owned()
  if text.length() == 0 {
    return None
  }
  if !has_space(text) {
    match text.find(":") {
      Some(i) if i > 0 && i < text.length() - 1 => {
        let scheme = text[:i].to_owned()
        let id = text[i + 1:].to_owned()
        if is_valid_scheme(scheme) {
          return Some(
            match scheme {
              "human" => Human(id)
              "team" => Team(id)
              "process" => Process(id)
              _ => Scheme(scheme~, id~)
            },
          )
        }
      }
      _ => ()
    }
    match text.find("/") {
      Some(i) if i > 0 && i < text.length() - 1 && !text.contains(":") =>
        return Some(
          Producer(name=text[:i].to_owned(), version=text[i + 1:].to_owned()),
        )
      _ => ()
    }
  }
  Some(Other(text))
}

///|
pub fn Actor::is_human(self : Actor) -> Bool {
  self is Human(_)
}

///|
/// True when the actor matches `/` or `:`.
pub fn Actor::is_valid(self : Actor) -> Bool {
  !(self is Other(_))
}

///|
/// One `sources` entry (OKF v0.3, section 5.1).
#derive(Eq, Debug)
pub(all) struct Source {
  resource : String
  id : String?
  title : String?
  author : Actor?
  usage_count : Int32?
  last_modified : String?
  usage_window : UsageWindow?
}

///|
/// A `usage_window` mapping with its raw `from` and `to` texts.
#derive(Eq, Debug)
pub(all) struct UsageWindow {
  from : String?
  to : String?
}

///|
/// A `{by, at}` record, as in `generated`. An attribution without an actor,
/// such as a v0.1 `timestamp`, has no `by`.
#derive(Eq, Debug)
pub(all) struct Attribution {
  by : Actor?
  at : String?
}

///|
/// A parsed `verified` event (OKF v0.3, section 5.2). Both `by` and `at` are
/// guaranteed present and valid. Only `Metadata::verified` (and its current and
/// historical filters) constructs one.
#derive(Eq, Debug)
struct Verification {
  by : Actor
  at : Instant
  at_text : String
}

///|
pub fn Verification::by(self : Verification) -> Actor {
  self.by
}

///|
pub fn Verification::at(self : Verification) -> Instant {
  self.at
}

///|
pub fn Verification::at_text(self : Verification) -> String {
  self.at_text
}

///|
/// The derived trust tier (OKF v0.3, section 5.3).
#derive(Eq, Compare, Debug)
pub(all) enum TrustTier {
  Unverified
  MachineConfirmed
  HumanReviewed
}

///|
/// The freshness of a concept against a caller-supplied instant (OKF v0.3,
/// section 5.5). A malformed `stale_after` is never `Fresh`.
#derive(Eq, Debug)
pub(all) enum Freshness {
  /// No `stale_after` key (or empty/null).
  NoExpiry
  /// `now < stale_after`.
  Fresh(Instant)
  /// `now >= stale_after`.
  Stale(Instant)
  /// `stale_after` is present but cannot be parsed as a timestamp.
  Malformed(String)
}

///|
/// One `parameters` entry of an Attested Computation (OKF v0.3, section 10.2).
/// Both `name` and `type` are required; `required` defaults to `false`.
#derive(Eq, Debug)
pub(all) struct Parameter {
  name : String
  type_ : String
  required : Bool
}

///|
/// The `executor` of an Attested Computation.
#derive(Eq, Debug)
pub(all) struct Executor {
  resource : String?
  receipt : ReadOnlyArray[String]
}

///|
fn usage_window_of(fields : Fields) -> UsageWindow {
  { from: fields.text("from"), to: fields.text("to"), }
}

///|
fn attribution_of(fields : Fields) -> Attribution? {
  match fields.text("by") {
    Some(by) => Some({ by: Actor::parse(by), at: fields.text("at"), })
    None => None
  }
}

///|
/// The OKF `type`, or `None` when it is missing or blank.
pub fn Metadata::concept_type(self : Metadata) -> ConceptType? {
  match self.text("type") {
    Some(t) =>
      try ConceptType(t) catch {
        _ => None
      } noraise {
        c => Some(c)
      }
    None => None
  }
}

///|
pub fn Metadata::title(self : Metadata) -> String? {
  self.text("title")
}

///|
pub fn Metadata::description(self : Metadata) -> String? {
  self.text("description")
}

///|
pub fn Metadata::resource(self : Metadata) -> String? {
  self.text("resource")
}

///|
pub fn Metadata::tags(self : Metadata) -> Array[String] {
  self.texts("tags")
}

///|
/// The top-level `usage_window`.
pub fn Metadata::usage_window(self : Metadata) -> UsageWindow? {
  match self.mappings("usage_window") {
    [fields, ..] => Some(usage_window_of(fields))
    [] => None
  }
}

///|
/// The `sources` entries that have a `resource`. Entries without one are left out.
pub fn Metadata::sources(self : Metadata) -> Array[Source] {
  self
  .mappings("sources")
  .iter()
  .filter_map(fields => {
    match fields.text("resource") {
      Some(resource) =>
        Some({
          resource,
          id: fields.text("id"),
          title: fields.text("title"),
          author: fields.text("author").bind(Actor::parse),
          usage_count: fields.int("usage_count"),
          last_modified: fields.text("last_modified"),
          usage_window: match fields.get("usage_window") {
            Some(Mapping(window)) => Some(usage_window_of(window))
            _ => None
          },
        })
      None => None
    }
  })
  .collect()
}

///|
/// `generated`, or with `v01_fields` a v0.1 `timestamp` as `generated.at`.
pub fn Metadata::generated(
  self : Metadata,
  options~ : Options = Options::default(),
) -> Attribution? {
  match self.mappings("generated") {
    [fields, ..] => attribution_of(fields)
    [] =>
      if options.v01_fields {
        match self.text("timestamp") {
          Some(at) => Some({ by: None, at: Some(at), })
          None => None
        }
      } else {
        None
      }
  }
}

///|
fn verified_event_of(fields : Fields, date_only : Bool) -> Verification? {
  guard fields.text("by").bind(Actor::parse) is Some(by) else { return None }
  guard fields.text("at") is Some(at_text) else { return None }
  guard Instant::parse(at_text, date_only~) is Some(at) else { return None }
  Some({ by, at, at_text, })
}

///|
/// Valid `verified` events as a list. A single mapping is a list with one entry.
/// Events missing `by` or a valid RFC 3339 `at` are ignored (OKF v0.3, section 5.2).
pub fn Metadata::verified(
  self : Metadata,
  options~ : Options = Options::default(),
) -> Array[Verification] {
  self
  .mappings("verified")
  .iter()
  .filter_map(fields => verified_event_of(fields, options.date_only_instants))
  .collect()
}

///|
fn Metadata::generated_instant(self : Metadata, options : Options) -> Instant? {
  self
  .generated(options~)
  .bind(g => g.at)
  .bind(t => Instant::parse(t, date_only=options.date_only_instants))
}

///|
/// `verified` events that are current: `at >= generated.at`, or all valid events
/// when `generated.at` is absent (OKF v0.3, section 5.3).
pub fn Metadata::current_verifications(
  self : Metadata,
  options~ : Options = Options::default(),
) -> Array[Verification] {
  let events = self.verified(options~)
  match self.generated_instant(options) {
    Some(g) => events.filter(v => v.at >= g)
    None => events
  }
}

///|
/// Earlier `verified` events whose `at` is before `generated.at` (OKF v0.3, section 5.3).
pub fn Metadata::historical_verifications(
  self : Metadata,
  options~ : Options = Options::default(),
) -> Array[Verification] {
  guard self.generated_instant(options) is Some(g) else { return [] }
  self.verified(options~).filter(v => v.at < g)
}

///|
/// The trust tier, derived from current `verified` events only (OKF v0.3, section 5.3).
pub fn Metadata::trust_tier(
  self : Metadata,
  options~ : Options = Options::default(),
) -> TrustTier {
  let current = self.current_verifications(options~)
  if current.is_empty() {
    Unverified
  } else if current.any(v => v.by.is_human()) {
    HumanReviewed
  } else {
    MachineConfirmed
  }
}

///|
/// The written `status`, or `None` when it is absent.
pub fn Metadata::status(self : Metadata) -> Status? {
  match self.text("status") {
    Some(text) => Status::parse(text)
    None => None
  }
}

///|
/// The status after the default of `options` applies.
pub fn Metadata::effective_status(
  self : Metadata,
  options~ : Options = Options::default(),
) -> Status? {
  match self.status() {
    Some(status) => Some(status)
    None => options.status_default
  }
}

///|
/// The raw `superseded_by` path value (OKF v0.3, section 5.4).
pub fn Metadata::superseded_by(self : Metadata) -> String? {
  self.text("superseded_by")
}

///|
/// The raw `stale_after` text.
pub fn Metadata::stale_after(self : Metadata) -> String? {
  self.text("stale_after")
}

///|
/// The freshness of this concept at `now` (OKF v0.3, section 5.5).
/// Missing, null, empty-string and empty-list values mean `NoExpiry`; any other
/// non-timestamp value (including non-empty sequences and mappings) is
/// `Malformed`.
pub fn Metadata::freshness(
  self : Metadata,
  now : Instant,
  options~ : Options = Options::default(),
) -> Freshness {
  match self.get("stale_after") {
    None | Some(Null) => NoExpiry
    Some(Scalar(text)) =>
      if text.length() == 0 {
        NoExpiry
      } else {
        match Instant::parse(text, date_only=options.date_only_instants) {
          Some(limit) => if now >= limit { Stale(limit) } else { Fresh(limit) }
          None => Malformed(text)
        }
      }
    Some(Seq(items)) if items.is_empty() => NoExpiry
    Some(Seq(_)) => {
      let raw = match self.raw_text("stale_after") {
        Some(t) if t.length() > 0 => t
        _ => ""
      }
      Malformed(raw)
    }
    Some(Mapping(_)) => {
      let raw = match self.raw_text("stale_after") {
        Some(t) if t.length() > 0 => t
        _ => ""
      }
      Malformed(raw)
    }
  }
}

///|
/// True when `now` is at or after `stale_after`, or when `stale_after` is
/// malformed. A malformed `stale_after` is never treated as fresh (OKF v0.3,
/// sections 5.5 and 11.2).
pub fn Metadata::is_stale(
  self : Metadata,
  now : Instant,
  options~ : Options = Options::default(),
) -> Bool {
  match self.freshness(now, options~) {
    Stale(_) | Malformed(_) => true
    NoExpiry | Fresh(_) => false
  }
}

///|
pub fn Metadata::runtime(self : Metadata) -> String? {
  self.text("runtime")
}

///|
/// Valid `parameters` entries of an Attested Computation. Entries missing
/// `name` or `type` are ignored (OKF v0.3, sections 10.2 and 11.2).
pub fn Metadata::parameters(self : Metadata) -> Array[Parameter] {
  self
  .mappings("parameters")
  .iter()
  .filter_map(fields => {
    match (fields.text("name"), fields.text("type")) {
      (Some(name), Some(type_)) =>
        Some({
          name,
          type_,
          required: fields.bool("required").unwrap_or(false),
        })
      _ => None
    }
  })
  .collect()
}

///|
pub fn Metadata::computation(self : Metadata) -> String? {
  self.text("computation")
}

///|
pub fn Metadata::executor(self : Metadata) -> Executor? {
  match self.mappings("executor") {
    [fields, ..] =>
      Some({
        resource: fields.text("resource"),
        receipt: ReadOnlyArray::from_array(fields.texts("receipt")),
      })
    [] => None
  }
}

///|
/// The `attester.resource` of an Attested Computation.
pub fn Metadata::attester(self : Metadata) -> String? {
  match self.mappings("attester") {
    [fields, ..] => fields.text("resource")
    [] => None
  }
}

///|
/// The keys that OKF v0.3 defines for concepts.
pub let okf_concept_keys : ReadOnlyArray[String] = [
  "type", "title", "description", "resource", "tags", "sources", "usage_window",
  "generated", "verified", "status", "superseded_by", "stale_after", "runtime", "parameters",
  "computation", "executor", "attester",
]

///|
/// The keys that OKF v0.3 defines for the bundle-root `index.md` (section 8.1).
pub let okf_bundle_keys : ReadOnlyArray[String] = [
  "okf_version", "title", "description", "license",
]

///|
pub extend Instant with Eq::{not_equal, equal}

///|
pub extend Instant with Compare::{op_lt, op_le, op_ge, compare, op_gt}

///|
pub extend Instant with Hash::{hash, hash_combine}

///|
pub extend Instant with @debug.Debug::{to_repr}

///|
pub extend Status with Eq::{not_equal, equal}

///|
pub extend Status with @debug.Debug::{to_repr}

///|
pub extend Actor with Eq::{not_equal, equal}

///|
pub extend Actor with @debug.Debug::{to_repr}

///|
pub extend Source with Eq::{not_equal, equal}

///|
pub extend Source with @debug.Debug::{to_repr}

///|
pub extend UsageWindow with Eq::{not_equal, equal}

///|
pub extend UsageWindow with @debug.Debug::{to_repr}

///|
pub extend Attribution with Eq::{not_equal, equal}

///|
pub extend Attribution with @debug.Debug::{to_repr}

///|
pub extend Verification with Eq::{not_equal, equal}

///|
pub extend Verification with @debug.Debug::{to_repr}

///|
pub extend TrustTier with Eq::{not_equal, equal}

///|
pub extend TrustTier with Compare::{op_lt, op_le, op_ge, compare, op_gt}

///|
pub extend TrustTier with @debug.Debug::{to_repr}

///|
pub extend Parameter with Eq::{not_equal, equal}

///|
pub extend Parameter with @debug.Debug::{to_repr}

///|
pub extend Executor with Eq::{not_equal, equal}

///|
pub extend Executor with @debug.Debug::{to_repr}

///|
pub extend UnknownStatus with Eq::{not_equal, equal}

///|
pub extend UnknownStatus with Hash::{hash, hash_combine}

///|
pub extend UnknownStatus with @debug.Debug::{to_repr}

///|
pub extend UnknownStatus with Show::{output}

///|
pub extend Freshness with Eq::{not_equal, equal}

///|
pub extend Freshness with @debug.Debug::{to_repr}