///|
/// A field of a timestamp text.
#derive(Eq, Debug)
pub(all) enum TimestampField {
  Year
  Month
  Day
  Hour
  Minute
  Second
  OffsetHour
  OffsetMinute
}

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

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

///|
/// The rule of a timestamp that a text or a value breaks.
#derive(Eq, Debug)
pub(all) enum TimestampRule {
  /// The text is not in the form `YYYY-MM-DDTHH:MM:SS[.fffffff](Z|+HH:MM|-HH:MM)`.
  Syntax
  /// A field is outside its range, for example the month 13 or the day 30 in
  /// February.
  FieldOutOfRange(TimestampField)
  /// The fraction of a second has more than 7 digits. The precision of a
  /// timestamp is 100 nanoseconds, the tick of .NET.
  TooPrecise
  /// A nanosecond value is negative, is 10^9 or more, or is not a multiple of 100.
  InvalidNanoseconds(Int32)
  /// The instant is before 0001-01-01T00:00:00Z or after
  /// 9999-12-31T23:59:59.9999999Z, the range of .NET `DateTime`.
  OutOfRange
}

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

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

///|
/// A text or a value that is not a valid timestamp.
#derive(Eq, Debug)
pub suberror TimestampError {
  /// The input `input` breaks the rule `rule`.
  InvalidTimestamp(input~ : String, rule~ : TimestampRule)
}

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

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

///|
/// Text for people that describes the fault.
pub fn TimestampError::message(self : TimestampError) -> String {
  let InvalidTimestamp(input~, rule~) = self
  let reason = match rule {
    Syntax =>
      "use the form YYYY-MM-DDTHH:MM:SS[.fffffff] with Z or an offset +HH:MM"
    FieldOutOfRange(field) => "the field \{field_label(field)} is out of range"
    TooPrecise => "the fraction of a second has more than 7 digits"
    InvalidNanoseconds(value) =>
      "the nanoseconds \{value} are not a multiple of 100 from 0 to 999999900"
    OutOfRange =>
      "the instant is outside 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.9999999Z"
  }
  "Invalid timestamp \{input.escape()}: \{reason}"
}

///|
fn field_label(field : TimestampField) -> String {
  match field {
    Year => "year"
    Month => "month"
    Day => "day"
    Hour => "hour"
    Minute => "minute"
    Second => "second"
    OffsetHour => "offset hour"
    OffsetMinute => "offset minute"
  }
}

///|
/// An instant in UTC with a precision of 100 nanoseconds, from
/// 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.9999999Z. The JSON encoding
/// writes it as ISO 8601 text in UTC, as System.Text.Json writes a UTC
/// `DateTime`.
#derive(Eq, Compare, Hash)
pub struct Timestamp {
  priv seconds : Int64
  priv nanoseconds : Int32
}

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

///|
pub extend Timestamp with Compare::{compare}

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

///|
/// Unix seconds of 0001-01-01T00:00:00Z.
let min_seconds : Int64 = -62135596800L

///|
/// Unix seconds of 9999-12-31T23:59:59Z.
let max_seconds : Int64 = 253402300799L

///|
/// The timestamp `seconds` after the Unix epoch plus `nanoseconds`. The
/// nanoseconds must be a multiple of 100 from 0 to 999999900.
pub fn Timestamp::from_unix(
  seconds : Int64,
  nanoseconds~ : Int32 = 0,
) -> Timestamp raise TimestampError {
  let input = "\{seconds}s \{nanoseconds}ns"
  guard nanoseconds >= 0 &&
    nanoseconds < 1_000_000_000 &&
    nanoseconds % 100 == 0 else {
    raise InvalidTimestamp(input~, rule=InvalidNanoseconds(nanoseconds))
  }
  guard seconds >= min_seconds && seconds <= max_seconds else {
    raise InvalidTimestamp(input~, rule=OutOfRange)
  }
  { seconds, nanoseconds, }
}

///|
/// The seconds after the Unix epoch, rounded down.
pub fn Timestamp::unix_seconds(self : Timestamp) -> Int64 {
  self.seconds
}

///|
/// The nanoseconds after `unix_seconds`, a multiple of 100.
pub fn Timestamp::nanoseconds(self : Timestamp) -> Int32 {
  self.nanoseconds
}

///|
/// Parse an RFC 3339 timestamp with a `Z` or a numeric offset, for example
/// `2026-12-01T10:15:00Z` or `2026-12-01T11:15:00.5+01:00`. A text with no
/// offset is an error, because it does not give one instant.
pub fn Timestamp::parse(text : String) -> Timestamp raise TimestampError {
  let chars = text.iter().collect()
  let syntax = () => InvalidTimestamp(input=text, rule=Syntax)
  let digits = (start : Int32, count : Int32) => {
    guard start + count <= chars.length() else { raise syntax() }
    let mut value = 0
    for i in start..<(start + count) {
      guard is_ascii_digit(chars[i]) else { raise syntax() }
      value = value * 10 + (chars[i].to_int() - '0'.to_int())
    }
    value
  }
  let expect = (at : Int32, char : Char) => {
    guard at < chars.length() && chars[at] == char else { raise syntax() }
  }
  let field = (value : Int32, low : Int32, high : Int32, field : TimestampField) => {
    guard value >= low && value <= high else {
      raise InvalidTimestamp(input=text, rule=FieldOutOfRange(field))
    }
  }
  let year = digits(0, 4)
  expect(4, '-')
  let month = digits(5, 2)
  expect(7, '-')
  let day = digits(8, 2)
  expect(10, 'T')
  let hour = digits(11, 2)
  expect(13, ':')
  let minute = digits(14, 2)
  expect(16, ':')
  let second = digits(17, 2)
  field(year, 1, 9999, Year)
  field(month, 1, 12, Month)
  field(day, 1, days_in_month(year, month), Day)
  field(hour, 0, 23, Hour)
  field(minute, 0, 59, Minute)
  field(second, 0, 59, Second)
  let mut at = 19
  let mut nanoseconds = 0
  if at < chars.length() && chars[at] == '.' {
    at += 1
    let start = at
    while at < chars.length() && is_ascii_digit(chars[at]) {
      at += 1
    }
    let count = at - start
    guard count >= 1 else { raise syntax() }
    guard count <= 7 else {
      raise InvalidTimestamp(input=text, rule=TooPrecise)
    }
    let mut scale = 1
    for _ in count..<9 {
      scale *= 10
    }
    nanoseconds = digits(start, count) * scale
  }
  guard at < chars.length() else { raise syntax() }
  let offset_seconds = match chars[at] {
    'Z' => {
      at += 1
      0
    }
    '+' | '-' as sign => {
      let offset_hour = digits(at + 1, 2)
      expect(at + 3, ':')
      let offset_minute = digits(at + 4, 2)
      field(offset_hour, 0, 23, OffsetHour)
      field(offset_minute, 0, 59, OffsetMinute)
      at += 6
      let value = offset_hour * 3600 + offset_minute * 60
      if sign == '-' {
        -value
      } else {
        value
      }
    }
    _ => raise syntax()
  }
  guard at == chars.length() else { raise syntax() }
  let seconds = days_from_civil(year, month, day) * 86400L +
    (hour * 3600 + minute * 60 + second - offset_seconds).to_int64()
  guard seconds >= min_seconds && seconds <= max_seconds else {
    raise InvalidTimestamp(input=text, rule=OutOfRange)
  }
  { seconds, nanoseconds, }
}

///|
/// The ISO 8601 text in UTC: `YYYY-MM-DDTHH:MM:SS`, a fraction with no trailing
/// zeros when the nanoseconds are not 0, and `Z`.
pub impl Show for Timestamp with fn output(self, logger) {
  let days = floor_div(self.seconds, 86400L)
  let of_day = (self.seconds - days * 86400L).to_int()
  let (year, month, day) = civil_from_days(days)
  logger.write_string(pad(year, 4))
  logger.write_char('-')
  logger.write_string(pad(month, 2))
  logger.write_char('-')
  logger.write_string(pad(day, 2))
  logger.write_char('T')
  logger.write_string(pad(of_day / 3600, 2))
  logger.write_char(':')
  logger.write_string(pad(of_day % 3600 / 60, 2))
  logger.write_char(':')
  logger.write_string(pad(of_day % 60, 2))
  if self.nanoseconds != 0 {
    let mut fraction = pad(self.nanoseconds, 9)
    while fraction.has_suffix("0") {
      fraction = fraction[:fraction.length() - 1].to_owned()
    }
    logger.write_char('.')
    logger.write_string(fraction)
  }
  logger.write_char('Z')
}

///|
pub extend Timestamp with Show::{output, to_string}

///|
pub impl @debug.Debug for Timestamp with fn to_repr(self) {
  @debug.Repr(self.to_string())
}

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

///|
fn pad(value : Int32, width : Int32) -> String {
  let text = value.to_string()
  let zeros = width - text.length()
  if zeros <= 0 {
    text
  } else {
    "0".repeat(zeros) + text
  }
}

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

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

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

///|
/// Days from 1970-01-01 to the civil date (H. Hinnant, "chrono-Compatible
/// Low-Level Date Algorithms"). The year is from 1 to 9999.
fn days_from_civil(year : Int32, month : Int32, day : Int32) -> Int64 {
  let y = (if month <= 2 { year - 1 } else { year }).to_int64()
  let era = y / 400L
  let yoe = y - era * 400L
  let mp = (if month > 2 { month - 3 } else { month + 9 }).to_int64()
  let doy = (153L * mp + 2L) / 5L + day.to_int64() - 1L
  let doe = yoe * 365L + yoe / 4L - yoe / 100L + doy
  era * 146097L + doe - 719468L
}

///|
/// The civil date of a day count from 1970-01-01, for days from year 1 to 9999.
fn civil_from_days(days : Int64) -> (Int32, Int32, Int32) {
  let z = days + 719468L
  let era = z / 146097L
  let doe = z - era * 146097L
  let yoe = (doe - doe / 1460L + doe / 36524L - doe / 146096L) / 365L
  let doy = doe - (365L * yoe + yoe / 4L - yoe / 100L)
  let mp = (5L * doy + 2L) / 153L
  let day = (doy - (153L * mp + 2L) / 5L + 1L).to_int()
  let month = (if mp < 10L { mp + 3L } else { mp - 9L }).to_int()
  let year = (yoe + era * 400L).to_int() + (if month <= 2 { 1 } else { 0 })
  (year, month, day)
}