///|
let ns_per_sec_big : @bigint.BigInt = @bigint.BigInt::from_int64(1_000_000_000L)

///|
let int64_min_big : @bigint.BigInt = @bigint.BigInt::from_int64(
    -9223372036854775807L,
  ) -
  @bigint.BigInt::from_int(1)

///|
let int64_max_big : @bigint.BigInt = @bigint.BigInt::from_int64(
  9223372036854775807L,
)

///|
fn is_leap_year(y : Int64) -> Bool {
  (y % 4L == 0L && y % 100L != 0L) || y % 400L == 0L
}

///|
fn days_in_month(y : Int64, m : Int32) -> Int32 {
  match m {
    1 | 3 | 5 | 7 | 8 | 10 | 12 => 31
    4 | 6 | 9 | 11 => 30
    2 => if is_leap_year(y) { 29 } else { 28 }
    _ => 30
  }
}

///|
/// Howard Hinnant's exact O(1) proleptic Gregorian days-since-1970-01-01.
fn days_from_civil(year : Int64, month : Int32, day : Int32) -> Int64 {
  let y = if month <= 2 { year - 1L } else { year }
  let era = (if y >= 0L { y } else { y - 399L }) / 400L
  let yoe = y - era * 400L
  let m = month.to_int64()
  let d = day.to_int64()
  let doy = (153L * (if m > 2L { m - 3L } else { m + 9L }) + 2L) / 5L + d - 1L
  let doe = yoe * 365L + yoe / 4L - yoe / 100L + doy
  era * 146097L + doe - 719468L
}

///|
/// Inverse of `days_from_civil`: returns `(year, month 1..12, day 1..31)`.
fn civil_from_days(z_in : Int64) -> (Int64, Int32, Int32) {
  let z = z_in + 719468L
  let era = (if z >= 0L { z } else { z - 146096L }) / 146097L
  let doe = z - era * 146097L
  let yoe = (doe - doe / 1460L + doe / 36524L - doe / 146096L) / 365L
  let y0 = yoe + era * 400L
  let doy = doe - (365L * yoe + yoe / 4L - yoe / 100L)
  let mp = (5L * doy + 2L) / 153L
  let d = (doy - (153L * mp + 2L) / 5L + 1L).to_int()
  let m = (if mp < 10L { mp + 3L } else { mp - 9L }).to_int()
  let y = if m <= 2 { y0 + 1L } else { y0 }
  (y, m, d)
}

///|
/// Returns weekday `0 = Sunday .. 6 = Saturday` for `days` since 1970-01-01
/// (1970-01-01 was Thursday = 4).
fn weekday_from_days(days : Int64) -> Int32 {
  let w = ((days + 4L) % 7L + 7L) % 7L
  w.to_int()
}

///|
fn weekday_name(w : Int32) -> String {
  match w {
    0 => "Sunday"
    1 => "Monday"
    2 => "Tuesday"
    3 => "Wednesday"
    4 => "Thursday"
    5 => "Friday"
    _ => "Saturday"
  }
}

///|
fn weekday_short_name(w : Int32) -> String {
  match w {
    0 => "Sun"
    1 => "Mon"
    2 => "Tue"
    3 => "Wed"
    4 => "Thu"
    5 => "Fri"
    _ => "Sat"
  }
}

///|
fn month_name(m : Int32) -> String {
  match m {
    1 => "January"
    2 => "February"
    3 => "March"
    4 => "April"
    5 => "May"
    6 => "June"
    7 => "July"
    8 => "August"
    9 => "September"
    10 => "October"
    11 => "November"
    _ => "December"
  }
}

///|
fn month_short_name(m : Int32) -> String {
  match m {
    1 => "Jan"
    2 => "Feb"
    3 => "Mar"
    4 => "Apr"
    5 => "May"
    6 => "Jun"
    7 => "Jul"
    8 => "Aug"
    9 => "Sep"
    10 => "Oct"
    11 => "Nov"
    _ => "Dec"
  }
}

///|
fn nth_weekday_of_month(
  year : Int64,
  month : Int32,
  target_wd : Int32,
  nth : Int32,
) -> Int32 {
  let first_days = days_from_civil(year, month, 1)
  let first_wd = weekday_from_days(first_days)
  let delta = (target_wd - first_wd + 7) % 7
  1 + delta + (nth - 1) * 7
}

///|
fn last_weekday_of_month(
  year : Int64,
  month : Int32,
  target_wd : Int32,
) -> Int32 {
  let dim = days_in_month(year, month)
  let last_days = days_from_civil(year, month, dim)
  let last_wd = weekday_from_days(last_days)
  let delta = (last_wd - target_wd + 7) % 7
  dim - delta
}

///|
/// US DST rule (1967-2006 and 2007+): returns true if `utc_sec` falls inside DST
/// for a US timezone with standard offset `std_offset_sec`.
fn is_us_dst(utc_sec : Int64, std_offset_sec : Int64) -> Bool {
  let approx_days = floor_div_i64(utc_sec + std_offset_sec, 86400L)
  let (year, _, _) = civil_from_days(approx_days)
  if year < 1967L {
    return false
  }
  let (start_month, start_day, end_month, end_day) = if year >= 2007L {
    (
      3,
      nth_weekday_of_month(year, 3, 0, 2),
      11,
      nth_weekday_of_month(year, 11, 0, 1),
    )
  } else if year >= 1987L {
    (
      4,
      nth_weekday_of_month(year, 4, 0, 1),
      10,
      last_weekday_of_month(year, 10, 0),
    )
  } else {
    (
      4,
      last_weekday_of_month(year, 4, 0),
      10,
      last_weekday_of_month(year, 10, 0),
    )
  }
  // Transitions at 02:00 local standard time -> DST starts; 02:00 local DST (= 01:00 std) -> ends.
  let dst_start_utc = days_from_civil(year, start_month, start_day) * 86400L +
    2L * 3600L -
    std_offset_sec
  let dst_end_utc = days_from_civil(year, end_month, end_day) * 86400L +
    1L * 3600L -
    std_offset_sec
  utc_sec >= dst_start_utc && utc_sec < dst_end_utc
}

///|
/// EU DST rule (1996+): last Sunday of March 01:00 UTC to last Sunday of Oct 01:00 UTC.
fn is_eu_dst(utc_sec : Int64) -> Bool {
  let (year, _, _) = civil_from_days(floor_div_i64(utc_sec, 86400L))
  if year < 1981L {
    return false
  }
  let start_day = last_weekday_of_month(year, 3, 0)
  let end_day = last_weekday_of_month(year, 10, 0)
  let start_utc = days_from_civil(year, 3, start_day) * 86400L + 3600L
  let end_utc = days_from_civil(year, 10, end_day) * 86400L + 3600L
  utc_sec >= start_utc && utc_sec < end_utc
}

///|
fn floor_div_i64(a : Int64, b : Int64) -> Int64 {
  let q = a / b
  let r = a % b
  if r != 0L && (r < 0L) != (b < 0L) {
    q - 1L
  } else {
    q
  }
}

///|
fn floor_mod_i64(a : Int64, b : Int64) -> Int64 {
  let r = a % b
  if r < 0L {
    r + b
  } else {
    r
  }
}

///|
/// Splits exact `Int64` Unix nanoseconds into `(utc_sec, sub_ns 0..999_999_999)`.
fn split_unix_ns(ns : Int64) -> (Int64, Int32) {
  let mut sec = ns / 1_000_000_000L
  let mut rem = ns % 1_000_000_000L
  if rem < 0L {
    sec -= 1L
    rem += 1_000_000_000L
  }
  (sec, rem.to_int())
}

///|
/// Resolves a pure timezone name (UTC, empty, Local, fixed offset, or embedded
/// IANA zone) to `(offset_seconds, zone_abbr)` at `utc_sec`.
fn resolve_tz_offset(
  tz : String,
  utc_sec : Int64,
) -> Result[(Int64, String), String] {
  match tz {
    "" | "UTC" | "Etc/UTC" | "GMT" | "Etc/GMT" | "Local" => Ok((0L, "UTC"))
    "America/Los_Angeles" =>
      if is_us_dst(utc_sec, -8L * 3600L) {
        Ok((-7L * 3600L, "PDT"))
      } else {
        Ok((-8L * 3600L, "PST"))
      }
    "America/Denver" =>
      if is_us_dst(utc_sec, -7L * 3600L) {
        Ok((-6L * 3600L, "MDT"))
      } else {
        Ok((-7L * 3600L, "MST"))
      }
    "America/Chicago" =>
      if is_us_dst(utc_sec, -6L * 3600L) {
        Ok((-5L * 3600L, "CDT"))
      } else {
        Ok((-6L * 3600L, "CST"))
      }
    "America/New_York" =>
      if is_us_dst(utc_sec, -5L * 3600L) {
        Ok((-4L * 3600L, "EDT"))
      } else {
        Ok((-5L * 3600L, "EST"))
      }
    "Europe/London" =>
      if is_eu_dst(utc_sec) {
        Ok((3600L, "BST"))
      } else {
        Ok((0L, "GMT"))
      }
    "Europe/Berlin" | "Europe/Paris" | "Europe/Amsterdam" | "Europe/Rome" =>
      if is_eu_dst(utc_sec) {
        Ok((7200L, "CEST"))
      } else {
        Ok((3600L, "CET"))
      }
    "Asia/Kolkata" | "Asia/Calcutta" => Ok((5L * 3600L + 1800L, "IST"))
    "Asia/Shanghai" | "Asia/Hong_Kong" | "Asia/Singapore" =>
      Ok((8L * 3600L, "CST"))
    "Asia/Tokyo" => Ok((9L * 3600L, "JST"))
    "Australia/Sydney" => Ok((10L * 3600L, "AEST"))
    _ => {
      // Fixed numeric offset: +HH:MM, -HH:MM, +HHMM, -HHMM
      if tz.length() == 6 || tz.length() == 5 {
        let s0 = tz.code_unit_at(0).to_int()
        if s0 == 0x2B || s0 == 0x2D {
          let sign = if s0 == 0x2D { -1L } else { 1L }
          let (h_str, m_str) = if tz.length() == 6 &&
            tz.code_unit_at(3).to_int() == 0x3A {
            (
              tz.unsafe_substring(start=1, end=3),
              tz.unsafe_substring(start=4, end=6),
            )
          } else if tz.length() == 5 {
            (
              tz.unsafe_substring(start=1, end=3),
              tz.unsafe_substring(start=3, end=5),
            )
          } else {
            return Err("unknown time zone \{tz}")
          }
          if parse_2digits(h_str) is Some(hh) &&
            parse_2digits(m_str) is Some(mm) &&
            hh < 24 &&
            mm < 60 {
            return Ok(
              (sign * (hh.to_int64() * 3600L + mm.to_int64() * 60L), tz),
            )
          }
        }
      }
      Err("unknown time zone \{tz}")
    }
  }
}

///|
fn parse_2digits(s : String) -> Int32? {
  if s.length() != 2 {
    return None
  }
  let c0 = s.code_unit_at(0).to_int()
  let c1 = s.code_unit_at(1).to_int()
  if !is_ascii_digit(c0) || !is_ascii_digit(c1) {
    return None
  }
  Some((c0 - 0x30) * 10 + (c1 - 0x30))
}

///|
/// Unpacks an OPA `ns` or `[ns, tz]` time argument.
fn extract_ns_and_tz(arg : @value.Value) -> Result[(Int64, String), String] {
  match arg {
    Number(d) =>
      match d.to_int64() {
        Some(ns) => Ok((ns, "UTC"))
        None =>
          if d.is_integer() {
            Err("timestamp too big")
          } else {
            Err("operand must be integer nanoseconds")
          }
      }
    Array(items) => {
      if items.length() != 2 {
        return Err("expected [ns, tz] array of length 2")
      }
      guard items[0] is Number(d) else {
        return Err("first element must be number")
      }
      guard d.to_int64() is Some(ns) else { return Err("timestamp too big") }
      guard items[1] is String(tz) else {
        return Err("second element must be timezone string")
      }
      Ok((ns, tz))
    }
    _ => Err("operand must be number or [number, string]")
  }
}

///|
priv struct LocalDateTime {
  year : Int64
  month : Int32
  day : Int32
  hour : Int32
  minute : Int32
  second : Int32
  nanos : Int32
  weekday : Int32
  offset_sec : Int64
  zone_abbr : String
}

///|
fn unix_ns_to_local(ns : Int64, tz : String) -> Result[LocalDateTime, String] {
  let (utc_sec, sub_ns) = split_unix_ns(ns)
  let (offset_sec, zone_abbr) = match resolve_tz_offset(tz, utc_sec) {
    Ok(v) => v
    Err(e) => return Err(e)
  }
  let local_sec = utc_sec + offset_sec
  let days = floor_div_i64(local_sec, 86400L)
  let sod = floor_mod_i64(local_sec, 86400L).to_int()
  let (year, month, day) = civil_from_days(days)
  let hour = sod / 3600
  let minute = sod % 3600 / 60
  let second = sod % 60
  let weekday = weekday_from_days(days)
  Ok({
    year,
    month,
    day,
    hour,
    minute,
    second,
    nanos: sub_ns,
    weekday,
    offset_sec,
    zone_abbr,
  })
}

///|
/// Converts `(year, month, day, hour, minute, second, nanos, offset_sec)` to
/// exact `Int64` Unix nanoseconds, checking OPA's `time outside of valid range`.
fn civil_to_unix_ns(
  year : Int64,
  month : Int32,
  day : Int32,
  hour : Int32,
  minute : Int32,
  second : Int32,
  nanos : Int32,
  offset_sec : Int64,
) -> Result[Int64, String] {
  let days = days_from_civil(year, month, day)
  let sec_big = @bigint.BigInt::from_int64(days) *
    @bigint.BigInt::from_int64(86400L) +
    @bigint.BigInt::from_int64(
      hour.to_int64() * 3600L + minute.to_int64() * 60L + second.to_int64(),
    ) -
    @bigint.BigInt::from_int64(offset_sec)
  let ns_big = sec_big * ns_per_sec_big + @bigint.BigInt::from_int(nanos)
  if ns_big < int64_min_big || ns_big > int64_max_big {
    return Err("time outside of valid range")
  }
  Ok(ns_big.to_int64())
}

///|
fn resolve_named_layout(layout : String) -> String {
  match layout {
    "ANSIC" => "Mon Jan _2 15:04:05 2006"
    "UnixDate" => "Mon Jan _2 15:04:05 MST 2006"
    "RubyDate" => "Mon Jan 02 15:04:05 -0700 2006"
    "RFC822" => "02 Jan 06 15:04 MST"
    "RFC822Z" => "02 Jan 06 15:04 -0700"
    "RFC850" => "Monday, 02-Jan-06 15:04:05 MST"
    "RFC1123" => "Mon, 02 Jan 2006 15:04:05 MST"
    "RFC1123Z" => "Mon, 02 Jan 2006 15:04:05 -0700"
    "RFC3339" => "2006-01-02T15:04:05Z07:00"
    "RFC3339Nano" => "2006-01-02T15:04:05.999999999Z07:00"
    "Kitchen" => "3:04PM"
    "Stamp" => "Jan _2 15:04:05"
    "StampMilli" => "Jan _2 15:04:05.000"
    "StampMicro" => "Jan _2 15:04:05.000000"
    "StampNano" => "Jan _2 15:04:05.000000000"
    _ => layout
  }
}

///|
fn pad_zero_int(val : Int64, width : Int32) -> String {
  let neg = val < 0L
  let abs_s = (if neg { -val } else { val }).to_string()
  let buf = StringBuilder()
  if neg {
    buf.write_char('-')
  }
  let mut pad = width - abs_s.length()
  while pad > 0 {
    buf.write_char('0')
    pad -= 1
  }
  buf.write_string(abs_s)
  buf.to_string()
}

///|
fn pad_space_int(val : Int32, width : Int32) -> String {
  let s = val.to_string()
  let buf = StringBuilder()
  let mut pad = width - s.length()
  while pad > 0 {
    buf.write_char(' ')
    pad -= 1
  }
  buf.write_string(s)
  buf.to_string()
}

///|
fn format_tz_offset(
  offset_sec : Int64,
  colon : Bool,
  z_for_utc : Bool,
) -> String {
  if z_for_utc && offset_sec == 0L {
    return "Z"
  }
  let sign = if offset_sec < 0L { "-" } else { "+" }
  let abs_sec = if offset_sec < 0L { -offset_sec } else { offset_sec }
  let hh = abs_sec / 3600L
  let mm = abs_sec % 3600L / 60L
  if colon {
    "\{sign}\{pad_zero_int(hh, 2)}:\{pad_zero_int(mm, 2)}"
  } else {
    "\{sign}\{pad_zero_int(hh, 2)}\{pad_zero_int(mm, 2)}"
  }
}

///|
/// Pure Go reference-time layout formatter (`time.format`).
fn format_go_time_layout(dt : LocalDateTime, raw_layout : String) -> String {
  let layout = resolve_named_layout(raw_layout)
  let buf = StringBuilder()
  let n = layout.length()
  let mut i = 0
  while i < n {
    let rest = layout.unsafe_substring(start=i, end=n)
    if rest.has_prefix("2006") {
      buf.write_string(pad_zero_int(dt.year, 4))
      i += 4
    } else if rest.has_prefix("January") {
      buf.write_string(month_name(dt.month))
      i += 7
    } else if rest.has_prefix("Jan") {
      buf.write_string(month_short_name(dt.month))
      i += 3
    } else if rest.has_prefix("Monday") {
      buf.write_string(weekday_name(dt.weekday))
      i += 6
    } else if rest.has_prefix("Mon") {
      buf.write_string(weekday_short_name(dt.weekday))
      i += 3
    } else if rest.has_prefix("Z07:00") {
      buf.write_string(format_tz_offset(dt.offset_sec, true, true))
      i += 6
    } else if rest.has_prefix("Z0700") {
      buf.write_string(format_tz_offset(dt.offset_sec, false, true))
      i += 5
    } else if rest.has_prefix("-07:00") {
      buf.write_string(format_tz_offset(dt.offset_sec, true, false))
      i += 6
    } else if rest.has_prefix("-0700") {
      buf.write_string(format_tz_offset(dt.offset_sec, false, false))
      i += 5
    } else if rest.has_prefix("-07") {
      let sign = if dt.offset_sec < 0L { "-" } else { "+" }
      let abs_h = (if dt.offset_sec < 0L {
          -dt.offset_sec
        } else {
          dt.offset_sec
        }) /
        3600L
      buf.write_string("\{sign}\{pad_zero_int(abs_h, 2)}")
      i += 3
    } else if rest.has_prefix("MST") {
      buf.write_string(dt.zone_abbr)
      i += 3
    } else if rest.has_prefix("15") {
      buf.write_string(pad_zero_int(dt.hour.to_int64(), 2))
      i += 2
    } else if rest.has_prefix("01") {
      buf.write_string(pad_zero_int(dt.month.to_int64(), 2))
      i += 2
    } else if rest.has_prefix("02") {
      buf.write_string(pad_zero_int(dt.day.to_int64(), 2))
      i += 2
    } else if rest.has_prefix("_2") {
      buf.write_string(pad_space_int(dt.day, 2))
      i += 2
    } else if rest.has_prefix("03") {
      let h12 = if dt.hour % 12 == 0 { 12 } else { dt.hour % 12 }
      buf.write_string(pad_zero_int(h12.to_int64(), 2))
      i += 2
    } else if rest.has_prefix("04") {
      buf.write_string(pad_zero_int(dt.minute.to_int64(), 2))
      i += 2
    } else if rest.has_prefix("05") {
      buf.write_string(pad_zero_int(dt.second.to_int64(), 2))
      i += 2
    } else if rest.has_prefix("06") {
      buf.write_string(pad_zero_int(floor_mod_i64(dt.year, 100L), 2))
      i += 2
    } else if rest.has_prefix("PM") {
      buf.write_string(if dt.hour >= 12 { "PM" } else { "AM" })
      i += 2
    } else if rest.has_prefix("pm") {
      buf.write_string(if dt.hour >= 12 { "pm" } else { "am" })
      i += 2
    } else if rest.has_prefix(".0") || rest.has_prefix(".9") {
      let ch_tok = layout.code_unit_at(i + 1).to_int()
      let mut j = i + 1
      while j < n && layout.code_unit_at(j).to_int() == ch_tok {
        j += 1
      }
      let width = j - (i + 1)
      let ns_str = pad_zero_int(dt.nanos.to_int64(), 9)
      let take = if width < 9 { width } else { 9 }
      let slice = ns_str.unsafe_substring(start=0, end=take)
      if ch_tok == 0x30 {
        // Fixed-width trailing zeros (.000)
        buf.write_char('.')
        buf.write_string(slice)
      } else {
        // Optional trailing zeros trimmed (.999999999)
        let mut end = slice.length()
        while end > 0 && slice.code_unit_at(end - 1).to_int() == 0x30 {
          end -= 1
        }
        if end > 0 {
          buf.write_char('.')
          buf.write_string(slice.unsafe_substring(start=0, end~))
        }
      }
      i = j
    } else if rest.has_prefix("1") {
      buf.write_string(dt.month.to_string())
      i += 1
    } else if rest.has_prefix("2") {
      buf.write_string(dt.day.to_string())
      i += 1
    } else if rest.has_prefix("3") {
      let h12 = if dt.hour % 12 == 0 { 12 } else { dt.hour % 12 }
      buf.write_string(h12.to_string())
      i += 1
    } else if rest.has_prefix("4") {
      buf.write_string(dt.minute.to_string())
      i += 1
    } else if rest.has_prefix("5") {
      buf.write_string(dt.second.to_string())
      i += 1
    } else {
      buf.write_char(Int32::unsafe_to_char(layout.code_unit_at(i).to_int()))
      i += 1
    }
  }
  buf.to_string()
}

///|
fn parse_int_digits(
  s : String,
  pos : Int32,
  min_digits : Int32,
  max_digits : Int32,
) -> (Int32, Int32)? {
  let n = s.length()
  let mut j = pos
  let mut val = 0
  while j < n &&
        j - pos < max_digits &&
        is_ascii_digit(s.code_unit_at(j).to_int()) {
    val = val * 10 + (s.code_unit_at(j).to_int() - 0x30)
    j += 1
  }
  if j - pos < min_digits {
    None
  } else {
    Some((val, j))
  }
}

///|
fn parse_frac_nanos(
  s : String,
  pos : Int32,
  fixed_width : Int32?,
) -> Result[(Int32, Int32), String] {
  let n = s.length()
  if pos >= n || s.code_unit_at(pos).to_int() != 0x2E {
    match fixed_width {
      Some(_) => return Err("missing fractional seconds")
      None => return Ok((0, pos))
    }
  }
  let mut j = pos + 1
  let mut digits = 0
  let mut ns = 0
  let mut scale = 100_000_000
  while j < n && is_ascii_digit(s.code_unit_at(j).to_int()) {
    let d = s.code_unit_at(j).to_int() - 0x30
    if scale > 0 {
      ns += d * scale
      scale = scale / 10
    }
    digits += 1
    j += 1
  }
  if digits == 0 || digits > 9 {
    return Err("invalid fractional seconds")
  }
  match fixed_width {
    Some(w) if digits != w => return Err("fractional seconds width mismatch")
    _ => ()
  }
  Ok((ns, j))
}

///|
fn parse_month_name_at(s : String, pos : Int32, full : Bool) -> (Int32, Int32)? {
  let rest = s.unsafe_substring(start=pos, end=s.length()).to_lower()
  for m in 1..<=12 {
    let target = (if full { month_name(m) } else { month_short_name(m) }).to_lower()
    if rest.has_prefix(target) {
      return Some((m, pos + target.length()))
    }
  }
  None
}

///|
fn parse_weekday_name_at(s : String, pos : Int32, full : Bool) -> Int32? {
  let rest = s.unsafe_substring(start=pos, end=s.length()).to_lower()
  for w in 0..<7 {
    let target = (if full { weekday_name(w) } else { weekday_short_name(w) }).to_lower()
    if rest.has_prefix(target) {
      return Some(pos + target.length())
    }
  }
  None
}

///|
fn parse_tz_offset_at(
  s : String,
  pos : Int32,
  allow_z : Bool,
  require_colon : Bool,
) -> Result[(Int64, Int32), String] {
  let n = s.length()
  if pos >= n {
    return Err("missing timezone offset")
  }
  let c0 = s.code_unit_at(pos).to_int()
  if allow_z && (c0 == 0x5A || c0 == 0x7A) {
    return Ok((0L, pos + 1))
  }
  if c0 != 0x2B && c0 != 0x2D {
    return Err("invalid timezone offset")
  }
  let sign = if c0 == 0x2D { -1L } else { 1L }
  guard parse_int_digits(s, pos + 1, 2, 2) is Some((hh, after_h)) else {
    return Err("invalid timezone hour")
  }
  let mut cur = after_h
  if require_colon {
    if cur >= n || s.code_unit_at(cur).to_int() != 0x3A {
      return Err("missing ':' in timezone offset")
    }
    cur += 1
  }
  guard parse_int_digits(s, cur, 2, 2) is Some((mm, after_m)) else {
    return Err("invalid timezone minute")
  }
  if hh > 23 || mm > 59 {
    return Err("timezone offset out of range")
  }
  Ok((sign * (hh.to_int64() * 3600L + mm.to_int64() * 60L), after_m))
}

///|
/// Pure Go reference-time layout parser (`time.parse_ns` and `time.parse_rfc3339_ns`).
fn parse_go_time_layout(
  raw_layout : String,
  value : String,
) -> Result[Int64, String] {
  let layout = resolve_named_layout(raw_layout)
  let mut li = 0
  let mut vi = 0
  let ln = layout.length()
  let vn = value.length()

  let mut year : Int64 = 0L
  let mut month : Int32 = 1
  let mut day : Int32 = 1
  let mut hour : Int32 = 0
  let mut minute : Int32 = 0
  let mut second : Int32 = 0
  let mut nanos : Int32 = 0
  let mut offset_sec : Int64 = 0L
  let mut is_pm : Bool? = None
  let mut used_12h = false

  while li < ln {
    let rest = layout.unsafe_substring(start=li, end=ln)
    if rest.has_prefix("2006") {
      guard parse_int_digits(value, vi, 4, 4) is Some((y, next_vi)) else {
        return Err("cannot parse year")
      }
      year = y.to_int64()
      li += 4
      vi = next_vi
    } else if rest.has_prefix("January") {
      guard parse_month_name_at(value, vi, true) is Some((m, next_vi)) else {
        return Err("cannot parse month")
      }
      month = m
      li += 7
      vi = next_vi
    } else if rest.has_prefix("Jan") {
      guard parse_month_name_at(value, vi, false) is Some((m, next_vi)) else {
        return Err("cannot parse month")
      }
      month = m
      li += 3
      vi = next_vi
    } else if rest.has_prefix("Monday") {
      guard parse_weekday_name_at(value, vi, true) is Some(next_vi) else {
        return Err("cannot parse weekday")
      }
      li += 6
      vi = next_vi
    } else if rest.has_prefix("Mon") {
      guard parse_weekday_name_at(value, vi, false) is Some(next_vi) else {
        return Err("cannot parse weekday")
      }
      li += 3
      vi = next_vi
    } else if rest.has_prefix("Z07:00") {
      match parse_tz_offset_at(value, vi, true, true) {
        Ok((off, next_vi)) => {
          offset_sec = off
          li += 6
          vi = next_vi
        }
        Err(e) => return Err(e)
      }
    } else if rest.has_prefix("Z0700") {
      match parse_tz_offset_at(value, vi, true, false) {
        Ok((off, next_vi)) => {
          offset_sec = off
          li += 5
          vi = next_vi
        }
        Err(e) => return Err(e)
      }
    } else if rest.has_prefix("-07:00") {
      match parse_tz_offset_at(value, vi, false, true) {
        Ok((off, next_vi)) => {
          offset_sec = off
          li += 6
          vi = next_vi
        }
        Err(e) => return Err(e)
      }
    } else if rest.has_prefix("-0700") {
      match parse_tz_offset_at(value, vi, false, false) {
        Ok((off, next_vi)) => {
          offset_sec = off
          li += 5
          vi = next_vi
        }
        Err(e) => return Err(e)
      }
    } else if rest.has_prefix("MST") {
      let start_z = vi
      while vi < vn {
        let zc = value.code_unit_at(vi).to_int()
        if (zc >= 0x41 && zc <= 0x5A) || (zc >= 0x61 && zc <= 0x7A) {
          vi += 1
        } else {
          break
        }
      }
      if vi == start_z {
        return Err("cannot parse timezone abbreviation")
      }
      let abbr = value.unsafe_substring(start=start_z, end=vi)
      offset_sec = match abbr {
        "UTC" | "GMT" => 0L
        "EST" => -5L * 3600L
        "EDT" => -4L * 3600L
        "CST" => -6L * 3600L
        "CDT" => -5L * 3600L
        "MST" => -7L * 3600L
        "MDT" => -6L * 3600L
        "PST" => -8L * 3600L
        "PDT" => -7L * 3600L
        "CET" => 3600L
        "CEST" => 7200L
        "IST" => 5L * 3600L + 1800L
        "JST" => 9L * 3600L
        _ => 0L
      }
      li += 3
    } else if rest.has_prefix("15") {
      guard parse_int_digits(value, vi, 2, 2) is Some((h, next_vi)) else {
        return Err("cannot parse hour")
      }
      hour = h
      li += 2
      vi = next_vi
    } else if rest.has_prefix("01") {
      guard parse_int_digits(value, vi, 2, 2) is Some((m, next_vi)) else {
        return Err("cannot parse month")
      }
      month = m
      li += 2
      vi = next_vi
    } else if rest.has_prefix("02") {
      guard parse_int_digits(value, vi, 2, 2) is Some((d, next_vi)) else {
        return Err("cannot parse day")
      }
      day = d
      li += 2
      vi = next_vi
    } else if rest.has_prefix("_2") {
      if vi < vn && value.code_unit_at(vi).to_int() == 0x20 {
        vi += 1
        guard parse_int_digits(value, vi, 1, 1) is Some((d, next_vi)) else {
          return Err("cannot parse day")
        }
        day = d
        vi = next_vi
      } else {
        guard parse_int_digits(value, vi, 1, 2) is Some((d, next_vi)) else {
          return Err("cannot parse day")
        }
        day = d
        vi = next_vi
      }
      li += 2
    } else if rest.has_prefix("03") {
      guard parse_int_digits(value, vi, 2, 2) is Some((h, next_vi)) else {
        return Err("cannot parse 12-hour")
      }
      hour = h
      used_12h = true
      li += 2
      vi = next_vi
    } else if rest.has_prefix("04") {
      guard parse_int_digits(value, vi, 2, 2) is Some((m, next_vi)) else {
        return Err("cannot parse minute")
      }
      minute = m
      li += 2
      vi = next_vi
    } else if rest.has_prefix("05") {
      guard parse_int_digits(value, vi, 2, 2) is Some((sec, next_vi)) else {
        return Err("cannot parse second")
      }
      second = sec
      li += 2
      vi = next_vi
      // Go `time.Parse` accepts optional `.digits` after `05` if the layout does
      // not explicitly specify `.0...` or `.9...`.
      let after_sec = layout.unsafe_substring(start=li, end=ln)
      if !after_sec.has_prefix(".0") && !after_sec.has_prefix(".9") {
        if vi < vn && value.code_unit_at(vi).to_int() == 0x2E {
          match parse_frac_nanos(value, vi, None) {
            Ok((fn_val, next_vi2)) => {
              nanos = fn_val
              vi = next_vi2
            }
            Err(e) => return Err(e)
          }
        }
      }
    } else if rest.has_prefix("06") {
      guard parse_int_digits(value, vi, 2, 2) is Some((y2, next_vi)) else {
        return Err("cannot parse 2-digit year")
      }
      year = if y2 >= 69 {
        (1900 + y2).to_int64()
      } else {
        (2000 + y2).to_int64()
      }
      li += 2
      vi = next_vi
    } else if rest.has_prefix("PM") || rest.has_prefix("pm") {
      if vi + 2 > vn {
        return Err("cannot parse AM/PM")
      }
      let tok = value.unsafe_substring(start=vi, end=vi + 2).to_upper()
      if tok == "PM" {
        is_pm = Some(true)
      } else if tok == "AM" {
        is_pm = Some(false)
      } else {
        return Err("cannot parse AM/PM")
      }
      li += 2
      vi += 2
    } else if rest.has_prefix(".0") || rest.has_prefix(".9") {
      let ch_tok = layout.code_unit_at(li + 1).to_int()
      let mut j = li + 1
      while j < ln && layout.code_unit_at(j).to_int() == ch_tok {
        j += 1
      }
      let width = j - (li + 1)
      let fixed = if ch_tok == 0x30 { Some(width) } else { None }
      match parse_frac_nanos(value, vi, fixed) {
        Ok((fn_val, next_vi)) => {
          nanos = fn_val
          li = j
          vi = next_vi
        }
        Err(e) => return Err(e)
      }
    } else if rest.has_prefix("1") {
      guard parse_int_digits(value, vi, 1, 2) is Some((m, next_vi)) else {
        return Err("cannot parse month")
      }
      month = m
      li += 1
      vi = next_vi
    } else if rest.has_prefix("2") {
      guard parse_int_digits(value, vi, 1, 2) is Some((d, next_vi)) else {
        return Err("cannot parse day")
      }
      day = d
      li += 1
      vi = next_vi
    } else if rest.has_prefix("3") {
      guard parse_int_digits(value, vi, 1, 2) is Some((h, next_vi)) else {
        return Err("cannot parse hour")
      }
      hour = h
      used_12h = true
      li += 1
      vi = next_vi
    } else if rest.has_prefix("4") {
      guard parse_int_digits(value, vi, 1, 2) is Some((m, next_vi)) else {
        return Err("cannot parse minute")
      }
      minute = m
      li += 1
      vi = next_vi
    } else if rest.has_prefix("5") {
      guard parse_int_digits(value, vi, 1, 2) is Some((sec, next_vi)) else {
        return Err("cannot parse second")
      }
      second = sec
      li += 1
      vi = next_vi
    } else {
      if vi >= vn || layout.code_unit_at(li) != value.code_unit_at(vi) {
        return Err("layout mismatch")
      }
      li += 1
      vi += 1
    }
  }
  if vi != vn {
    return Err("extra text in time value")
  }
  if used_12h {
    if hour < 1 || hour > 12 {
      return Err("12-hour out of range")
    }
    match is_pm {
      Some(true) => if hour < 12 { hour += 12 }
      Some(false) => if hour == 12 { hour = 0 }
      None => ()
    }
  }
  if month < 1 || month > 12 {
    return Err("month out of range")
  }
  if day < 1 || day > days_in_month(year, month) {
    return Err("day out of range")
  }
  if hour < 0 ||
    hour > 23 ||
    minute < 0 ||
    minute > 59 ||
    second < 0 ||
    second > 59 {
    return Err("time component out of range")
  }
  civil_to_unix_ns(year, month, day, hour, minute, second, nanos, offset_sec)
}

///|
/// Pure OPA `time.parse_duration_ns` supporting Go units (`ns`, `us`, `µs`,
/// `μs`, `ms`, `s`, `m`, `h`) plus OPA extended units (`d`, `w`, `y`).
fn parse_duration_ns_str(s : String) -> Result[Int64, String] {
  let n = s.length()
  if n == 0 {
    return Err("invalid duration \"\"")
  }
  let mut i = 0
  let mut neg = false
  let c0 = s.code_unit_at(0).to_int()
  if c0 == 0x2D {
    neg = true
    i += 1
  } else if c0 == 0x2B {
    i += 1
  }
  if i == n {
    return Err("invalid duration")
  }
  if s.unsafe_substring(start=i, end=n) == "0" {
    return Ok(0L)
  }
  let mut total = @bigint.BigInt::from_int(0)
  let ten = @bigint.BigInt::from_int(10)
  while i < n {
    // Parse integer and optional fractional digits
    let mut int_part = @bigint.BigInt::from_int(0)
    let mut frac_part = @bigint.BigInt::from_int(0)
    let mut frac_scale = @bigint.BigInt::from_int(1)
    let mut has_digits = false
    while i < n && is_ascii_digit(s.code_unit_at(i).to_int()) {
      has_digits = true
      int_part = int_part * ten +
        @bigint.BigInt::from_int(s.code_unit_at(i).to_int() - 0x30)
      i += 1
    }
    if i < n && s.code_unit_at(i).to_int() == 0x2E {
      i += 1
      while i < n && is_ascii_digit(s.code_unit_at(i).to_int()) {
        has_digits = true
        frac_part = frac_part * ten +
          @bigint.BigInt::from_int(s.code_unit_at(i).to_int() - 0x30)
        frac_scale = frac_scale * ten
        i += 1
      }
    }
    if !has_digits {
      return Err("invalid duration")
    }
    // Parse unit
    let u_start = i
    while i < n {
      let uc = s.code_unit_at(i).to_int()
      if is_ascii_digit(uc) || uc == 0x2E {
        break
      }
      i += 1
    }
    let unit = s.unsafe_substring(start=u_start, end=i)
    let unit_ns : Int64 = match unit {
      "ns" => 1L
      "us" | "µs" | "μs" => 1_000L
      "ms" => 1_000_000L
      "s" => 1_000_000_000L
      "m" => 60_000_000_000L
      "h" => 3_600_000_000_000L
      "d" => 86_400_000_000_000L
      "w" => 604_800_000_000_000L
      "y" => 31_536_000_000_000_000L
      _ => return Err("unknown unit \"\{unit}\" in duration")
    }
    let unit_big = @bigint.BigInt::from_int64(unit_ns)
    let part_ns = int_part * unit_big + frac_part * unit_big / frac_scale
    total = total + part_ns
  }
  let signed = if neg { -total } else { total }
  if signed < int64_min_big || signed > int64_max_big {
    return Err("duration overflow")
  }
  Ok(signed.to_int64())
}

///|
/// Go-compatible `AddDate(years, months, days)`: normalizes month overflow
/// (`year + floor((m - 1) / 12)`, `((m - 1) mod 12) + 1`) and rolls day overflow
/// into subsequent months via `days_from_civil(y, m, 1) + (day - 1) + add_days`.
fn add_date_ns(
  ns : Int64,
  add_years : Int64,
  add_months : Int64,
  add_days : Int64,
) -> Result[Int64, String] {
  let dt = match unix_ns_to_local(ns, "UTC") {
    Ok(v) => v
    Err(e) => return Err(e)
  }
  let raw_m = (dt.month - 1).to_int64() + add_months
  let year_carry = floor_div_i64(raw_m, 12L)
  let norm_m = floor_mod_i64(raw_m, 12L).to_int() + 1
  let norm_y = dt.year + add_years + year_carry
  // Roll over days just like Go's time.Date(norm_y, norm_m, dt.day + add_days, ...)
  let base_days = days_from_civil(norm_y, norm_m, 1) +
    (dt.day - 1).to_int64() +
    add_days
  let (fy, fm, fd) = civil_from_days(base_days)
  civil_to_unix_ns(fy, fm, fd, dt.hour, dt.minute, dt.second, dt.nanos, 0L)
}

///|
/// OPA's exact `time.diff(ns1, ns2)` returning `[years, months, days, hours, mins, secs]`.
fn diff_dates(
  ns1 : Int64,
  tz1 : String,
  ns2 : Int64,
  tz2 : String,
) -> Result[Array[Int64], String] {
  let (a_ns, a_tz, b_ns) = if ns1 <= ns2 {
    (ns1, tz1, ns2)
  } else {
    (ns2, tz2, ns1)
  }
  // Convert both instants into the earlier instant's timezone (matches Go/OPA).
  let d1 = match unix_ns_to_local(a_ns, a_tz) {
    Ok(v) => v
    Err(e) => return Err(e)
  }
  let d2 = match unix_ns_to_local(b_ns, a_tz) {
    Ok(v) => v
    Err(e) => return Err(e)
  }
  let mut years = d2.year - d1.year
  let mut months = (d2.month - d1.month).to_int64()
  let mut days = (d2.day - d1.day).to_int64()
  let mut hours = (d2.hour - d1.hour).to_int64()
  let mut mins = (d2.minute - d1.minute).to_int64()
  let mut secs = (d2.second - d1.second).to_int64()
  if secs < 0L {
    secs += 60L
    mins -= 1L
  }
  if mins < 0L {
    mins += 60L
    hours -= 1L
  }
  if hours < 0L {
    hours += 24L
    days -= 1L
  }
  if days < 0L {
    days += days_in_month(d1.year, d1.month).to_int64()
    months -= 1L
  }
  if months < 0L {
    months += 12L
    years -= 1L
  }
  Ok([years, months, days, hours, mins, secs])
}

///|
fn register_time_builtins(list : Array[(String, BuiltinEntry)]) -> Unit {
  add_fn(list, "time.now_ns", 0, fn(_, ctx) {
    Ok(
      Some(
        @value.Value::Number(
          @value.Decimal::from_bigint(ctx.clock().now().to_bigint()),
        ),
      ),
    )
  })

  add_fn(list, "time.parse_ns", 2, fn(args, _) {
    guard args[0] is String(layout) else {
      return Err(
        EvalFailure(name="time.parse_ns", message="operand 1 must be string"),
      )
    }
    guard args[1] is String(val) else {
      return Err(
        EvalFailure(name="time.parse_ns", message="operand 2 must be string"),
      )
    }
    match parse_go_time_layout(layout, val) {
      Ok(ns) => Ok(Some(@value.Value::Number(@value.Decimal::from_int64(ns))))
      Err(msg) => Err(EvalFailure(name="time.parse_ns", message=msg))
    }
  })

  add_fn(list, "time.parse_rfc3339_ns", 1, fn(args, _) {
    guard args[0] is String(val) else {
      return Err(
        EvalFailure(
          name="time.parse_rfc3339_ns",
          message="operand 1 must be string",
        ),
      )
    }
    match parse_go_time_layout("RFC3339Nano", val) {
      Ok(ns) => Ok(Some(@value.Value::Number(@value.Decimal::from_int64(ns))))
      Err(msg) => Err(EvalFailure(name="time.parse_rfc3339_ns", message=msg))
    }
  })

  add_fn(list, "time.parse_duration_ns", 1, fn(args, _) {
    guard args[0] is String(val) else {
      return Err(
        EvalFailure(
          name="time.parse_duration_ns",
          message="operand 1 must be string",
        ),
      )
    }
    match parse_duration_ns_str(val) {
      Ok(ns) => Ok(Some(@value.Value::Number(@value.Decimal::from_int64(ns))))
      Err(msg) => Err(EvalFailure(name="time.parse_duration_ns", message=msg))
    }
  })

  add_fn(list, "time.date", 1, fn(args, _) {
    let (ns, tz) = match extract_ns_and_tz(args[0]) {
      Ok(v) => v
      Err(msg) => return Err(EvalFailure(name="time.date", message=msg))
    }
    match unix_ns_to_local(ns, tz) {
      Ok(dt) =>
        Ok(
          Some(
            @value.Value::array([
              @value.Value::Number(@value.Decimal::from_int64(dt.year)),
              @value.Value::int(dt.month),
              @value.Value::int(dt.day),
            ]),
          ),
        )
      Err(msg) => Err(EvalFailure(name="time.date", message=msg))
    }
  })

  add_fn(list, "time.clock", 1, fn(args, _) {
    let (ns, tz) = match extract_ns_and_tz(args[0]) {
      Ok(v) => v
      Err(msg) => return Err(EvalFailure(name="time.clock", message=msg))
    }
    match unix_ns_to_local(ns, tz) {
      Ok(dt) =>
        Ok(
          Some(
            @value.Value::array([
              @value.Value::int(dt.hour),
              @value.Value::int(dt.minute),
              @value.Value::int(dt.second),
            ]),
          ),
        )
      Err(msg) => Err(EvalFailure(name="time.clock", message=msg))
    }
  })

  add_fn(list, "time.weekday", 1, fn(args, _) {
    let (ns, tz) = match extract_ns_and_tz(args[0]) {
      Ok(v) => v
      Err(msg) => return Err(EvalFailure(name="time.weekday", message=msg))
    }
    match unix_ns_to_local(ns, tz) {
      Ok(dt) => Ok(Some(@value.Value::String(weekday_name(dt.weekday))))
      Err(msg) => Err(EvalFailure(name="time.weekday", message=msg))
    }
  })

  add_fn(list, "time.add_date", 4, fn(args, _) {
    guard args[0] is Number(ns_d) && ns_d.to_int64() is Some(ns) else {
      return Err(
        EvalFailure(
          name="time.add_date",
          message="operand 1 must be integer nanoseconds",
        ),
      )
    }
    guard args[1] is Number(y_d) && y_d.to_int64() is Some(years) else {
      return Err(
        EvalFailure(
          name="time.add_date",
          message="operand 2 must be integer number",
        ),
      )
    }
    guard args[2] is Number(m_d) && m_d.to_int64() is Some(months) else {
      return Err(
        EvalFailure(
          name="time.add_date",
          message="operand 3 must be integer number",
        ),
      )
    }
    guard args[3] is Number(d_d) && d_d.to_int64() is Some(days) else {
      return Err(
        EvalFailure(
          name="time.add_date",
          message="operand 4 must be integer number",
        ),
      )
    }
    match add_date_ns(ns, years, months, days) {
      Ok(out) => Ok(Some(@value.Value::Number(@value.Decimal::from_int64(out))))
      Err(msg) => Err(EvalFailure(name="time.add_date", message=msg))
    }
  })

  add_fn(list, "time.diff", 2, fn(args, _) {
    let (ns1, tz1) = match extract_ns_and_tz(args[0]) {
      Ok(v) => v
      Err(msg) => return Err(EvalFailure(name="time.diff", message=msg))
    }
    let (ns2, tz2) = match extract_ns_and_tz(args[1]) {
      Ok(v) => v
      Err(msg) => return Err(EvalFailure(name="time.diff", message=msg))
    }
    match diff_dates(ns1, tz1, ns2, tz2) {
      Ok(parts) => {
        let out : Array[@value.Value] = []
        for p in parts {
          out.push(@value.Value::Number(@value.Decimal::from_int64(p)))
        }
        Ok(Some(@value.Value::array(out)))
      }
      Err(msg) => Err(EvalFailure(name="time.diff", message=msg))
    }
  })

  add_fn(list, "time.format", 1, fn(args, _) {
    let (ns, tz, layout) : (Int64, String, String) = match args[0] {
      Number(d) =>
        match d.to_int64() {
          Some(ns) => (ns, "UTC", "RFC3339Nano")
          None =>
            return Err(
              EvalFailure(name="time.format", message="timestamp too big"),
            )
        }
      Array(items) => {
        if items.length() < 1 || items.length() > 3 {
          return Err(
            EvalFailure(
              name="time.format",
              message="operand 1 array must have 1 to 3 elements",
            ),
          )
        }
        guard items[0] is Number(d) else {
          return Err(
            EvalFailure(
              name="time.format",
              message="first element must be number",
            ),
          )
        }
        guard d.to_int64() is Some(ns) else {
          return Err(
            EvalFailure(name="time.format", message="timestamp too big"),
          )
        }
        let tz = if items.length() >= 2 {
          guard items[1] is String(t) else {
            return Err(
              EvalFailure(
                name="time.format",
                message="second element must be string",
              ),
            )
          }
          t
        } else {
          "UTC"
        }
        let lay = if items.length() == 3 {
          guard items[2] is String(l) else {
            return Err(
              EvalFailure(
                name="time.format",
                message="third element must be string",
              ),
            )
          }
          l
        } else {
          "RFC3339Nano"
        }
        (ns, tz, lay)
      }
      _ =>
        return Err(
          EvalFailure(
            name="time.format",
            message="operand 1 must be number or array",
          ),
        )
    }
    match unix_ns_to_local(ns, tz) {
      Ok(dt) =>
        Ok(Some(@value.Value::String(format_go_time_layout(dt, layout))))
      Err(msg) => Err(EvalFailure(name="time.format", message=msg))
    }
  })
}