#!/usr/bin/env node

"use strict";

/**
 * state-save.js — Write session state to .claude/STATE.md for resume.
 *
 * Usage:
 *   node state-save.js --command "/eck:design" --feature "my-feature" --mode standard \
 *     --stopped-at "Stage 3" --branch main \
 *     [--plan-path .claude/TASKS.md] [--flags "--trace"] \
 *     [--completed "Stage 1,Stage 2"] [--remaining "Stage 4,Stage 5"]
 *
 * Exit codes:
 *   0 = success
 *   1 = error
 */

const fs = require("fs");
const path = require("path");

function resolveStatePath(customPath) {
  if (customPath) return customPath;
  const cwd = process.env.CLAUDE_PROJECT_DIR || process.cwd();
  return path.join(cwd, ".claude", "STATE.md");
}

function parseFlag(args, flag) {
  const idx = args.indexOf(flag);
  if (idx === -1 || idx + 1 >= args.length) return null;
  return args[idx + 1];
}

/**
 * Format state as markdown per the STATE.md spec.
 */
function formatState(state) {
  const lines = ["# ECK Session State", ""];
  lines.push(`Command: ${state.command || ""}`);
  lines.push(`Feature: ${state.feature || ""}`);
  lines.push(`Plan: ${state.plan_path || ""}`);
  lines.push(`Mode: ${state.mode || ""}`);
  lines.push(`Flags: ${state.flags || ""}`);
  lines.push(`Branch: ${state.branch || ""}`);
  lines.push("");
  lines.push("## Stopped at");
  lines.push(state.stopped_at || "");
  lines.push("");
  lines.push("## Completed");
  if (state.completed && state.completed.length > 0) {
    for (const item of state.completed) {
      lines.push(`- ${item}`);
    }
  } else {
    lines.push("(none)");
  }
  lines.push("");
  lines.push("## Remaining");
  if (state.remaining && state.remaining.length > 0) {
    for (const item of state.remaining) {
      lines.push(`- ${item}`);
    }
  } else {
    lines.push("(none)");
  }
  lines.push("");
  lines.push("## Timestamp");
  lines.push(state.timestamp || new Date().toISOString());
  lines.push("");
  return lines.join("\n");
}

/**
 * Write STATE.md atomically.
 * @returns {{success: boolean, path: string}}
 */
function stateSave(state, statePath) {
  const resolved = statePath || resolveStatePath();
  const dir = path.dirname(resolved);
  fs.mkdirSync(dir, { recursive: true });

  const content = formatState(state);
  const tmpPath = resolved + ".tmp";
  fs.writeFileSync(tmpPath, content, "utf-8");
  fs.renameSync(tmpPath, resolved);

  return { success: true, path: resolved };
}

function main() {
  const args = process.argv.slice(2);

  const state = {
    command: parseFlag(args, "--command"),
    feature: parseFlag(args, "--feature"),
    plan_path: parseFlag(args, "--plan-path"),
    mode: parseFlag(args, "--mode"),
    flags: parseFlag(args, "--flags"),
    branch: parseFlag(args, "--branch"),
    stopped_at: parseFlag(args, "--stopped-at"),
    completed: (parseFlag(args, "--completed") || "")
      .split(",")
      .map((s) => s.trim())
      .filter(Boolean),
    remaining: (parseFlag(args, "--remaining") || "")
      .split(",")
      .map((s) => s.trim())
      .filter(Boolean),
    timestamp: new Date().toISOString(),
  };

  if (!state.command) {
    console.error("Usage: state-save --command <cmd> --feature <feat> ...");
    process.exit(1);
  }

  const customPath = parseFlag(args, "--path");
  const result = stateSave(state, customPath);
  console.log(JSON.stringify(result));
}

module.exports = { stateSave, formatState, resolveStatePath };

if (require.main === module) {
  main();
}
