import type { Command } from 'commander';
import { withAuth } from './with-auth.js';
import { fetchProjects } from '../tui/gateway-api.js';

export function registerPrdyCommand(program: Command) {
  const cmd = program
    .command('prdy')
    .description('PRD wizard — create and manage Product Requirement Documents')
    .option('-g, --gateway <url>', 'Gateway URL', 'http://localhost:14242')
    .option('--init [name]', 'Create a new PRD')
    .option('--update [name]', 'Update an existing PRD')
    .option('--project <idOrName>', 'Scope to project')
    .action(
      async (opts: {
        gateway: string;
        init?: string | boolean;
        update?: string | boolean;
        project?: string;
      }) => {
        // Detect project context when --project flag is provided
        if (opts.project) {
          try {
            const auth = await withAuth(opts.gateway);
            const projects = await fetchProjects(auth.gateway, auth.cookie);
            const match = projects.find((p) => p.id === opts.project || p.name === opts.project);
            if (match) {
              console.log(`Project context: ${match.name} (${match.id})\n`);
            }
          } catch {
            // Gateway not available — proceed without project context
          }
        }

        try {
          const { runPrdWizard } = await import('@mosaicstack/prdy');
          const name =
            typeof opts.init === 'string'
              ? opts.init
              : typeof opts.update === 'string'
                ? opts.update
                : 'untitled';
          await runPrdWizard({
            name,
            projectPath: process.cwd(),
            interactive: true,
          });
        } catch (err) {
          console.error(`PRD wizard failed: ${err instanceof Error ? err.message : String(err)}`);
          process.exit(1);
        }
      },
    );

  return cmd;
}
