///|
/// One calendar event, mapped from a `VEVENT` component (RFC 5545 §3.6.1).
///
/// This is a typed *view* over the component tree, not a replacement for it:
/// unknown properties stay in the `Component` and nothing is dropped. Every
/// field is optional because RFC 5545 makes every `VEVENT` property optional;
/// a property that is *present but malformed* raises [`@text.ParseError`]
/// instead of being silently skipped, so a broken feed is loud rather than
/// subtly wrong. A property that is simply absent is `None` — absence is not
/// breakage. An event that states no `DTEND` ends where its `DURATION`
/// says it does (RFC 5545 §3.8.5.3 offers `DURATION` as the alternative
/// end); carrying both is the spec violation it names and raises.
///
/// Recurrence dates and overrides are retained for the rrule package's
/// series union, exclusions, and override merge.
#derive(Debug)
pub struct Event {
  uid : String?
  summary : String?
  location : String?
  description : String?
  dtstart : IcalDateTime?
  dtend : IcalDateTime?
  /// The raw `RRULE` value exactly as it appeared on the wire; the rule is
  /// parsed and expanded by later milestones (S2/S3/S8).
  rrule : String?
  /// The series instance this event overrides, when this is an override
  /// event rather than a series definition.
  recurrence_id : IcalDateTime?
  /// `RANGE=THISANDFUTURE` on RECURRENCE-ID, when present.
  recurrence_range : String?
  /// Event status, notably `CANCELLED` on an overridden instance.
  status : String?
  /// Every `EXDATE` value across repeated property lines, in wire order.
  exdates : Array[IcalDateTime]
  /// Every DATE or DATE-TIME RDATE in wire order. PERIOD is unsupported.
  rdates : Array[IcalDateTime]
}

///|
pub extend Event with @moonbitlang/core/debug.Debug::{to_repr}

///|
/// An all-day event is one whose `DTSTART` is a DATE value.
pub fn Event::all_day(self : Event) -> Bool {
  match self.dtstart {
    Some(dt) => dt.all_day
    None => false
  }
}

///|
pub impl Show for Event with fn output(self, logger) {
  let uid = self.uid.unwrap_or("-")
  let summary = self.summary.unwrap_or("")
  match self.dtstart {
    Some(dt) => logger.write_string("VEVENT \{uid}: \{summary} @ \{dt}")
    None => logger.write_string("VEVENT \{uid}: \{summary}")
  }
}

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

///|
/// The `VEVENT` children of this component as typed events, in wire order.
///
/// `zones` resolves `TZID=` parameters. Pass the table the way [`parse_events`]
/// builds it — [`ZoneTable::with_builtin`] over [`build_zone_table`] applied to
/// the same feed — so unsupported feed declarations shadow UTC defaults.
///
/// Only direct children are considered: a `VEVENT` nests directly inside a
/// `VCALENDAR`, never deeper.
pub fn Component::events(
  self : Component,
  zones~ : ZoneTable,
) -> Array[Event] raise {
  let out : Array[Event] = []
  for child in self.children {
    if child.kind == "VEVENT" {
      out.push(event_from_component(child, zones))
    }
  }
  out
}

///|
/// Map this component when it is a VEVENT; other component kinds return None.
/// Only properties of this event are interpreted, so unrelated unsupported
/// time zones or event properties do not prevent a selective query.
pub fn Component::event(self : Component, zones~ : ZoneTable) -> Event? raise {
  if self.kind == "VEVENT" {
    Some(event_from_component(self, zones))
  } else {
    None
  }
}

///|
/// Parse a complete iCalendar document into its lossless component trees.
/// Unknown components and properties remain available for inspection and
/// serialization.
pub fn parse_calendar(input : String) -> Array[Component] raise {
  parse_components(@text.unfold(input))
}

///|
/// Parse a whole iCalendar feed into typed events: unfold the text, build
/// the component tree, register fixed zones and unsupported declarations,
/// then map every `VEVENT`. Referenced unsupported zones raise.
///
/// # Example
/// ```mbt nocheck
/// fn test_example() raise {
///   let events = @model.parse_events(
///     "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nSUMMARY:Sync\r\nEND:VEVENT\r\nEND:VCALENDAR",
///   )
///   assert_eq(events.length(), 1)
///   assert_eq(events[0].summary, Some("Sync"))
/// }
/// ```
pub fn parse_events(input : String) -> Array[Event] raise {
  let roots = parse_calendar(input)
  let zones = ZoneTable::with_builtin(build_zone_table(roots))
  let out : Array[Event] = []
  for root in roots {
    for event in root.events(zones~) {
      out.push(event)
    }
  }
  out
}

///|
/// Map one `VEVENT` component onto an [`Event`]. A malformed date property
/// raises; a missing one stays `None`.
fn event_from_component(
  component : Component,
  zones : ZoneTable,
) -> Event raise {
  // RFC 5545 §3.6.1's eventprop ABNF marks DTSTART ("in any case, it
  // MUST NOT occur more than once"), UID and RECURRENCE-ID
  // ("OPTIONAL, but MUST NOT occur more than once") at MUST level — the
  // first-occurrence readers would silently pick one line and drop the
  // rest, so these are loud. RRULE is only "SHOULD NOT occur more than
  // once" and DTEND/DURATION carry no once-annotation (§3.8.2.2 only
  // forbids carrying both) — duplicates there stay tolerated with the
  // first line winning, the same reading dateutil and icalendar give.
  for name in ["DTSTART", "UID", "RECURRENCE-ID"] {
    let lines = component.properties_named(name)
    if lines.length() > 1 {
      raise @text.ParseError::BadLine(
        line_no=lines[1].line_no,
        line=name,
        message="VEVENT carries more than one \{name}",
      )
    }
  }
  let dtstart = component
    .property("DTSTART")
    .map(line => parse_date_time(line, zones))
  // The end: DTEND as stated, or DTSTART plus DURATION when the event
  // spells its length instead. RFC 5545 §3.8.5.3 forbids carrying both —
  // which end applies would be a guess, so the violation is loud.
  let dtend_line = component.property("DTEND")
  let duration_line = component.property("DURATION")
  if dtend_line is Some(_) && duration_line is Some(_) {
    raise @text.ParseError::BadLine(
      line_no=duration_line.unwrap().line_no,
      line=duration_line.unwrap().value,
      message="VEVENT carries both DTEND and DURATION",
    )
  }
  // §3.8.2.2: the DTEND value type must be the same as DTSTART's, and a
  // DURATION on an all-day event must be whole days or weeks — a mixed
  // pair would make the event's own extent a guess between the two
  // calendars' conventions.
  match (dtstart, dtend_line) {
    (Some(start), Some(line)) => {
      let end = parse_date_time(line, zones)
      if end.all_day != start.all_day {
        raise @text.ParseError::BadLine(
          line_no=line.line_no,
          line=line.value,
          message="DTEND value type must agree with DTSTART",
        )
      }
    }
    _ => ()
  }
  match (dtstart, duration_line) {
    (Some(start), Some(line)) =>
      if start.all_day && line.value.contains("T") {
        raise @text.ParseError::BadLine(
          line_no=line.line_no,
          line=line.value,
          message="DURATION on a DATE-valued event must be days or weeks",
        )
      }
    _ => ()
  }
  let dtend = match dtend_line {
    Some(line) => Some(parse_date_time(line, zones))
    None =>
      match (duration_line, dtstart) {
        (Some(line), Some(start)) => {
          let seconds = parse_duration(
            line.value,
            line_no=line.line_no,
            raw=line.value,
          )
          Some(start.shift_seconds(seconds))
        }
        _ => None
      }
  }
  let recurrence_id = component
    .property("RECURRENCE-ID")
    .map(line => parse_date_time(line, zones))
  let recurrence_range = component
    .property("RECURRENCE-ID")
    .bind(line => line.param("RANGE"))
  let exdates = recurrence_dates(component, "EXDATE", zones, dtstart~)
  let rdates = recurrence_dates(component, "RDATE", zones, dtstart~)
  {
    uid: text_of(component, "UID"),
    summary: text_of(component, "SUMMARY"),
    location: text_of(component, "LOCATION"),
    description: text_of(component, "DESCRIPTION"),
    dtstart,
    dtend,
    rrule: component.property("RRULE").map(line => line.value),
    recurrence_id,
    recurrence_range,
    status: text_of(component, "STATUS"),
    exdates,
    rdates,
  }
}

///|
fn recurrence_dates(
  component : Component,
  name : String,
  zones : ZoneTable,
  dtstart~ : IcalDateTime?,
) -> Array[IcalDateTime] raise {
  let out : Array[IcalDateTime] = []
  for line in component.properties_named(name) {
    let kind = line.param("VALUE").map(v => v.to_upper()).unwrap_or("DATE-TIME")
    if kind == "PERIOD" {
      raise @text.ParseError::BadLine(
        line_no=line.line_no,
        line=line.value,
        message="unsupported \{name} VALUE=PERIOD",
      )
    }
    if kind != "DATE" && kind != "DATE-TIME" {
      raise @text.ParseError::BadLine(
        line_no=line.line_no,
        line=line.value,
        message="unsupported \{name} VALUE: \{kind}",
      )
    }
    for value in split_values(line.value) {
      // Materialize the default so bare dates cannot masquerade as DATE-TIME.
      if kind == "DATE-TIME" && value.length() == 8 {
        raise @text.ParseError::BadLine(
          line_no=line.line_no,
          line=value,
          message="\{name} VALUE=DATE-TIME with a date value",
        )
      }
      let date = parse_date_time_value(
        value,
        zones,
        tzid=line.param("TZID"),
        value_is_date=kind == "DATE",
      )
      // The domain-agreement check runs here, where the offending line's
      // number is still in hand — the old post-parse loop could only
      // report "line 0" because the values had left their lines behind.
      match dtstart {
        Some(start) =>
          if date.all_day != start.all_day ||
            date.is_floating() != start.is_floating() {
            raise @text.ParseError::BadLine(
              line_no=line.line_no,
              line=date.to_string(),
              message="recurrence date value type must agree with DTSTART",
            )
          }
        None => ()
      }
      out.push(date)
    }
  }
  out
}

///|
/// Unescaped display text of the first property with this name, if any.
fn text_of(component : Component, name : String) -> String? {
  match component.property(name) {
    Some(line) => Some(@text.unescape_value(line.value))
    None => None
  }
}

///|
/// Split a comma-separated property value into its parts, as `EXDATE` and
/// `RDATE` lists are written.
fn split_values(value : String) -> Array[String] {
  let parts : Array[String] = []
  for part in value.to_string_view().split(",".to_string_view()) {
    parts.push(part.to_owned())
  }
  parts
}