#!/usr/bin/env node

const assert = require("node:assert/strict");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const { spawnSync } = require("node:child_process");

const pluginRoot = path.resolve(__dirname, "..");
const fixture = fs.mkdtempSync(path.join(os.tmpdir(), "carbon-confidence-plugin-"));

for (const requiredPath of [
  "skills/carbon-confidence/SKILL.md",
  "skills/carbon-eval/SKILL.md",
  "skills/carbon-release/SKILL.md",
  "skills/carbon-incident/SKILL.md",
  "references/decision-model.md",
  "references/testing-ai-methods.md",
  "templates/release-report.md"
]) {
  assert.equal(
    fs.existsSync(path.join(pluginRoot, requiredPath)),
    true,
    `Missing CARBON confidence feature: ${requiredPath}`
  );
}

function run(command, args = [], input = "") {
  const result = spawnSync(command, args, {
    cwd: fixture,
    encoding: "utf8",
    input
  });
  assert.equal(
    result.status,
    0,
    `${command} ${args.join(" ")} failed:\n${result.stderr || result.stdout}`
  );
  return result.stdout;
}

try {
  run(path.join(pluginRoot, "bin", "carbon-confidence-init"), ["--dir", fixture, "--quiet"]);

  const manifest = JSON.parse(
    fs.readFileSync(path.join(fixture, ".confidence", "manifest.json"), "utf8")
  );
  assert.equal(manifest.projectRoot, ".");
  assert.equal(manifest.plugin, "carbon-confidence");
  assert.equal(manifest.methodArchitecture, "testing-ai-operational-v1");
  assert.equal(manifest.bookCompanion, "optional");
  assert.match(
    fs.readFileSync(path.join(fixture, ".confidence", "risks.yaml"), "utf8"),
    /method_refs:[\s\S]*TAI-UNCERTAINTY[\s\S]*book_refs:/
  );

  const nestedEvalDir = path.join(fixture, ".confidence", "evals", "nested");
  fs.mkdirSync(nestedEvalDir, { recursive: true });
  fs.writeFileSync(path.join(nestedEvalDir, "result.json"), "{}\n");

  const trackChange = path.join(pluginRoot, "bin", "carbon-confidence-track-change");
  run(
    trackChange,
    [],
    JSON.stringify({
      cwd: fixture,
      session_id: "smoke",
      tool_name: "Edit",
      tool_input: { file_path: "src/app.js" }
    })
  );
  run(
    trackChange,
    [],
    JSON.stringify({
      cwd: fixture,
      session_id: "smoke",
      tool_name: "Edit",
      tool_input: { file_path: path.join(os.tmpdir(), "outside.js") }
    })
  );

  const status = JSON.parse(
    run(path.join(pluginRoot, "bin", "carbon-confidence-status"), [
      "--dir",
      fixture,
      "--json"
    ])
  );
  assert.equal(status.complete, true);
  assert.equal(status.evalArtifacts, 1);
  assert.equal(status.traceEvents, 1);
  assert.equal(status.decision, "MORE EVIDENCE");

  const dashboardInput = path.join(fixture, ".confidence", "dashboard.json");
  const dashboardOutput = path.join(fixture, ".confidence", "dashboard.html");
  fs.writeFileSync(
    dashboardInput,
    `${JSON.stringify({
      title: "Smoke Review",
      decision: "CANARY",
      confidence: "medium",
      scope: "Smoke fixture",
      summary: "The narrow canary is supported.",
      metrics: [
        {
          label: "Repeated runs",
          value: "20",
          status: "good",
          progress: 80,
          detail: "Observed, not inferred."
        }
      ],
      risks: [
        {
          severity: "medium",
          title: "Slice coverage",
          detail: "One user slice remains small.",
          owner: "Quality"
        }
      ],
      evidence: [
        { label: "Harness", status: "verified", detail: "Executed locally." },
        { label: "Rollback", status: "partial", detail: "Procedure exists." }
      ],
      unknowns: ["Production tail latency"],
      artifacts: [".confidence/evals/result.json"]
    }, null, 2)}\n`
  );
  run(path.join(pluginRoot, "bin", "carbon-confidence-dashboard"), [
    "--input",
    dashboardInput,
    "--output",
    dashboardOutput
  ]);
  const dashboard = fs.readFileSync(dashboardOutput, "utf8");
  assert.match(dashboard, /Smoke Review/);
  assert.match(dashboard, /CANARY/);
  assert.match(dashboard, /Production tail latency/);
  assert.match(dashboard, /50%/);

  const guard = path.join(pluginRoot, "bin", "carbon-confidence-guard");
  const releaseWarning = JSON.parse(
    run(
      guard,
      [],
      JSON.stringify({
        cwd: fixture,
        tool_input: { command: "git push origin main" }
      })
    )
  );
  assert.match(
    releaseWarning.hookSpecificOutput.additionalContext,
    /MORE EVIDENCE/
  );

  const destructiveWarning = JSON.parse(
    run(
      guard,
      [],
      JSON.stringify({
        cwd: fixture,
        tool_input: { command: "terraform destroy" }
      })
    )
  );
  assert.match(
    destructiveWarning.hookSpecificOutput.additionalContext,
    /irreversible side effects/
  );

  console.log("CARBON confidence smoke test passed.");
} finally {
  fs.rmSync(fixture, { recursive: true, force: true });
}
