// cli/router.ts — Command dispatch for CLI mode (SPEC-124)
import { parseArgs } from 'node:util';
import { PLANU_VERSION } from '../config/version.js';
import { red, bold, cyan, dim } from './colors.js';
// Lazy-load commands to avoid importing tool handlers when not needed
async function loadCommands() {
    const [{ initCommand }, { createCommand }, { listCommand }, { statusCommand }, { estimateCommand }, { validateCommand }, { dashboardCommand }, { auditCommand }, { serveCommand }, { handoffCommand }, { watchCommand }, { installCommand }, { doctorCommand }, { uninstallCommand }, { activateCommand }, { specCommand }, { healthCommand }, { releaseCommand },] = await Promise.all([
        import('./commands/init.js'),
        import('./commands/create.js'),
        import('./commands/list.js'),
        import('./commands/status.js'),
        import('./commands/estimate.js'),
        import('./commands/validate.js'),
        import('./commands/dashboard.js'),
        import('./commands/audit.js'),
        import('./commands/serve.js'),
        import('./commands/handoff.js'),
        import('./commands/watch.js'),
        import('./commands/install.js'),
        import('./commands/doctor.js'),
        import('./commands/uninstall.js'),
        import('./commands/activate.js'),
        import('./commands/spec.js'),
        import('./commands/health.js'),
        import('./commands/release.js'),
    ]);
    const cmds = [
        initCommand,
        createCommand,
        listCommand,
        statusCommand,
        estimateCommand,
        validateCommand,
        dashboardCommand,
        auditCommand,
        serveCommand,
        handoffCommand,
        watchCommand,
        installCommand,
        doctorCommand,
        uninstallCommand,
        activateCommand,
        specCommand,
        healthCommand,
        releaseCommand,
    ];
    const map = new Map();
    for (const cmd of cmds) {
        map.set(cmd.name, cmd);
    }
    return map;
}
function printHelp(commands) {
    const lines = [
        `${bold('planu')} ${dim(`v${PLANU_VERSION}`)} — Spec Driven Development CLI`,
        '',
        `${cyan('Usage:')} planu <command> [options]`,
        '',
        cyan('Commands:'),
    ];
    for (const cmd of commands.values()) {
        lines.push(`  ${cmd.name.padEnd(14)} ${dim(cmd.description)}`);
    }
    lines.push('');
    lines.push(cyan('Global options:'));
    lines.push('  --help       Show help');
    lines.push('  --version    Show version');
    lines.push('  --json       Output raw JSON (for scripting)');
    lines.push('  --quiet      Suppress non-essential output');
    lines.push('  --verbose    Include stack traces on errors');
    process.stdout.write(lines.join('\n') + '\n');
}
/**
 * Parse the first arg as a command name and dispatch to the appropriate handler.
 */
export async function route(args) {
    // Handle global flags
    const { values } = parseArgs({
        args,
        options: {
            help: { type: 'boolean', short: 'h' },
            version: { type: 'boolean' },
            json: { type: 'boolean' },
            quiet: { type: 'boolean', short: 'q' },
            verbose: { type: 'boolean' },
        },
        strict: false,
        allowPositionals: true,
    });
    const globalFlags = {
        json: values.json,
        quiet: values.quiet,
        verbose: values.verbose,
    };
    if (values.version) {
        process.stdout.write(`planu ${PLANU_VERSION}\n`);
        return;
    }
    const commands = await loadCommands();
    if (values.help && args.length <= 1) {
        printHelp(commands);
        return;
    }
    const commandName = args[0];
    if (!commandName || commandName === 'help') {
        printHelp(commands);
        return;
    }
    if (commandName === 'version') {
        process.stdout.write(`planu ${PLANU_VERSION}\n`);
        return;
    }
    const cmd = commands.get(commandName);
    if (!cmd) {
        process.stderr.write(`${red('Error:')} Unknown command "${commandName}"\n`);
        process.stderr.write(`Run ${cyan('planu --help')} to see available commands.\n`);
        process.exitCode = 1;
        return;
    }
    try {
        await cmd.run(args.slice(1), globalFlags);
    }
    catch (err) {
        const message = err instanceof Error ? err.message : String(err);
        process.stderr.write(`${red('Error:')} ${message}\n`);
        if (globalFlags.verbose && err instanceof Error && err.stack) {
            process.stderr.write(`${dim(err.stack)}\n`);
        }
        process.exitCode = 1;
    }
}
//# sourceMappingURL=router.js.map