#!/usr/bin/env node

"use strict";

/**
 * state-restore.js — Read and parse .claude/STATE.md for session resume.
 *
 * Usage:
 *   node state-restore.js [--path .claude/STATE.md]
 *
 * Exit codes:
 *   0 = success (exists or not)
 *   1 = parse 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];
}

/**
 * Parse a STATE.md file into a structured object.
 * @param {string} content - Raw markdown content
 * @returns {object} Parsed state fields
 */
function parseState(content) {
  const state = {
    command: "",
    feature: "",
    plan_path: "",
    mode: "",
    flags: "",
    branch: "",
    stopped_at: "",
    completed: [],
    remaining: [],
    timestamp: "",
  };

  const lines = content.split("\n");

  // Parse header fields (key: value lines)
  for (const line of lines) {
    const match = line.match(
      /^(Command|Feature|Plan|Mode|Flags|Branch):\s*(.*)/,
    );
    if (match) {
      const key = match[1].toLowerCase();
      const value = match[2].trim();
      if (key === "plan") state.plan_path = value;
      else state[key] = value;
    }
  }

  // Parse sections
  let section = null;
  for (const line of lines) {
    if (line.startsWith("## Stopped at")) {
      section = "stopped_at";
      continue;
    }
    if (line.startsWith("## Completed")) {
      section = "completed";
      continue;
    }
    if (line.startsWith("## Remaining")) {
      section = "remaining";
      continue;
    }
    if (line.startsWith("## Timestamp")) {
      section = "timestamp";
      continue;
    }
    if (line.startsWith("## ") || line.startsWith("# ")) {
      section = null;
      continue;
    }

    if (section === "stopped_at" && line.trim()) {
      state.stopped_at = line.trim();
    }
    if (section === "timestamp" && line.trim()) {
      state.timestamp = line.trim();
    }
    if (section === "completed" && line.startsWith("- ")) {
      state.completed.push(line.slice(2).trim());
    }
    if (section === "remaining" && line.startsWith("- ")) {
      state.remaining.push(line.slice(2).trim());
    }
  }

  return state;
}

/**
 * Read and parse STATE.md.
 * @returns {{exists: boolean, state?: object}}
 */
function stateRestore(statePath) {
  const resolved = statePath || resolveStatePath();

  if (!fs.existsSync(resolved)) {
    return { exists: false };
  }

  const content = fs.readFileSync(resolved, "utf-8");
  const state = parseState(content);
  return { exists: true, state };
}

function main() {
  const args = process.argv.slice(2);
  const customPath = parseFlag(args, "--path");
  const result = stateRestore(customPath);
  console.log(JSON.stringify(result));
}

module.exports = { stateRestore, parseState, resolveStatePath };

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