import { Command } from 'commander';

import { createPrd, listPrds, loadPrd } from './prd.js';
import { runPrdWizard } from './wizard.js';

interface InitCommandOptions {
  readonly name: string;
  readonly project: string;
  readonly template?: 'software' | 'feature' | 'spike';
}

interface ListCommandOptions {
  readonly project: string;
}

interface ShowCommandOptions {
  readonly project: string;
  readonly id?: string;
}

export function buildPrdyCli(): Command {
  const program = new Command();
  program.name('mosaic').description('Mosaic CLI').exitOverride();

  const prdy = program.command('prdy').description('PRD wizard commands');

  prdy
    .command('init')
    .description('Create a PRD document')
    .requiredOption('--name <name>', 'PRD name')
    .requiredOption('--project <path>', 'Project path')
    .option('--template <template>', 'Template (software|feature|spike)')
    .action(async (options: InitCommandOptions) => {
      const doc = process.stdout.isTTY
        ? await runPrdWizard({
            name: options.name,
            projectPath: options.project,
            template: options.template,
            interactive: true,
          })
        : await createPrd({
            name: options.name,
            projectPath: options.project,
            template: options.template,
            interactive: false,
          });

      console.log(
        JSON.stringify(
          {
            ok: true,
            id: doc.id,
            title: doc.title,
            status: doc.status,
            projectPath: doc.projectPath,
          },
          null,
          2,
        ),
      );
    });

  prdy
    .command('list')
    .description('List PRD documents for a project')
    .requiredOption('--project <path>', 'Project path')
    .action(async (options: ListCommandOptions) => {
      const docs = await listPrds(options.project);
      console.log(JSON.stringify(docs, null, 2));
    });

  prdy
    .command('show')
    .description('Show a PRD document')
    .requiredOption('--project <path>', 'Project path')
    .option('--id <id>', 'PRD document id')
    .action(async (options: ShowCommandOptions) => {
      if (options.id !== undefined) {
        const docs = await listPrds(options.project);
        const match = docs.find((doc) => doc.id === options.id);

        if (match === undefined) {
          throw new Error(`PRD id not found: ${options.id}`);
        }

        console.log(JSON.stringify(match, null, 2));
        return;
      }

      const doc = await loadPrd(options.project);
      console.log(JSON.stringify(doc, null, 2));
    });

  return program;
}

export async function runPrdyCli(argv: readonly string[] = process.argv): Promise<void> {
  const program = buildPrdyCli();
  await program.parseAsync(argv);
}
