///|
/// Raised when saving a workspace workflow configuration fails validation.
#derive(Eq, Debug)
pub(all) suberror WorkflowConfigError {
  InvalidPreset(String)
  ScorecardOutOfRange(Int32)
}

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

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

///|
/// Human-readable error message for a `WorkflowConfigError`.
pub fn WorkflowConfigError::message(self : WorkflowConfigError) -> String {
  match self {
    InvalidPreset(preset) =>
      "Unknown workflow preset '\{preset}'. Expected openspec-sdlc-v1, regulated-bpmn-v1, lightweight-rfc-v1, or custom-file."
    ScorecardOutOfRange(score) =>
      "Minimum scorecard floor \{score} is out of range (expected 0 to 100)."
  }
}

///|
let valid_workflow_presets : ReadOnlyArray[String] = [
  "openspec-sdlc-v1", "regulated-bpmn-v1", "lightweight-rfc-v1", "custom-file",
]

///|
/// Default workspace workflow configuration when `.mission-control/workflow.toml`
/// does not exist.
pub fn default_workflow_config() -> @app.WireWorkflowConfig {
  {
    preset: "openspec-sdlc-v1",
    min_scorecard: 85,
    require_security_gate: false,
    source_origin: "default",
  }
}

///|
/// Validates and serializes a workspace workflow configuration to TOML for
/// `.mission-control/workflow.toml`.
pub fn serialize_workflow_toml(
  preset~ : String,
  min_scorecard~ : Int32,
  require_security_gate~ : Bool,
) -> String raise WorkflowConfigError {
  guard valid_workflow_presets.contains(preset) else {
    raise InvalidPreset(preset)
  }
  guard min_scorecard >= 0 && min_scorecard <= 100 else {
    raise ScorecardOutOfRange(min_scorecard)
  }
  let sec = if require_security_gate { "true" } else { "false" }
  (
    $|[workflow]
    $|preset = "\{preset}"
    $|min_scorecard = \{min_scorecard}
    $|require_security_gate = \{sec}
    $|
  )
}

///|
/// Parses `.mission-control/workflow.toml` into a `WireWorkflowConfig`, falling
/// back to defaults for omitted fields.
pub fn parse_workflow_toml(
  text : String,
  origin~ : String = ".mission-control/workflow.toml",
) -> (@app.WireWorkflowConfig, Array[String]) {
  let def = default_workflow_config()
  let notes : Array[String] = []
  let parsed : @toml.TomlValue? = Some(@toml.parse(text)) catch {
    err => {
      notes.push("Workflow TOML parse error in \{origin}: \{err}")
      None
    }
  }
  guard parsed is Some(TomlTable(root)) else {
    return ({ ..def, source_origin: origin, }, notes)
  }
  let wf_table : Map[String, @toml.TomlValue] = match root.get("workflow") {
    Some(TomlTable(tbl)) => tbl
    _ => root
  }
  let preset = match wf_table.get("preset") {
    Some(TomlString(s)) if valid_workflow_presets.contains(s) => s
    Some(TomlString(bad)) => {
      notes.push("Ignored unknown workflow preset '\{bad}' in \{origin}")
      def.preset
    }
    _ => def.preset
  }
  let min_scorecard = match wf_table.get("min_scorecard") {
    Some(TomlInteger(n)) =>
      if n >= 0L && n <= 100L {
        n.to_int()
      } else {
        notes.push("Ignored out-of-range min_scorecard \{n} in \{origin}")
        def.min_scorecard
      }
    _ => def.min_scorecard
  }
  let require_security_gate = match wf_table.get("require_security_gate") {
    Some(TomlBoolean(b)) => b
    _ => preset == "regulated-bpmn-v1"
  }
  (
    { preset, min_scorecard, require_security_gate, source_origin: origin, },
    notes,
  )
}

///|
/// Maps a numeric 0..100 score to a deterministic A..F letter grade.
pub fn score_to_grade(score : Int32) -> String {
  if score >= 90 {
    "A"
  } else if score >= 80 {
    "B"
  } else if score >= 70 {
    "C"
  } else if score >= 60 {
    "D"
  } else {
    "F"
  }
}

///|
/// Open-closed extension point for deterministic document quality scoring.
/// Each scorer returns `(deduction, findings)` against a document and the
/// workspace's loaded Data Dictionary.
pub(open) trait DocumentScorer {
  fn id(Self) -> String
  fn evaluate(Self, @app.WirePacketDocument, @app.WorkspaceDictionary) -> (
    Int32,
    Array[@app.WireScoreFinding],
  )
}

///|
/// Built-in scorer checking document structural completeness (non-empty
/// content, summary, requirements in spec deltas, tasks in task lists).
pub struct StructuralCompletenessScorer {}

///|
pub fn StructuralCompletenessScorer::StructuralCompletenessScorer() -> StructuralCompletenessScorer {
  StructuralCompletenessScorer::{ }
}

///|
pub impl DocumentScorer for StructuralCompletenessScorer with fn id(_self) {
  "structural"
}

///|
pub impl DocumentScorer for StructuralCompletenessScorer with fn evaluate(
  _self,
  doc,
  _dict,
) {
  let findings : Array[@app.WireScoreFinding] = []
  let mut penalty = 0
  if doc.source_lines.length() < 3 {
    penalty += 15
    findings.push({
      scorer: "structural",
      severity: "warning",
      message: "Document has fewer than 3 lines of content.",
      document_path: Some(doc.path),
    })
  }
  if doc.summary.trim().is_empty() {
    penalty += 8
    findings.push({
      scorer: "structural",
      severity: "warning",
      message: "Document is missing a leading prose summary paragraph.",
      document_path: Some(doc.path),
    })
  }
  match doc.role {
    SpecDelta =>
      if doc.requirements.is_empty() {
        penalty += 25
        findings.push({
          scorer: "structural",
          severity: "error",
          message: "Spec delta declares no structured requirements.",
          document_path: Some(doc.path),
        })
      }
    Tasks =>
      if doc.tasks.is_empty() {
        penalty += 20
        findings.push({
          scorer: "structural",
          severity: "warning",
          message: "Tasks document contains no checklist items.",
          document_path: Some(doc.path),
        })
      }
    _ => ()
  }
  (penalty, findings)
}

///|
/// Built-in scorer checking EARS conformance (`SHALL` modal + scenarios) on
/// specification documents.
pub struct EarsConformanceScorer {}

///|
pub fn EarsConformanceScorer::EarsConformanceScorer() -> EarsConformanceScorer {
  EarsConformanceScorer::{ }
}

///|
pub impl DocumentScorer for EarsConformanceScorer with fn id(_self) {
  "ears"
}

///|
pub impl DocumentScorer for EarsConformanceScorer with fn evaluate(
  _self,
  doc,
  _dict,
) {
  let findings : Array[@app.WireScoreFinding] = []
  let mut penalty = 0
  for req in doc.requirements {
    if !req.text.contains("SHALL") {
      penalty += 12
      findings.push({
        scorer: "ears",
        severity: "warning",
        message: "Requirement '\{req.title}' does not contain uppercase SHALL.",
        document_path: Some(doc.path),
      })
    }
    if req.scenarios.is_empty() {
      penalty += 8
      findings.push({
        scorer: "ears",
        severity: "warning",
        message: "Requirement '\{req.title}' has no acceptance scenario.",
        document_path: Some(doc.path),
      })
    }
  }
  (penalty, findings)
}

///|
/// Built-in scorer deducting points for open Prose Term Audit findings on a
/// document.
pub struct DictionaryHygieneScorer {}

///|
pub fn DictionaryHygieneScorer::DictionaryHygieneScorer() -> DictionaryHygieneScorer {
  DictionaryHygieneScorer::{ }
}

///|
pub impl DocumentScorer for DictionaryHygieneScorer with fn id(_self) {
  "dictionary-hygiene"
}

///|
pub impl DocumentScorer for DictionaryHygieneScorer with fn evaluate(
  _self,
  doc,
  dict,
) {
  let findings : Array[@app.WireScoreFinding] = []
  let mut penalty = 0
  for f in dict.findings {
    if f.document_path == doc.path {
      let ded = if f.kind == "deprecated_synonym" { 15 } else { 8 }
      penalty += ded
      findings.push({
        scorer: "dictionary-hygiene",
        severity: "warning",
        message: "Prose uses '\{f.term}'; prefer '\{f.suggested_label}'.",
        document_path: Some(doc.path),
      })
    }
  }
  (penalty, findings)
}

///|
/// Default registered `DocumentScorer` chain.
pub fn default_document_scorers() -> Array[&DocumentScorer] {
  [
    StructuralCompletenessScorer() as &DocumentScorer,
    EarsConformanceScorer() as &DocumentScorer,
    DictionaryHygieneScorer() as &DocumentScorer,
  ]
}

///|
/// Scores a single reading packet document across all registered scorers.
pub fn score_document(
  doc : @app.WirePacketDocument,
  dict : @app.WorkspaceDictionary,
  scorers~ : Array[&DocumentScorer] = default_document_scorers(),
) -> @app.WireDocumentScorecard {
  let mut total_penalty = 0
  let findings : Array[@app.WireScoreFinding] = []
  for scorer in scorers {
    let (ded, fs) = scorer.evaluate(doc, dict)
    total_penalty += ded
    for f in fs {
      findings.push(f)
    }
  }
  let raw = 100 - total_penalty
  let clamped = if raw < 0 { 0 } else if raw > 100 { 100 } else { raw }
  {
    document_path: doc.path,
    score: clamped,
    grade: score_to_grade(clamped),
    findings: ReadOnlyArray::from_array(findings),
  }
}

///|
let default_rego_gate_policy : String =
  #|package mc.gates
  #|
  #|default score_floor_ok := false
  #|score_floor_ok if {
  #|  input.score >= input.min_scorecard
  #|}
  #|
  #|default artifacts_ok := false
  #|artifacts_ok if {
  #|  input.artifact_count >= 2
  #|}
  #|
  #|default dictionary_clean := false
  #|dictionary_clean if {
  #|  input.audit_findings == 0
  #|}
  #|
  #|default tasks_ok := false
  #|tasks_ok if {
  #|  input.stage != "verify"
  #|}
  #|tasks_ok if {
  #|  input.tasks_total == 0
  #|}
  #|tasks_ok if {
  #|  input.tasks_completed == input.tasks_total
  #|}
  #|
  #|default allow := false
  #|allow if {
  #|  score_floor_ok
  #|  artifacts_ok
  #|  dictionary_clean
  #|  tasks_ok
  #|}

///|
fn eval_rego_bool(
  compiled : @rego.CompiledPolicy,
  rule : Array[String],
  input : @rego_value.Value,
) -> Bool {
  let ans = @rego.eval_rule(compiled, rule, input=Some(input)) catch {
    _ => None
  }
  match ans {
    Some(@rego_value.Value::Bool(b)) => b
    _ => false
  }
}

///|
fn next_stage_for(stage : String, require_security : Bool) -> String? {
  match stage {
    "explore" => Some("propose")
    "propose" =>
      if require_security {
        Some("security")
      } else {
        Some("implement")
      }
    "security" => Some("implement")
    "implement" => Some("verify")
    "verify" => Some("archived")
    _ => None
  }
}

///|
/// Pure evaluation of workspace document scorecards and live `moonrockz/rego`
/// transition gates for all live intent items.
pub fn evaluate_sdlc_pure(
  workspace : @app.WorkspaceId,
  intent : @app.WorkspaceIntent,
  dict : @app.WorkspaceDictionary,
  workflow : @app.WireWorkflowConfig,
  scorers~ : Array[&DocumentScorer] = default_document_scorers(),
  initial_notes~ : Array[String] = [],
) -> @app.WorkspaceSdlc {
  let notes : Array[String] = []
  for n in initial_notes {
    notes.push(n)
  }
  let compiled_opt : @rego.CompiledPolicy? = Some(
    @rego.compile_sources([default_rego_gate_policy]),
  ) catch {
    err => {
      notes.push("Rego gate policy failed to compile: \{err}")
      None
    }
  }
  if compiled_opt is Some(_) {
    notes.push("Evaluated transition gates with Rego v1 package mc.gates.")
  }

  let evals : Array[@app.WireItemEvaluation] = []
  let mut sum_score = 0
  for item in intent.items {
    let doc_cards : Array[@app.WireDocumentScorecard] = []
    let mut doc_sum = 0
    for doc in item.packet.documents {
      let card = score_document(doc, dict, scorers~)
      doc_sum += card.score
      doc_cards.push(card)
    }
    let item_score = if doc_cards.is_empty() {
      100
    } else {
      doc_sum / doc_cards.length()
    }
    sum_score += item_score

    // Count Prose Term Audit findings affecting documents of this item.
    let mut item_audit_count = 0
    for f in dict.findings {
      if item.packet.documents.iter().any(d => d.path == f.document_path) {
        item_audit_count += 1
      }
    }

    let rego_input = @rego_value.Value::Object(
      @rego_value.RegoObject::from_strings([
        ("score", Number(@rego_value.Decimal::from_int(item_score))),
        (
          "min_scorecard",
          Number(@rego_value.Decimal::from_int(workflow.min_scorecard)),
        ),
        ("stage", String(item.stage)),
        (
          "artifact_count",
          Number(@rego_value.Decimal::from_int(item.packet.documents.length())),
        ),
        (
          "tasks_completed",
          Number(@rego_value.Decimal::from_int(item.task_progress.completed)),
        ),
        (
          "tasks_total",
          Number(@rego_value.Decimal::from_int(item.task_progress.total)),
        ),
        (
          "audit_findings",
          Number(@rego_value.Decimal::from_int(item_audit_count)),
        ),
        ("require_security_gate", Bool(workflow.require_security_gate)),
      ]),
    )

    let (score_ok, art_ok, dict_ok, tasks_ok, allow_ok) = match compiled_opt {
      Some(compiled) =>
        (
          eval_rego_bool(
            compiled,
            ["mc", "gates", "score_floor_ok"],
            rego_input,
          ),
          eval_rego_bool(compiled, ["mc", "gates", "artifacts_ok"], rego_input),
          eval_rego_bool(
            compiled,
            ["mc", "gates", "dictionary_clean"],
            rego_input,
          ),
          eval_rego_bool(compiled, ["mc", "gates", "tasks_ok"], rego_input),
          eval_rego_bool(compiled, ["mc", "gates", "allow"], rego_input),
        )
      None => (false, false, false, false, false)
    }

    let gates : Array[@app.WireGateCheck] = [
      {
        name: "Scorecard Floor",
        source: "Rego",
        passed: score_ok,
        detail: "\{item_score} vs floor >= \{workflow.min_scorecard}",
      },
      {
        name: "Reading Packet Artifacts",
        source: "Rego",
        passed: art_ok,
        detail: "\{item.packet.documents.length()} artifact(s) present (min 2)",
      },
      {
        name: "Data Dictionary Hygiene",
        source: "Rego + RDF",
        passed: dict_ok,
        detail: if dict_ok {
          "0 open Prose Term Audit findings"
        } else {
          "\{item_audit_count} open Prose Term Audit finding(s)"
        },
      },
      {
        name: "Task Completion",
        source: "Rego",
        passed: tasks_ok,
        detail: "\{item.task_progress.completed}/\{item.task_progress.total} tasks completed",
      },
    ]

    evals.push({
      item_id: item.id,
      slug: item.slug,
      stage: item.stage,
      score: item_score,
      grade: score_to_grade(item_score),
      next_stage: next_stage_for(item.stage, workflow.require_security_gate),
      gates_passed: allow_ok,
      gates: ReadOnlyArray::from_array(gates),
      documents: ReadOnlyArray::from_array(doc_cards),
    })
  }

  let rollup_score = if evals.is_empty() {
    100
  } else {
    sum_score / evals.length()
  }
  {
    workspace,
    rollup_score,
    rollup_grade: score_to_grade(rollup_score),
    workflow,
    evaluations: ReadOnlyArray::from_array(evals),
    policy_notes: ReadOnlyArray::from_array(notes),
  }
}

///|
/// Pure `Inquiry` reading `.mission-control/workflow.toml` (if present and
/// workspace-confined) and evaluating scorecards & Rego gates.
pub fn inspect_workspace_sdlc(
  workspace_id : @app.WorkspaceId,
  workspace_root : FolderPath,
  intent : @app.WorkspaceIntent,
  dict : @app.WorkspaceDictionary,
) -> Inquiry[@app.WorkspaceSdlc] {
  let wf_path = workspace_root.join([".mission-control", "workflow.toml"])
  RealPath(workspace_root, root_ans => {
    let evaluate_default = () => {
      Done(
        evaluate_sdlc_pure(
          workspace_id,
          intent,
          dict,
          default_workflow_config(),
        ),
      )
    }
    match root_ans {
      Resolved(real_root) =>
        RealPath(wf_path, wf_real => {
          match wf_real {
            Resolved(real_wf) if real_root.contains(real_wf) =>
              ReadFile(wf_path, text => {
                match text {
                  Found(content) => {
                    let (wf, notes) = parse_workflow_toml(content)
                    Done(
                      evaluate_sdlc_pure(
                        workspace_id,
                        intent,
                        dict,
                        wf,
                        initial_notes=notes,
                      ),
                    )
                  }
                  Missing | TooLarge | TimedOut | Failed(_) =>
                    evaluate_default()
                }
              })
            _ => evaluate_default()
          }
        })
      Missing | TimedOut | Failed(_) => evaluate_default()
    }
  })
}