///|
/// A half-open interval of UTC sample labels, with optional bounds.
struct TimeWindow {
  from : SampleTime?
  until : SampleTime?
}

///|
/// Validate the dates and order of the bounds. Equal bounds select nothing.
pub fn TimeWindow::new(
  from? : SampleTime,
  until? : SampleTime,
) -> TimeWindow raise WaveformError {
  if from is Some(lo) {
    lo.validate()
  }
  if until is Some(hi) {
    hi.validate()
    if from is Some(lo) && hi < lo {
      raise InvalidWaveform("time window end precedes its start")
    }
  }
  { from, until, }
}

///|
priv enum HeaderSelection {
  EmptyAt(Int32)
  WholeRecord
  NeedsTiming(SampleTime, start_matches~ : Bool)
}

///|
/// Find the first index at or after `bound`. Sample labels are monotone,
/// including ties after rounding and a record's own explicit leap second.
fn lower_bound(
  start : SampleTime,
  rate : Double,
  count : Int32,
  first : Int32,
  bound : SampleTime,
) -> Int32 {
  if bound <= start {
    return 0
  }
  let mut low = first.max(1)
  let mut high = count
  while low < high {
    let mid = low + (high - low) / 2
    // The caller validated the start and rate, and mid is positive. An
    // unrepresentable timestamp therefore lies beyond every valid bound.
    let before = (time_at(start, rate, mid.to_int64()) < bound) catch {
      InvalidWaveform(_) => false
    }
    if before {
      low = mid + 1
    } else {
      high = mid
    }
  }
  low
}

///|
/// The parser has already checked the record's civil fields. Comparing labels
/// also works for wire years outside the calendar supported by `time_at`.
fn TimeWindow::select_header(
  self : TimeWindow,
  record : @mseed.Record,
) -> HeaderSelection raise WaveformError {
  if self.from is Some(lo) && self.until == Some(lo) {
    return EmptyAt(0)
  }
  let start = SampleTime::from_header(record.header)
  if self.until is Some(hi) && start >= hi {
    return EmptyAt(0)
  }
  let start_matches = !(self.from is Some(lo) && start < lo)
  let count = record.sample_count
  if count <= 0 {
    guard count == 0 && record.payload.is_empty() else {
      raise InvalidWaveform(
        "cannot select by time when the sample count is unknown",
      )
    }
    guard record.version == 2 ||
      (record.encoding == 0 && record.header.rate == 0.0) else {
      raise InvalidWaveform(
        "a header-only miniSEED 3 record must use zero encoding and rate",
      )
    }
    return if start_matches { WholeRecord } else { EmptyAt(0) }
  }
  if count == 1 {
    return if start_matches { WholeRecord } else { EmptyAt(1) }
  }
  if start_matches && self.until is None {
    return WholeRecord
  }
  NeedsTiming(start, start_matches~)
}

///|
fn TimeWindow::timed_indices(
  self : TimeWindow,
  record : @mseed.Record,
  start : SampleTime,
) -> (Int32, Int32) raise WaveformError {
  start.validate()
  let rate = record.header.rate
  guard rate.is_finite() && rate != 0.0 else {
    raise InvalidWaveform(
      "cannot select multiple samples by time when the sample rate is zero or nonfinite",
    )
  }
  let count = record.sample_count
  let first = match self.from {
    None => 0
    Some(lo) => lower_bound(start, rate, count, 0, lo)
  }
  let end = match self.until {
    None => count
    Some(hi) => lower_bound(start, rate, count, first, hi)
  }
  (first, end)
}

///|
/// Return the zero-based half-open sample range of a parsed record. Header-only
/// records have no sample indices. A bound after the last sample gives the
/// insertion index at the end. Samples beyond year 9999 follow every valid bound.
/// Sample order alone can establish a full or empty range. Other multi-sample
/// ranges require a known rate and a start in years 1 through 9999.
pub fn TimeWindow::indices(
  self : TimeWindow,
  record : @mseed.Record,
) -> (Int32, Int32) raise WaveformError {
  match self.select_header(record) {
    EmptyAt(i) => (i, i)
    WholeRecord => (0, record.sample_count)
    NeedsTiming(start, ..) => self.timed_indices(record, start)
  }
}

///|
/// Test whether a parsed record has a selected sample or a selected
/// header-only timestamp. With both bounds omitted, accept every parsed
/// record, including opaque payloads with unspecified timing. For a known
/// positive count, a matching start proves the record contains a sample.
pub fn TimeWindow::contains_record(
  self : TimeWindow,
  record : @mseed.Record,
) -> Bool raise WaveformError {
  if self.from is None && self.until is None {
    return true
  }
  match self.select_header(record) {
    EmptyAt(_) => false
    WholeRecord | NeedsTiming(_, start_matches=true) => true
    NeedsTiming(start, start_matches=false) => {
      let (first, end) = self.timed_indices(record, start)
      first < end
    }
  }
}