#!/usr/bin/env node

/**
 * Fast-path CLI for high-frequency state commands.
 * Bypasses oclif bootstrap (~15-20s in linked ESM dev mode) by importing
 * only the service modules directly. Startup: ~200ms.
 *
 * Usage:
 *   sa-fast task list [--json] [--status <status>]
 *   sa-fast task create --summary <text> [--profile <id>] [--id <id>]
 *   sa-fast task claim --id <id> [--profile <role>]
 *   sa-fast task done --id <id> [--profile <role>]
 *   sa-fast evidence add --summary <text> --task <id> [--role <role>] [--type <kind>]
 *   sa-fast workflow pending [--json]
 */

import { join } from 'node:path';
import { existsSync } from 'node:fs';

const cwd = process.cwd();
const args = process.argv.slice(2);

function flag(name) {
  const idx = args.indexOf(`--${name}`);
  if (idx === -1) return undefined;
  return args[idx + 1];
}

function hasFlag(name) {
  return args.indexOf(`--${name}`) !== -1;
}

function exitJson(data) {
  process.stdout.write(JSON.stringify({ status: 0, result: data }, null, 2) + '\n');
  process.exit(0);
}

function exitText(msg) {
  process.stdout.write(msg + '\n');
  process.exit(0);
}

function exitError(msg, code = 1) {
  process.stderr.write(`Error: ${msg}\n`);
  process.exit(code);
}

const stateDir = join(cwd, '.setup-agents', 'state');
if (!existsSync(join(cwd, '.setup-agents', 'config.json'))) {
  exitError('Not a setup-agents project (missing .setup-agents/config.json). Run "sf setup-agents init" first.');
}

const [domain, command] = [args[0], args[1]];

async function main() {
  const { createTask, listTasks, getTask, claimTask, completeTask, taskStatePath } = await import(
    '../lib/services/task-state.js'
  );

  if (domain === 'task') {
    if (command === 'list') {
      const status = flag('status');
      const tasks = listTasks(cwd, status ? { status } : {});
      if (hasFlag('json')) {
        exitJson({ records: tasks, file: taskStatePath(cwd) });
      }
      if (tasks.length === 0) {
        exitText('No tasks found.');
      }
      for (const t of tasks) {
        process.stdout.write(`${t.id}\t${t.status}\t${t.owner ?? ''}\t${t.summary}\n`);
      }
      process.exit(0);
    }

    if (command === 'create') {
      const summary = flag('summary');
      if (!summary) exitError('--summary is required');
      const id = flag('id');
      const profile = flag('profile') ?? flag('role');
      const record = createTask(cwd, { id, summary, profile });
      if (hasFlag('json')) {
        exitJson({ record, file: taskStatePath(cwd) });
      }
      exitText(`Created task ${record.id}`);
    }

    if (command === 'claim') {
      const id = flag('id') ?? flag('task');
      if (!id) exitError('--id is required');
      if (!getTask(cwd, id)) exitError(`Task not found: ${id}`);
      const profile = flag('profile') ?? flag('role') ?? 'developer';
      const record = claimTask(cwd, { id, profile });
      if (hasFlag('json')) {
        exitJson({ record, file: taskStatePath(cwd) });
      }
      exitText(`Claimed task ${record.id} as ${record.owner}`);
    }

    if (command === 'done') {
      const id = flag('id') ?? flag('task');
      if (!id) exitError('--id is required');
      if (!getTask(cwd, id)) exitError(`Task not found: ${id}`);
      const profile = flag('profile') ?? flag('role');
      const record = completeTask(cwd, { id, profile });
      if (hasFlag('json')) {
        exitJson({ record, file: taskStatePath(cwd) });
      }
      exitText(`Completed task ${record.id}`);
    }

    exitError(`Unknown task command: ${command}. Available: list, create, claim, done`);
  }

  if (domain === 'evidence') {
    if (command === 'add') {
      const { addEvidenceRecord, recordPath } = await import('../lib/services/orchestration-records.js');
      const summary = flag('summary');
      if (!summary) exitError('--summary is required');
      const task = flag('task');
      const profile = flag('profile') ?? flag('role') ?? 'developer';
      const evidenceKind = flag('type') ?? flag('kind') ?? 'other';
      const record = addEvidenceRecord(cwd, {
        summary,
        profile,
        taskIds: task ? [task] : [],
        evidenceKind,
        command: flag('command'),
        path: flag('path'),
        details: flag('details'),
      });
      const file = recordPath(cwd, 'evidence');
      if (hasFlag('json')) {
        exitJson({ record, file });
      }
      exitText(`Created evidence ${record.id}`);
    }
    exitError(`Unknown evidence command: ${command}. Available: add`);
  }

  if (domain === 'workflow') {
    if (command === 'pending') {
      const { listWorkflowRuns, pausedPhaseAndNext, midPhaseGates, workflowRunPath } = await import(
        '../lib/services/workflow-state.js'
      );
      const { PHASE_TO_PROFILE } = await import('../lib/services/workflow-instructions.js');
      const file = workflowRunPath(cwd);
      const runs = listWorkflowRuns(cwd).filter((r) => r.status === 'paused' || r.status === 'running');
      const items = [];

      for (const run of runs) {
        if (run.status === 'paused') {
          const gate = pausedPhaseAndNext(run, cwd);
          if (gate) {
            const reviewer = PHASE_TO_PROFILE[gate.nextPhase];
            items.push({
              runId: run.id,
              storyId: run.storyId,
              pausedPhase: gate.pausedPhase,
              nextPhase: gate.nextPhase,
              reviewId: gate.reviewId,
              kind: 'transition',
              approveCommand: `sf setup-agents review complete --id ${gate.reviewId} --result approved --reviewer ${reviewer}`,
              resumeCommand: `sf setup-agents workflow run --story ${run.storyId} --resume ${run.id}`,
            });
          }
        }
        for (const midGate of midPhaseGates(run)) {
          const phaseRecord = run.phases.find((p) => p.phase === midGate.phase);
          const reviewer = phaseRecord ? PHASE_TO_PROFILE[midGate.phase] : 'reviewer';
          items.push({
            runId: run.id,
            storyId: run.storyId,
            pausedPhase: midGate.phase,
            nextPhase: undefined,
            reviewId: midGate.reviewId,
            kind: 'mid-phase',
            approveCommand: `sf setup-agents review complete --id ${midGate.reviewId} --result approved --reviewer ${reviewer}`,
            resumeCommand: `sf setup-agents workflow run --story ${run.storyId} --resume ${run.id}`,
          });
        }
      }

      if (hasFlag('json')) {
        exitJson({ items, file });
      }
      if (items.length === 0) {
        exitText('No pending workflow actions.');
      }
      for (const item of items) {
        process.stdout.write(`[${item.kind}] ${item.runId} story=${item.storyId} phase=${item.pausedPhase}\n`);
        process.stdout.write(`  approve: ${item.approveCommand}\n`);
        process.stdout.write(`  resume:  ${item.resumeCommand}\n`);
      }
      process.exit(0);
    }
    exitError(`Unknown workflow command: ${command}. Available: pending`);
  }

  exitError(
    `Unknown domain: ${domain}. Available: task, evidence, workflow\n\nUsage:\n  sa-fast task list [--json]\n  sa-fast task create --summary <text>\n  sa-fast task claim --id <id>\n  sa-fast task done --id <id>\n  sa-fast evidence add --summary <text> --task <id>\n  sa-fast workflow pending [--json]`
  );
}

main().catch((err) => {
  exitError(err.message);
});
