// Open-closed adapter trait and deterministic multi-adapter projection
// composition.

///|
/// Open extension point for SDD adapters (OpenSpec, BMAD, or custom formats)
/// that project pure workspace file snapshots into canonical `IntentProjection`
/// values without performing I/O.
pub(open) trait IntentAdapter {
  /// Stable lowercase identifier of this adapter.
  fn adapter_id(Self) -> AdapterId
  /// Projects workspace-relative `(DocumentPath, content)` snapshots into
  /// canonical intent items, main specifications, and diagnostics.
  fn project(
    Self,
    workspace_urn~ : String,
    files : ReadOnlyArray[(DocumentPath, String)],
  ) -> IntentProjection
}

///|
/// Functional adapter wrapper turning a closure into an `IntentAdapter` for
/// lightweight composition and testing.
pub struct FnIntentAdapter {
  priv id : AdapterId
  priv run : (String, ReadOnlyArray[(DocumentPath, String)]) -> IntentProjection
}

///|
/// Constructs a functional `IntentAdapter`.
pub fn FnIntentAdapter::FnIntentAdapter(
  id~ : AdapterId,
  run : (String, ReadOnlyArray[(DocumentPath, String)]) -> IntentProjection,
) -> FnIntentAdapter {
  { id, run, }
}

///|
pub impl IntentAdapter for FnIntentAdapter with fn adapter_id(self) {
  self.id
}

///|
pub impl IntentAdapter for FnIntentAdapter with fn project(
  self,
  workspace_urn~,
  files,
) {
  (self.run)(workspace_urn, files)
}

///|
/// Deterministically combines projections from multiple adapters. Preserves the
/// first `IntentItem` for each `IntentId`, emits a `DuplicateId` diagnostic for
/// any colliding item, sorts items by `IntentId` and specs by `DocumentPath`,
/// and retains all diagnostics.
pub fn compose_projections(
  projections : Array[IntentProjection],
) -> IntentProjection {
  let seen : Map[IntentId, Bool] = Map([])
  let items : Array[IntentItem] = []
  let specs : Array[PacketDocument] = []
  let diagnostics : Array[IntentDiagnostic] = []
  for proj in projections {
    for item in proj.items() {
      if seen.contains(item.id()) {
        diagnostics.push(
          IntentDiagnostic(
            kind=DuplicateId(item.id()),
            path=Some(item.origin_path()),
            message="Duplicate canonical intent ID \{item.id()} ignored.",
          ),
        )
      } else {
        seen[item.id()] = true
        items.push(item)
      }
    }
    for spec in proj.specs() {
      specs.push(spec)
    }
    for diag in proj.diagnostics() {
      diagnostics.push(diag)
    }
  }
  items.sort_by((a, b) => a.id().compare(b.id()))
  specs.sort_by((a, b) => a.path().compare(b.path()))
  IntentProjection(items~, specs~, diagnostics~)
}

///|
/// Runs every adapter in `adapters` over the same immutable file snapshot and
/// composes their projections deterministically.
pub fn run_adapters(
  adapters : Array[&IntentAdapter],
  workspace_urn~ : String,
  files : ReadOnlyArray[(DocumentPath, String)],
) -> IntentProjection {
  let projections : Array[IntentProjection] = []
  for adapter in adapters {
    projections.push(adapter.project(workspace_urn~, files))
  }
  compose_projections(projections)
}