import { existsSync, readFileSync } from "node:fs";
import { spawnSync } from "node:child_process";
import { join } from "node:path";

const includesAll = (text, terms) => terms.every((term) => text.includes(term));

const readText = (path) => readFileSync(path, "utf8");

const runHookProbe = (root) => {
  const hookPath = join(root, "plugins", "lazyclaude", "bin", "lazyclaude-hook.js");
  const result = spawnSync(process.execPath, [hookPath, "user-prompt-submit"], {
    cwd: root,
    encoding: "utf8",
    input: JSON.stringify({
      hook_event_name: "UserPromptSubmit",
      prompt: "$dynamic-workflow verify delegation",
      cwd: root,
    }),
  });
  if (result.status !== 0) return "";
  try {
    return JSON.parse(result.stdout).hookSpecificOutput?.additionalContext ?? "";
  } catch {
    return "";
  }
};

export const createWorkflowCheckReport = (root, version) => {
  const commandPath = join(root, "plugins", "lazyclaude", "commands", "dynamic-workflow.md");
  const agentsPath = join(root, "docs", "agents.md");
  const hookContext = runHookProbe(root);
  const commandText = existsSync(commandPath) ? readText(commandPath) : "";
  const agentsText = existsSync(agentsPath) ? readText(agentsPath) : "";

  const checks = {
    goalGuidance: includesAll(`${hookContext}\n${commandText}`, ["get_goal", "create_goal", "update_goal", "/goal"]),
    dynamicWorkflowGuidance: includesAll(`${hookContext}\n${commandText}`, ["Workflow", "EnterWorktree", "claude --worktree"]),
    subagentDelegation: includesAll(`${hookContext}\n${commandText}\n${agentsText}`, [
      "prometheus-planner",
      "boulder-executor",
      "oracle-verifier",
      "qa-runner",
    ]),
    dynamicWorkflowCommand: existsSync(commandPath),
    hookRoute: hookContext.includes("/lazyclaude:dynamic-workflow"),
  };

  const missing = Object.entries(checks)
    .filter(([, passed]) => !passed)
    .map(([name]) => name);

  return {
    status: missing.length === 0 ? "pass" : "fail",
    version,
    checks,
    missing,
  };
};

export const runWorkflowCheckCli = (root, version, args, io = { stdout: process.stdout, stderr: process.stderr }) => {
  const outputJson = args.includes("--json");
  const report = createWorkflowCheckReport(root, version);
  if (outputJson) {
    io.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
  } else {
    io.stdout.write(`WORKFLOW_CHECK_${report.status.toUpperCase()}\n`);
    for (const [name, passed] of Object.entries(report.checks)) {
      io.stdout.write(`${name}=${passed ? "pass" : "fail"}\n`);
    }
    if (report.missing.length) io.stdout.write(`missing=${report.missing.join(",")}\n`);
  }
  return report.status === "pass" ? 0 : 1;
};
