// Core canonical intent domain types: artifacts, requirement deltas, task
// checklists, monotonic reading packets, workflow items, and diagnostics.

///|
/// Role of a document inside a canonical reading packet. Built-in roles cover
/// standard SDD artifacts while `Custom` keeps the axis open for additional
/// adapters.
#derive(Eq, Debug)
pub(all) enum ArtifactRole {
  Proposal
  Design
  SpecDelta
  Tasks
  MainSpec
  Custom(AdapterId)
}

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

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

///|
/// Human-readable label for an `ArtifactRole`.
pub fn ArtifactRole::label(self : ArtifactRole) -> String {
  match self {
    Proposal => "Proposal"
    Design => "Design"
    SpecDelta => "Spec Delta"
    Tasks => "Tasks"
    MainSpec => "Specification"
    Custom(id) => id.as_str()
  }
}

///|
/// Change operation for a requirement entry in a delta specification.
#derive(Eq, Debug)
pub(all) enum RequirementDeltaKind {
  Added
  Modified
  Removed
  Renamed
}

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

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

///|
/// A single Gherkin-style acceptance scenario attached to a requirement.
/// `when_text` and `then_text` hold free prose clauses without structural
/// character restrictions.
#derive(Eq, Debug)
pub struct ScenarioEntry {
  priv title : IntentTitle
  priv when_text : String
  priv then_text : String
}

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

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

///|
/// Constructs an immutable `ScenarioEntry`.
pub fn ScenarioEntry::ScenarioEntry(
  title~ : IntentTitle,
  when_text~ : String,
  then_text~ : String,
) -> ScenarioEntry {
  { title, when_text, then_text, }
}

///|
/// Title of the scenario.
pub fn ScenarioEntry::title(self : ScenarioEntry) -> IntentTitle {
  self.title
}

///|
/// `WHEN` clause prose of the scenario.
pub fn ScenarioEntry::when_text(self : ScenarioEntry) -> String {
  self.when_text
}

///|
/// `THEN` clause prose of the scenario.
pub fn ScenarioEntry::then_text(self : ScenarioEntry) -> String {
  self.then_text
}

///|
/// A requirement delta extracted from a specification or delta document.
/// `text` holds arbitrary EARS requirement prose.
#derive(Eq, Debug)
pub struct RequirementDelta {
  priv kind : RequirementDeltaKind
  priv title : IntentTitle
  priv text : String
  priv scenarios : ReadOnlyArray[ScenarioEntry]
}

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

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

///|
/// Constructs an immutable `RequirementDelta`.
pub fn RequirementDelta::RequirementDelta(
  kind~ : RequirementDeltaKind,
  title~ : IntentTitle,
  text~ : String,
  scenarios~ : Array[ScenarioEntry] = [],
) -> RequirementDelta {
  { kind, title, text, scenarios: ReadOnlyArray::from_array(scenarios), }
}

///|
/// Delta kind (`Added`, `Modified`, `Removed`, or `Renamed`).
pub fn RequirementDelta::kind(self : RequirementDelta) -> RequirementDeltaKind {
  self.kind
}

///|
/// Requirement heading title.
pub fn RequirementDelta::title(self : RequirementDelta) -> IntentTitle {
  self.title
}

///|
/// Requirement EARS prose text.
pub fn RequirementDelta::text(self : RequirementDelta) -> String {
  self.text
}

///|
/// Immutable list of scenarios for this requirement.
pub fn RequirementDelta::scenarios(
  self : RequirementDelta,
) -> ReadOnlyArray[ScenarioEntry] {
  self.scenarios
}

///|
/// One checklist task item extracted from a `tasks.md` or equivalent artifact.
#derive(Eq, Debug)
pub struct TaskItem {
  priv code : String
  priv label : IntentTitle
  priv completed : Bool
}

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

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

///|
/// Constructs an immutable `TaskItem`. `code` is an optional task reference
/// such as `"1.1"` (or empty when unnumbered).
pub fn TaskItem::TaskItem(
  code~ : String = "",
  label~ : IntentTitle,
  completed~ : Bool,
) -> TaskItem {
  { code, label, completed, }
}

///|
/// Task code prefix (for example `"1.1"`).
pub fn TaskItem::code(self : TaskItem) -> String {
  self.code
}

///|
/// Task description title.
pub fn TaskItem::label(self : TaskItem) -> IntentTitle {
  self.label
}

///|
/// Whether the task checkbox is ticked.
pub fn TaskItem::completed(self : TaskItem) -> Bool {
  self.completed
}

///|
/// Derived checklist progress where `0 <= completed <= total` holds by
/// construction.
#derive(Eq, Debug)
pub struct TaskProgress {
  priv completed : Int32
  priv total : Int32
}

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

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

///|
/// Derives `TaskProgress` from a sequence of task items.
pub fn TaskProgress::from_tasks(tasks : Array[TaskItem]) -> TaskProgress {
  let mut completed = 0
  for task in tasks {
    if task.completed {
      completed += 1
    }
  }
  { completed, total: tasks.length(), }
}

///|
/// Number of completed tasks.
pub fn TaskProgress::completed(self : TaskProgress) -> Int32 {
  self.completed
}

///|
/// Total number of tasks.
pub fn TaskProgress::total(self : TaskProgress) -> Int32 {
  self.total
}

///|
/// Integer completion percentage in `[0, 100]`. Returns `100` when `total == 0`.
pub fn TaskProgress::percent(self : TaskProgress) -> Int32 {
  if self.total <= 0 {
    100
  } else {
    self.completed * 100 / self.total
  }
}

///|
/// Whether every task is completed (true when `total > 0` and
/// `completed == total`).
pub fn TaskProgress::all_done(self : TaskProgress) -> Bool {
  self.total > 0 && self.completed == self.total
}

///|
/// Input payload for constructing a document in a `ReadingPacket`. Step
/// numbers are assigned monotonically by `ReadingPacket::ReadingPacket`.
#derive(Eq, Debug)
pub struct DocumentInput {
  priv role : ArtifactRole
  priv title : IntentTitle
  priv path : DocumentPath
  priv summary : String
  priv source_lines : ReadOnlyArray[String]
  priv requirements : ReadOnlyArray[RequirementDelta]
  priv tasks : ReadOnlyArray[TaskItem]
}

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

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

///|
/// Creates an immutable `DocumentInput`. `summary` and `source_lines` carry
/// raw prose/source lines without structural restrictions.
pub fn DocumentInput::DocumentInput(
  role~ : ArtifactRole,
  title~ : IntentTitle,
  path~ : DocumentPath,
  summary~ : String = "",
  source_lines~ : Array[String] = [],
  requirements~ : Array[RequirementDelta] = [],
  tasks~ : Array[TaskItem] = [],
) -> DocumentInput {
  {
    role,
    title,
    path,
    summary,
    source_lines: ReadOnlyArray::from_array(source_lines),
    requirements: ReadOnlyArray::from_array(requirements),
    tasks: ReadOnlyArray::from_array(tasks),
  }
}

///|
/// One document inside an ordered `ReadingPacket`, carrying its 1-based
/// monotonic step number.
#derive(Eq, Debug)
pub struct PacketDocument {
  priv step : Int32
  priv role : ArtifactRole
  priv title : IntentTitle
  priv path : DocumentPath
  priv summary : String
  priv source_lines : ReadOnlyArray[String]
  priv requirements : ReadOnlyArray[RequirementDelta]
  priv tasks : ReadOnlyArray[TaskItem]
}

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

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

///|
/// Constructs a standalone `PacketDocument` (such as a main specification
/// outside a change reading packet) at step `1`.
pub fn PacketDocument::standalone(input : DocumentInput) -> PacketDocument {
  {
    step: 1,
    role: input.role,
    title: input.title,
    path: input.path,
    summary: input.summary,
    source_lines: input.source_lines,
    requirements: input.requirements,
    tasks: input.tasks,
  }
}

///|
/// 1-based position inside the owning reading packet.
pub fn PacketDocument::step(self : PacketDocument) -> Int32 {
  self.step
}

///|
/// Artifact role of the document.
pub fn PacketDocument::role(self : PacketDocument) -> ArtifactRole {
  self.role
}

///|
/// Display title of the document.
pub fn PacketDocument::title(self : PacketDocument) -> IntentTitle {
  self.title
}

///|
/// Confined workspace-relative path of the document.
pub fn PacketDocument::path(self : PacketDocument) -> DocumentPath {
  self.path
}

///|
/// Leading summary prose extracted from the document.
pub fn PacketDocument::summary(self : PacketDocument) -> String {
  self.summary
}

///|
/// Raw source lines of the document.
pub fn PacketDocument::source_lines(
  self : PacketDocument,
) -> ReadOnlyArray[String] {
  self.source_lines
}

///|
/// Requirement deltas contained in the document.
pub fn PacketDocument::requirements(
  self : PacketDocument,
) -> ReadOnlyArray[RequirementDelta] {
  self.requirements
}

///|
/// Checklist tasks contained in the document.
pub fn PacketDocument::tasks(self : PacketDocument) -> ReadOnlyArray[TaskItem] {
  self.tasks
}

///|
/// Ordered reading packet whose documents are monotonically numbered `1..N`.
#derive(Eq, Debug)
pub struct ReadingPacket {
  priv documents : ReadOnlyArray[PacketDocument]
}

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

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

///|
/// Constructs a `ReadingPacket`, assigning 1-based monotonic step indices
/// `1..N` in document order.
pub fn ReadingPacket::ReadingPacket(
  inputs : Array[DocumentInput],
) -> ReadingPacket {
  let docs : Array[PacketDocument] = []
  for idx, input in inputs {
    docs.push({
      step: idx + 1,
      role: input.role,
      title: input.title,
      path: input.path,
      summary: input.summary,
      source_lines: input.source_lines,
      requirements: input.requirements,
      tasks: input.tasks,
    })
  }
  { documents: ReadOnlyArray::from_array(docs), }
}

///|
/// All ordered documents in the reading packet.
pub fn ReadingPacket::documents(
  self : ReadingPacket,
) -> ReadOnlyArray[PacketDocument] {
  self.documents
}

///|
/// Number of documents in the reading packet.
pub fn ReadingPacket::step_count(self : ReadingPacket) -> Int32 {
  self.documents.length()
}

///|
/// First document matching `role`, if present.
pub fn ReadingPacket::document_by_role(
  self : ReadingPacket,
  role : ArtifactRole,
) -> PacketDocument? {
  for doc in self.documents {
    if doc.role == role {
      return Some(doc)
    }
  }
  None
}

///|
/// Document at 1-based step number `step`, if in range.
pub fn ReadingPacket::document_at(
  self : ReadingPacket,
  step : Int32,
) -> PacketDocument? {
  if step >= 1 && step <= self.documents.length() {
    Some(self.documents[step - 1])
  } else {
    None
  }
}

///|
/// Aggregates `TaskProgress` across all tasks in the reading packet.
pub fn ReadingPacket::task_progress(self : ReadingPacket) -> TaskProgress {
  let all_tasks : Array[TaskItem] = []
  for doc in self.documents {
    for task in doc.tasks {
      all_tasks.push(task)
    }
  }
  TaskProgress::from_tasks(all_tasks)
}

///|
/// Lifecycle status of a canonical intent item.
#derive(Eq, Debug)
pub(all) enum IntentStatus {
  Active
  ReadyToVerify
  Archived
  Blocked(String)
}

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

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

///|
/// A canonical work item (change, proposal, or epic slice) projected from a
/// workspace source by an `IntentAdapter`.
#derive(Eq, Debug)
pub struct IntentItem {
  priv id : IntentId
  priv slug : String
  priv title : IntentTitle
  priv adapter : AdapterId
  priv stage : StageId
  priv status : IntentStatus
  priv origin_path : DocumentPath
  priv packet : ReadingPacket
}

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

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

///|
/// Constructs an immutable `IntentItem`.
pub fn IntentItem::IntentItem(
  id~ : IntentId,
  slug~ : String,
  title~ : IntentTitle,
  adapter~ : AdapterId,
  stage~ : StageId,
  status~ : IntentStatus,
  origin_path~ : DocumentPath,
  packet~ : ReadingPacket,
) -> IntentItem {
  { id, slug, title, adapter, stage, status, origin_path, packet, }
}

///|
/// Deterministic workspace-scoped URN of the item.
pub fn IntentItem::id(self : IntentItem) -> IntentId {
  self.id
}

///|
/// Short folder/change slug of the item.
pub fn IntentItem::slug(self : IntentItem) -> String {
  self.slug
}

///|
/// Human-readable title of the item.
pub fn IntentItem::title(self : IntentItem) -> IntentTitle {
  self.title
}

///|
/// Adapter that projected this item.
pub fn IntentItem::adapter(self : IntentItem) -> AdapterId {
  self.adapter
}

///|
/// Current workflow stage of the item.
pub fn IntentItem::stage(self : IntentItem) -> StageId {
  self.stage
}

///|
/// Lifecycle status of the item.
pub fn IntentItem::status(self : IntentItem) -> IntentStatus {
  self.status
}

///|
/// Confined workspace-relative folder or file path where the item lives.
pub fn IntentItem::origin_path(self : IntentItem) -> DocumentPath {
  self.origin_path
}

///|
/// Ordered reading packet for this item.
pub fn IntentItem::packet(self : IntentItem) -> ReadingPacket {
  self.packet
}

///|
/// Derived checklist progress across the item's reading packet.
pub fn IntentItem::task_progress(self : IntentItem) -> TaskProgress {
  self.packet.task_progress()
}

///|
/// Non-fatal diagnostic kind emitted while projecting workspace intent.
#derive(Eq, Debug)
pub(all) enum IntentDiagnosticKind {
  MissingArtifact(ArtifactRole)
  ParseProblem(String)
  EmptySpec
  DuplicateId(IntentId)
}

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

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

///|
/// Structured diagnostic emitted during intent projection or composition.
#derive(Eq, Debug)
pub struct IntentDiagnostic {
  priv kind : IntentDiagnosticKind
  priv path : DocumentPath?
  priv message : String
}

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

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

///|
/// Constructs an immutable `IntentDiagnostic`.
pub fn IntentDiagnostic::IntentDiagnostic(
  kind~ : IntentDiagnosticKind,
  path~ : DocumentPath? = None,
  message~ : String,
) -> IntentDiagnostic {
  { kind, path, message, }
}

///|
/// Structured kind of the diagnostic.
pub fn IntentDiagnostic::kind(self : IntentDiagnostic) -> IntentDiagnosticKind {
  self.kind
}

///|
/// Optional workspace-relative path associated with the diagnostic.
pub fn IntentDiagnostic::path(self : IntentDiagnostic) -> DocumentPath? {
  self.path
}

///|
/// Human-readable explanation of the diagnostic.
pub fn IntentDiagnostic::message(self : IntentDiagnostic) -> String {
  self.message
}

///|
/// Complete canonical intent projection for a workspace: active/archived work
/// items, main specification documents, and diagnostics.
#derive(Eq, Debug)
pub struct IntentProjection {
  priv items : ReadOnlyArray[IntentItem]
  priv specs : ReadOnlyArray[PacketDocument]
  priv diagnostics : ReadOnlyArray[IntentDiagnostic]
}

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

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

///|
/// Constructs an immutable `IntentProjection`.
pub fn IntentProjection::IntentProjection(
  items~ : Array[IntentItem] = [],
  specs~ : Array[PacketDocument] = [],
  diagnostics~ : Array[IntentDiagnostic] = [],
) -> IntentProjection {
  {
    items: ReadOnlyArray::from_array(items),
    specs: ReadOnlyArray::from_array(specs),
    diagnostics: ReadOnlyArray::from_array(diagnostics),
  }
}

///|
/// Empty projection with zero items, specs, and diagnostics.
pub fn IntentProjection::empty() -> IntentProjection {
  { items: [], specs: [], diagnostics: [], }
}

///|
/// All projected canonical intent items.
pub fn IntentProjection::items(
  self : IntentProjection,
) -> ReadOnlyArray[IntentItem] {
  self.items
}

///|
/// All standalone main specifications in the workspace.
pub fn IntentProjection::specs(
  self : IntentProjection,
) -> ReadOnlyArray[PacketDocument] {
  self.specs
}

///|
/// All diagnostics emitted during projection or composition.
pub fn IntentProjection::diagnostics(
  self : IntentProjection,
) -> ReadOnlyArray[IntentDiagnostic] {
  self.diagnostics
}

///|
/// Finds an item by its `IntentId`.
pub fn IntentProjection::find(
  self : IntentProjection,
  id : IntentId,
) -> IntentItem? {
  for item in self.items {
    if item.id == id {
      return Some(item)
    }
  }
  None
}

///|
/// Returns all items currently in `stage`.
pub fn IntentProjection::by_stage(
  self : IntentProjection,
  stage : StageId,
) -> Array[IntentItem] {
  let matched : Array[IntentItem] = []
  for item in self.items {
    if item.stage == stage {
      matched.push(item)
    }
  }
  matched
}