#!/usr/bin/env bun
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
import path from "node:path";
import type { GateProfile } from "../scripts/task-phase-lib.ts";

function usage(): never {
  console.error(`Usage:
  task-phase-init T-xxx --goal "Goal text" --repo /path/repo [--source "Source ref"] [--status queued|active|blocked|done] [--phase intake|shape|implement|verify|review|repair|done|blocked|needs_user_decision|retrospective|closed] [--gate-profile repo_code|docs_only|audit|migration|ops_setup|research_with_artifact]
`);
  process.exit(1);
}

type Phase = "intake" | "shape" | "implement" | "verify" | "review" | "repair" | "done" | "blocked" | "needs_user_decision" | "retrospective" | "closed";
type Status = "queued" | "active" | "blocked" | "done";

const phases = new Set<Phase>(["intake", "shape", "implement", "verify", "review", "repair", "done", "blocked", "needs_user_decision", "retrospective", "closed"]);
const statuses = new Set<Status>(["queued", "active", "blocked", "done"]);
const gateProfiles = new Set<GateProfile>(["repo_code", "docs_only", "audit", "migration", "ops_setup", "research_with_artifact"]);

const args = process.argv.slice(2);
const taskId = args.shift();
if (!taskId) usage();
if (!/^T-[A-Za-z0-9._-]+$/.test(taskId)) {
  console.error("task id must look like T-xxx");
  process.exit(1);
}

let goal = "";
let source = "unknown";
let repo = "";
let status: Status = "queued";
let phase: Phase = "intake";
let gateProfile: GateProfile = "repo_code";

for (let i = 0; i < args.length; i++) {
  const arg = args[i];
  const next = args[i + 1];
  switch (arg) {
    case "--goal":
      goal = next || "";
      i++;
      break;
    case "--source":
      source = next || "";
      i++;
      break;
    case "--repo":
      repo = next || "";
      i++;
      break;
    case "--status":
      if (!next || !statuses.has(next as Status)) {
        console.error(`invalid status: ${next || ""}`);
        process.exit(1);
      }
      status = next as Status;
      i++;
      break;
    case "--phase":
      if (!next || !phases.has(next as Phase)) {
        console.error(`invalid phase: ${next || ""}`);
        process.exit(1);
      }
      phase = next as Phase;
      i++;
      break;
    case "--gate-profile":
      if (!next || !gateProfiles.has(next as GateProfile)) {
        console.error(`invalid gate profile: ${next || ""}`);
        process.exit(1);
      }
      gateProfile = next as GateProfile;
      i++;
      break;
    case "-h":
    case "--help":
      usage();
      break;
    default:
      console.error(`Unknown arg: ${arg}`);
      usage();
  }
}

if (!goal) {
  console.error("--goal required");
  process.exit(1);
}
if (!repo) {
  console.error("--repo required");
  process.exit(1);
}

const repoAbs = path.resolve(repo);
const tasksRoot = "/home/sebas/work/tasks";
const taskDir = path.join(tasksRoot, taskId);
const artifactsDir = path.join(taskDir, "artifacts");
const scratchDir = path.join(taskDir, "scratch");
const readmeFile = path.join(taskDir, "README.md");
const stateFile = path.join(taskDir, "STATE.md");
const evidenceFile = path.join(taskDir, "EVIDENCE.md");
const retrospectiveFile = path.join(taskDir, "RETROSPECTIVE.md");
const evidenceHtmlFile = path.join(artifactsDir, "evidence.html");
const relativeEvidenceFile = `${taskId}/artifacts/evidence.html`;
const evidenceLink = `https://ballbox-first.emperor-ratio.ts.net/files/work/tasks/${relativeEvidenceFile}`;
const now = new Date().toISOString();

mkdirSync(artifactsDir, { recursive: true });
mkdirSync(scratchDir, { recursive: true });

if (!existsSync(readmeFile)) {
  writeFileSync(readmeFile, `# ${taskId}

## Goal
${goal}

## Source
- ${source}

## Scope / exclusions
- TODO

## Main repo(s) / path(s)
- ${repoAbs}
`);
}

if (!existsSync(stateFile)) {
  writeFileSync(stateFile, `# ${taskId} state

- Phase: ${phase}
- Status: ${status}
- Objective: ${goal}
- Done gate: TODO
- Not doing: TODO
- Reality constraints: TODO
- Validation plan: TODO
- Current result: just initialized
- Next step: lock the frame and fill required gates
- Blockers: none
- Evidence location: ${artifactsDir}
- Evidence link: ${evidenceLink}
- Candidate done: no
- Validator status: pending
- Repair applied: no
- Revalidation status: pending
- Gate profile: ${gateProfile}
- Retrospective required: no
- Retrospective status: pending
- Preventive changes needed: no
- Observed failures summary: none yet
- Required gates:
  - truthfulness_check_pass
  - evidence_link_present
- Gate status:
  - truthfulness_check_pass: pending
  - evidence_link_present: pass
- Observed failures:
  - none
- Preventive changes proposed:
  - none
- Follow-up tasks created:
  - none
- Last updated: ${now}
`);
}

if (!existsSync(evidenceFile)) {
  writeFileSync(evidenceFile, `# ${taskId} evidence

## Canonical evidence link
- ${evidenceLink}

## Validation notes
- TODO

## Artifacts
- Add links to screenshots, HTML captures, logs, exported text, or other proof files.
- For complex bundles, keep ${relativeEvidenceFile} as the main joinery page.
`);
}

if (!existsSync(retrospectiveFile)) {
  writeFileSync(retrospectiveFile, `# ${taskId} retrospective

## Trigger
- Fill this only if the phase machine reaches \`retrospective\`.

## Rules
- Do not repair the main deliverable here.
- Capture what went wrong.
- Propose preventive changes.
- Spawn follow-up tasks instead of fixing the system here.

## Observed failures
- none

## Root cause guess
- TODO

## Preventive changes proposed
- none

## Follow-up tasks created
- none
`);
}

if (!existsSync(evidenceHtmlFile)) {
  writeFileSync(evidenceHtmlFile, `<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>${taskId} evidence</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    body { font-family: system-ui, sans-serif; max-width: 900px; margin: 2rem auto; padding: 0 1rem; line-height: 1.5; }
    code { background: #f2f2f2; padding: 0.1rem 0.3rem; border-radius: 4px; }
  </style>
</head>
<body>
  <h1>${taskId} evidence</h1>
  <p>Main task folder: <code>${taskDir}</code></p>
  <p>Repo: <code>${repoAbs}</code></p>
  <h2>Status</h2>
  <p>Replace this page or extend it with links to screenshots, logs, exported text, HTML captures, and validation proof.</p>
  <h2>Suggested links</h2>
  <ul>
    <li><a href="../EVIDENCE.md">EVIDENCE.md</a> if exposed through markdown-capable viewer</li>
    <li><a href="../RETROSPECTIVE.md">RETROSPECTIVE.md</a> for the post-task learning record</li>
    <li>Add screenshots/logs/text files into this folder and link them here</li>
  </ul>
</body>
</html>
`);
}

console.log(`task_dir=${taskDir}`);
console.log(`readme=${readmeFile}`);
console.log(`state=${stateFile}`);
console.log(`evidence=${evidenceFile}`);
console.log(`retrospective=${retrospectiveFile}`);
console.log(`evidence_html=${evidenceHtmlFile}`);
console.log(`evidence_link=${evidenceLink}`);
console.log(`scratch=${scratchDir}`);
