// RFC 3339 date-time parsing and UTC formatting backed by
// `moonbitstack/moondate` and bridged to `moonbitlang/x/time.ZonedDateTime`.

///|
fn is_ascii_digit(s : String, idx : Int32) -> Bool {
  let c = s.code_unit_at(idx).to_int()
  c >= 0x30 && c <= 0x39
}

///|
/// Strict RFC 3339 §5.6 lexical syntax check:
/// `YYYY-MM-DD (T|t| ) HH:MM:SS (. DIGIT+)? (Z|z| (+|-) HH:MM)`
fn is_strict_rfc3339_syntax(text : String) -> Bool {
  let len = text.length()
  if len < 20 {
    return false
  }
  // YYYY-MM-DD
  if !(is_ascii_digit(text, 0) &&
    is_ascii_digit(text, 1) &&
    is_ascii_digit(text, 2) &&
    is_ascii_digit(text, 3) &&
    text.code_unit_at(4).to_int() == 0x2D &&
    is_ascii_digit(text, 5) &&
    is_ascii_digit(text, 6) &&
    text.code_unit_at(7).to_int() == 0x2D &&
    is_ascii_digit(text, 8) &&
    is_ascii_digit(text, 9)) {
    return false
  }
  // Separator: 'T', 't', or ' '
  let sep = text.code_unit_at(10).to_int()
  if sep != 0x54 && sep != 0x74 && sep != 0x20 {
    return false
  }
  // HH:MM:SS
  if !(is_ascii_digit(text, 11) &&
    is_ascii_digit(text, 12) &&
    text.code_unit_at(13).to_int() == 0x3A &&
    is_ascii_digit(text, 14) &&
    is_ascii_digit(text, 15) &&
    text.code_unit_at(16).to_int() == 0x3A &&
    is_ascii_digit(text, 17) &&
    is_ascii_digit(text, 18)) {
    return false
  }
  let mut idx : Int32 = 19
  // Optional fractional seconds: '.' 1*DIGIT
  if idx < len && text.code_unit_at(idx).to_int() == 0x2E {
    idx += 1
    let frac_start = idx
    while idx < len && is_ascii_digit(text, idx) {
      idx += 1
    }
    if idx == frac_start {
      return false
    }
  }
  if idx >= len {
    return false
  }
  let tz = text.code_unit_at(idx).to_int()
  if tz == 0x5A || tz == 0x7A {
    // 'Z' or 'z' must be the final character
    idx + 1 == len
  } else if tz == 0x2B || tz == 0x2D {
    // (+|-)HH:MM exact 6 characters
    idx + 6 == len &&
    is_ascii_digit(text, idx + 1) &&
    is_ascii_digit(text, idx + 2) &&
    text.code_unit_at(idx + 3).to_int() == 0x3A &&
    is_ascii_digit(text, idx + 4) &&
    is_ascii_digit(text, idx + 5)
  } else {
    false
  }
}

///|
/// Parse an RFC 3339 date-time string into a UTC `@time.ZonedDateTime`.
pub fn rfc3339_parse(
  text : String,
  ctx? : @cjson.DecodeContext,
) -> @time.ZonedDateTime raise @cjson.JsonDecodeError {
  let err_ctx = match ctx {
    Some(c) => c
    None => root_decode_context()
  }
  fn fail_parse() -> @time.ZonedDateTime raise @cjson.JsonDecodeError {
    raise err_ctx.error("invalid RFC 3339 date-time: \"\{text}\"")
  }

  if !is_strict_rfc3339_syntax(text) {
    return fail_parse()
  }
  let moment = @moondate.parse(text[:]) catch { _ => return fail_parse() }
  match moment {
    @moondate.Zoned(date~, time~, ..) => {
      if date.year < 0 || date.year > 9999 {
        return fail_parse()
      }
      match moment.instant() {
        Some((raw_epoch_sec, raw_nano)) => {
          let (epoch_sec, nano) = if time.second == 60 {
            // RFC 3339 §5.7: leap seconds are only valid at UTC 23:59:60
            // (which moondate rolls to 00:00:00 of the next UTC day); clamp
            // to POSIX 23:59:59.999999999 so it stays before the next second.
            let mod_day = (raw_epoch_sec % 86400L + 86400L) % 86400L
            if mod_day != 0L {
              return fail_parse()
            }
            (raw_epoch_sec - 1L, 999_999_999)
          } else {
            (raw_epoch_sec, raw_nano)
          }
          @time.ZonedDateTime::from_unix_second(
            epoch_sec,
            nanosecond=nano,
            zone=@time.utc_zone,
          ) catch {
            _ => fail_parse()
          }
        }
        None => fail_parse()
      }
    }
    _ => fail_parse()
  }
}

///|
/// Format a `@time.ZonedDateTime` as a canonical UTC RFC 3339 string
/// (`YYYY-MM-DDTHH:MM:SSZ` or `YYYY-MM-DDTHH:MM:SS.Z`).
pub fn rfc3339_format_utc(dt : @time.ZonedDateTime) -> String {
  let moment = @moondate.Moment::of_epoch(
    dt.to_unix_second(),
    nano=dt.nanosecond(),
    zone=@moondate.Utc,
  )
  moment.layout(@moondate.RFC3339Nano)
}