///|
/// Record metadata. A negative rate denotes seconds per sample.
#derive(Eq, @debug.Debug)
pub(all) struct Header {
  source_id : String
  year : Int32
  day : Int32
  hour : Int32
  minute : Int32
  second : Int32
  nanosecond : Int32
  rate : Double
  flags : Int32
  publication : Int32
  extra : Bytes
}

///|
/// An individual record with its encoded payload. The endianness applies to
/// the payload. The record header may have used a different byte order.
#derive(Eq, @debug.Debug)
pub(all) struct Record {
  header : Header
  version : Int32
  encoding : Int32
  sample_count : Int32
  little_endian : Bool
  payload : Bytes
  byte_length : Int32
  /// Optional miniSEED 2 blockettes whose bodies are not represented in Header.
  unmapped_blockettes : Array[Int32]
}

///|
#derive(@debug.Debug)
pub(all) suberror RecordError {
  BadHeader(String)
  BadLength(String)
  BadChecksum(UInt32, UInt32)
}

///|
pub impl Show for RecordError with fn output(self, logger) {
  match self {
    BadHeader(msg) | BadLength(msg) => logger.write_string(msg)
    BadChecksum(stored, computed) =>
      logger.write_string(
        "CRC-32C mismatch (stored 0x\{stored.to_string(radix=16)}, computed 0x\{computed.to_string(radix=16)})",
      )
  }
}

///|
const MAX_RECORD_BYTES : Int32 = 16_777_216

///|
fn days_in_year(year : Int32) -> Int32 {
  if year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) {
    366
  } else {
    365
  }
}

///|
fn validate_time(header : Header) -> Unit raise RecordError {
  guard header.year >= 0 &&
    header.year <= 65535 &&
    header.day >= 1 &&
    header.day <= days_in_year(header.year) &&
    header.hour >= 0 &&
    header.hour <= 23 &&
    header.minute >= 0 &&
    header.minute <= 59 &&
    header.second >= 0 &&
    header.second <= 60 &&
    header.nanosecond >= 0 &&
    header.nanosecond < 1_000_000_000 else {
    raise BadHeader("invalid UTC start time")
  }
}

///|
/// Returns the first record's size as soon as its framing fields have arrived.
/// An incomplete prefix returns None. Individual records are limited to 16 MiB.
pub fn record_length(prefix : Bytes) -> Int32? raise RecordError {
  if prefix.is_empty() {
    return None
  }
  if prefix[0] != b'M' {
    return scan_v2(prefix, framing_only=true).map(layout => layout.size)
  }
  if prefix.length() >= 2 && prefix[1] != b'S' {
    raise BadHeader("invalid miniSEED 3 signature")
  }
  if prefix.length() >= 3 && prefix[2] != 3 {
    raise BadHeader("unsupported miniSEED format version")
  }
  if prefix.length() < 40 {
    None
  } else {
    Some(v3_length(prefix))
  }
}

///|
/// Parses exactly one record. A miniSEED 3 record must pass its CRC-32C check.
pub fn parse(data : Bytes) -> Record raise RecordError {
  if !data.is_empty() && data[0] != b'M' {
    return parse_v2(data)
  }
  guard record_length(data) is Some(length) else {
    raise BadLength("incomplete miniSEED record header")
  }
  guard data.length() == length else {
    raise BadLength(
      "expected \{length} bytes for one record, received \{data.length()}",
    )
  }
  parse_v3(data)
}