/** CLI entry: run a Han-style flow through the deterministic code conductor. */
import { writeFile } from 'node:fs/promises';
import { runFlow } from './flow.js';
import { getFlow, describeFlows, FLOW_NAMES } from './flows/index.js';
import type { Band } from './types.js';

const argv = process.argv.slice(2);
const positional = argv.filter((a: string) => !a.startsWith('--'));
const flowName = positional[0];
const question = positional.slice(1).join(' ').trim();

const flow = flowName ? getFlow(flowName) : undefined;
if (!flow || !question) {
  console.error('usage: tsx src/run.ts <flow> "<question>" [--size=small|medium|large] [--repo=/abs/path] [--fast]\n');
  console.error('flows:');
  console.error(describeFlows());
  if (flowName && !flow) console.error(`\nunknown flow "${flowName}" — choose one of: ${FLOW_NAMES.join(', ')}`);
  process.exit(1);
}

const repoArg = argv.find((a: string) => a.startsWith('--repo='));
const sizeArg = argv.find((a: string) => a.startsWith('--size='));
const concise = argv.includes('--fast') || argv.includes('--concise');
const band = (sizeArg ? sizeArg.slice('--size='.length) : 'small') as Band;

const input = {
  question,
  band,
  ...(repoArg ? { repoPath: repoArg.slice('--repo='.length) } : {}),
  ...(concise ? { concise: true } : {}),
};

const started = Date.now();
console.error(`conductor: "${flow.name}" — band=${band}${concise ? ' fast' : ''}`);
const { outputPath, artifact } = await runFlow(flow, input, { onLog: (m) => console.error(m) });
const path = outputPath ?? `conductor-report-${flow.name}.md`;
await writeFile(path, artifact, 'utf8');
console.error(`\n✓ conductor done in ${Math.round((Date.now() - started) / 1000)}s → ${path}`);
