///|
fn impact_json_strings(values : Array[String]) -> Json {
  Json::array(values.map(value => Json::string(value)))
}

///|
fn impact_edge_json(edge : ImpactEdge) -> Json {
  Json::object({
    "dependency": Json::string(edge.dependency),
    "dependent": Json::string(edge.dependent),
    "kind": Json::string(edge.kind),
    "line": Json::number(edge.line.to_double()),
    "column": Json::number(edge.column.to_double()),
  })
}

///|
/// Render a versioned advisory plan. This schema deliberately contains no
/// passing-test verdict: it records selection and evidence, not execution.
pub fn render_impact_json(plan : ImpactPlan) -> String {
  let traces = plan.traces.map(trace => {
    Json::object({
      "test": Json::string(trace.test_file),
      "changed": Json::string(trace.changed),
      "chain": Json::array(trace.chain.map(impact_edge_json)),
    })
  })
  let issues = plan.issues.map(issue => {
    Json::object({
      "file": Json::string(issue.file),
      "line": Json::number(issue.line.to_double()),
      "reason": Json::string(issue.reason),
    })
  })
  Json::object({
    "tool": Json::string("moonimpact"),
    "version": Json::number(1.0),
    "kind": Json::string("test-plan"),
    "advisory": Json::boolean(true),
    "root": Json::string(plan.root),
    "input": Json::string(plan.input),
    "source_snapshot": Json::string("live-working-tree"),
    "mode": Json::string(plan.mode),
    "strategy": Json::string(plan.strategy),
    "changed": impact_json_strings(plan.changed),
    "tests": impact_json_strings(plan.tests),
    "inventory": impact_json_strings(plan.inventory),
    "affected": impact_json_strings(plan.affected),
    "traces": Json::array(traces),
    "reasons": impact_json_strings(plan.reasons),
    "issues": Json::array(issues),
    "counts": Json::object({
      "changed": Json::number(plan.changed.length().to_double()),
      "sources": Json::number(plan.source_count.to_double()),
      "edges": Json::number(plan.edge_count.to_double()),
      "inventory": Json::number(plan.inventory.length().to_double()),
      "selected_tests": Json::number(plan.tests.length().to_double()),
      "known_affected": Json::number(plan.affected.length().to_double()),
      "issues": Json::number(plan.issues.length().to_double()),
    }),
    "limitations": impact_json_strings([
      "Selection uses supported static dependencies and explicit configuration, not complete language semantics.",
      if plan.mode == "moonbit" {
        "No test success is established by this plan; --run executes trusted project code using the local MoonBit toolchain."
      } else {
        "No test success is established by this plan; --run executes trusted project code using the local Vitest installation."
      },
      "Git input describes changes; analyzed sources are a live working tree, not an atomic repository snapshot.",
      if plan.mode == "moonbit" {
        "Full fallback runs unfiltered moon test; the runner may discover additional tests beyond this static inventory."
      } else {
        "Full fallback requests all tests from Vitest; the runner may discover additional tests beyond this inventory."
      },
    ]),
  }).stringify(indent=2)
}

///|
/// Quote text to keep control characters in filenames out of terminal output.
fn impact_quote(value : String) -> String {
  Json::string(value).stringify()
}

///|
/// Human-readable selection with one shortest known witness per related test.
pub fn render_impact_text(plan : ImpactPlan) -> String {
  let moonbit = plan.mode == "moonbit"
  let unit_word = if moonbit { "package" } else { "test file" }
  let lines : Array[String] = [
    "MoonImpact — advisory test plan",
    "root: " + impact_quote(plan.root),
    "input: " + impact_quote(plan.input),
    "strategy: " + plan.strategy,
    if moonbit {
      "mode: moonbit package graph"
    } else {
      "mode: js-ts source graph"
    },
    "changed: \{plan.changed.length()}  sources: \{plan.source_count}  edges: \{plan.edge_count}",
    "test inventory: \{plan.inventory.length()}  selected: \{plan.tests.length()}  uncertainties: \{plan.issues.length()}",
    "This is a plan, not a passing test result. Tests run only with --run.",
  ]
  if plan.strategy == "full" {
    lines.push(
      "Full fallback: request the runner's full suite; known chains below are not a coverage guarantee.",
    )
  }
  if !plan.reasons.is_empty() {
    lines.push("")
    lines.push("Reasons:")
    for reason in plan.reasons {
      lines.push("  - " + impact_quote(reason))
    }
  }
  if !plan.tests.is_empty() {
    lines.push("")
    lines.push(
      if moonbit {
        "Selected packages:"
      } else {
        "Selected test files:"
      },
    )
    for path in plan.tests {
      lines.push("  " + impact_quote(path))
    }
  }
  if !plan.traces.is_empty() {
    lines.push("")
    lines.push("Known dependency evidence:")
    for trace in plan.traces {
      lines.push(
        "  " +
        impact_quote(trace.changed) +
        " => " +
        impact_quote(trace.test_file),
      )
      if trace.chain.is_empty() {
        lines.push("    directly changed test")
      }
      for edge in trace.chain {
        lines.push(
          "    " +
          impact_quote(edge.dependency) +
          " -> " +
          impact_quote(edge.dependent) +
          " [\{edge.kind}; reference at \{edge.line}:\{edge.column}]",
        )
      }
    }
  }
  if !plan.issues.is_empty() {
    lines.push("")
    lines.push("Uncertainties / blocked inputs:")
    for issue in plan.issues {
      lines.push(
        "  " +
        impact_quote(issue.file) +
        ":\{issue.line} " +
        impact_quote(issue.reason),
      )
    }
  }
  lines.join("\n")
}

///|
fn impact_html_escape(text : String) -> String {
  let out = StringBuilder()
  for c in text {
    match c {
      '&' => out.write_string("&")
      '<' => out.write_string("<")
      '>' => out.write_string(">")
      '"' => out.write_string(""")
      '\'' => out.write_string("'")
      _ => out.write_char(c)
    }
  }
  out.to_string()
}

///|
/// Generate a standalone, script-free HTML report. All project-controlled
/// strings are escaped; the report fetches no external assets or scripts.
pub fn render_impact_html(plan : ImpactPlan) -> String {
  let out = StringBuilder()
  out.write_string(
    (
      #|
      #|
      #|
      #|
      #|MoonImpact — Test plan
      #|
CHANGE IMPACT / VUE + TYPESCRIPT

MoonImpact

#|

Advisory selection, not a passing test result. Unsupported dependencies trigger a full-suite fallback.

), ) out.write_string( "

" + impact_html_escape(plan.strategy) + "

", ) out.write_string( "

Root: " + impact_html_escape(plan.root) + "
", ) out.write_string( "Input: " + impact_html_escape(plan.input) + "

", ) out.write_string( "
\{plan.changed.length()}Changes
\{plan.tests.length()} / \{plan.inventory.length()}Selected / inventoried tests
\{plan.edge_count}Known dependency edges
\{plan.issues.length()}Uncertainties
", ) out.write_string("

Selection reasons

    ") for reason in plan.reasons { out.write_string("
  • " + impact_html_escape(reason) + "
  • ") } if plan.reasons.is_empty() { out.write_string( "
  • Related tests were found using the known dependency graph.
  • ", ) } out.write_string( "

The live working tree is not an atomic Git snapshot. Full fallback runs the runner's unfiltered full suite, which may include tests outside this static inventory.

", ) out.write_string("

Selected tests

    ") for path in plan.tests { out.write_string("
  • " + impact_html_escape(path) + "
  • ") } if plan.tests.is_empty() { out.write_string( "
  • No test execution is selected. Review the strategy and reasons above.
  • ", ) } out.write_string("

Known evidence chains

") for trace in plan.traces { out.write_string( "
" + impact_html_escape(trace.test_file) + "

Change: " + impact_html_escape(trace.changed) + "

    ", ) if trace.chain.is_empty() { out.write_string("
  • The test file itself changed.
  • ") } for edge in trace.chain { out.write_string( "
  • " + impact_html_escape(edge.dependency) + " → " + impact_html_escape(edge.dependent) + "
    " + impact_html_escape(edge.kind) + " · reference \{edge.line}:\{edge.column}
  • ", ) } out.write_string("
") } out.write_string( "

Uncertainties / blocked inputs

", ) for issue in plan.issues { out.write_string( "", ) } out.write_string( "
File / lineReason
" + impact_html_escape(issue.file) + ":\{issue.line}" + impact_html_escape(issue.reason) + "

MoonImpact MVP · supported static module and file-input dependencies only · no test success asserted

\n", ) out.to_string() }