#!/usr/bin/env node
// Copyright (c) 2026 Hellmai Ltd
// SPDX-License-Identifier: AGPL-3.0-only
/**
 * Orchestrate Initiative CLI
 *
 * Orchestrate initiative execution with parallel agent spawning.
 * Builds execution plan based on WU dependencies and manages wave-based execution.
 *
 * WU-2375: Added --client parameter for client-capability-aware output.
 *
 * Usage:
 *   pnpm orchestrate:initiative --initiative INIT-001
 *   pnpm orchestrate:initiative --initiative INIT-001 --dry-run
 *   pnpm orchestrate:initiative --initiative INIT-001 --client codex-cli
 */
import { Command } from 'commander';
import chalk from 'chalk';
import { loadInitiativeWUs, loadMultipleInitiatives, buildExecutionPlanWithLockPolicy, resolveLaneConfigsFromConfig, formatExecutionPlan, formatExecutionPlanWithEmbeddedSpawns, calculateProgress, formatProgress, buildCheckpointWave, formatCheckpointOutput, validateCheckpointFlags, resolveCheckpointModeAsync, LOG_PREFIX, } from '@lumenflow/initiatives';
import { EXIT_CODES } from '@lumenflow/core/wu-constants';
import { getConfig } from '@lumenflow/core/config';
import { getErrorMessage, ProcessExitError } from '@lumenflow/core/error-handler';
import { runCLI } from './cli-entry-point.js';
const VALID_CLIENTS = ['claude-code', 'codex-cli', 'gemini-cli', 'cursor', 'windsurf'];
const program = new Command()
    .name('orchestrate-initiative')
    .description('Orchestrate initiative execution with parallel agent spawning')
    .option('-i, --initiative <ids...>', 'Initiative ID(s) to orchestrate')
    .option('-d, --dry-run', 'Show execution plan without spawning agents')
    .option('-p, --progress', 'Show current progress only')
    .option('-c, --checkpoint-per-wave', 'Spawn next wave then exit (no polling)')
    .option('--no-checkpoint', 'Force polling mode')
    .option('--client <name>', 'Agent client (claude-code, codex-cli, gemini-cli, cursor, windsurf)')
    .action(async (options) => {
    const { initiative: initIds, dryRun, progress: progressOnly, checkpointPerWave, checkpoint, client: clientArg, } = options;
    const noCheckpoint = checkpoint === false;
    try {
        validateCheckpointFlags({ checkpointPerWave, dryRun, noCheckpoint });
    }
    catch (error) {
        const message = `${LOG_PREFIX} Error: ${getErrorMessage(error)}`;
        console.error(chalk.red(message));
        throw new ProcessExitError(message, EXIT_CODES.ERROR);
    }
    // WU-2375: Resolve client name
    const config = getConfig();
    const clientName = clientArg || config.agents?.defaultClient || undefined;
    if (clientArg && !VALID_CLIENTS.includes(clientArg)) {
        console.warn(chalk.yellow(`${LOG_PREFIX} Warning: Unknown client '${clientArg}'. ` +
            `Valid clients: ${VALID_CLIENTS.join(', ')}`));
    }
    if (clientName) {
        console.log(chalk.cyan(`${LOG_PREFIX} Client: ${clientName}`));
    }
    if (!initIds || initIds.length === 0) {
        const message = `${LOG_PREFIX} Error: --initiative is required`;
        console.error(chalk.red(message));
        console.error('');
        console.error('Usage:');
        console.error('  pnpm orchestrate:initiative --initiative INIT-001');
        console.error('  pnpm orchestrate:initiative --initiative INIT-001 --dry-run');
        console.error('  pnpm orchestrate:initiative --initiative INIT-001 --client codex-cli');
        throw new ProcessExitError(message, EXIT_CODES.ERROR);
    }
    try {
        console.log(chalk.cyan(`${LOG_PREFIX} Loading initiative(s): ${initIds.join(', ')}`));
        let wus;
        let initiative;
        if (initIds.length === 1) {
            const result = loadInitiativeWUs(initIds[0]);
            initiative = result.initiative;
            wus = result.wus;
        }
        else {
            wus = loadMultipleInitiatives(initIds);
            initiative = { id: 'MULTI', title: `Combined: ${initIds.join(', ')}` };
        }
        console.log(chalk.green(`${LOG_PREFIX} Loaded ${wus.length} WU(s)`));
        console.log('');
        const progress = calculateProgress(wus);
        console.log(chalk.bold('Progress:'));
        console.log(formatProgress(progress));
        console.log('');
        if (progressOnly) {
            return;
        }
        const checkpointDecision = await resolveCheckpointModeAsync({ checkpointPerWave, noCheckpoint, dryRun }, wus);
        if (checkpointDecision.enabled) {
            if (initIds.length > 1) {
                const message = `${LOG_PREFIX} Error: Checkpoint mode only supports single initiative`;
                console.error(chalk.red(message));
                throw new ProcessExitError(message, EXIT_CODES.ERROR);
            }
            const waveData = buildCheckpointWave(initIds[0], { dryRun });
            if (!waveData) {
                console.log(chalk.green(`${LOG_PREFIX} All WUs are complete! Nothing to spawn.`));
                return;
            }
            // WU-2375: Pass clientName to checkpoint output formatting
            console.log(formatCheckpointOutput({ ...waveData, dryRun, clientName }));
            return;
        }
        console.log(chalk.cyan(`${LOG_PREFIX} Building execution plan...`));
        const laneConfigs = resolveLaneConfigsFromConfig(config);
        const plan = buildExecutionPlanWithLockPolicy(wus, { laneConfigs });
        if (plan.waves.length === 0) {
            // WU-1906: Distinguish all-done from all-blocked
            const hasPending = plan.deferred.length > 0 || plan.skippedWithReasons.length > 0;
            if (hasPending) {
                const pendingCount = plan.deferred.length + plan.skippedWithReasons.length;
                console.log(chalk.yellow(`${LOG_PREFIX} ${pendingCount} WU(s) still pending but none are unblocked.`));
                if (plan.deferred.length > 0) {
                    console.log(chalk.yellow(`${LOG_PREFIX}   ${plan.deferred.length} deferred (waiting for dependencies)`));
                }
                if (plan.skippedWithReasons.length > 0) {
                    console.log(chalk.yellow(`${LOG_PREFIX}   ${plan.skippedWithReasons.length} skipped (non-ready status)`));
                }
            }
            else {
                console.log(chalk.green(`${LOG_PREFIX} All WUs are complete! Nothing to execute.`));
            }
            return;
        }
        console.log('');
        console.log(chalk.bold('Execution Plan:'));
        console.log(formatExecutionPlan(initiative, plan));
        if (dryRun) {
            console.log(chalk.yellow(`${LOG_PREFIX} Dry run mode - no agents spawned`));
            console.log('');
            console.log(chalk.bold('Next Steps (Recommended Defaults):'));
            console.log('');
            console.log(chalk.cyan('  Option 1 (Recommended): Checkpoint-per-wave mode'));
            console.log('    pnpm orchestrate:initiative -i ' + initIds[0] + ' -c');
            console.log('    Best for: Large initiatives, context management, idempotent resumption');
            console.log('');
            console.log(chalk.cyan('  Option 2: Full execution (polling mode)'));
            console.log('    pnpm orchestrate:initiative -i ' + initIds[0]);
            console.log('    Best for: Small initiatives (<4 WUs), quick execution');
            console.log('');
            console.log(chalk.cyan('  Option 3: Manual briefing/delegation per WU'));
            console.log('    pnpm wu:brief --id <WU-ID> --client <client>');
            console.log('    pnpm wu:delegate --id <WU-ID> --parent-wu <PARENT-WU-ID> --client <client>');
            console.log('    Best for: Testing, debugging, explicit lineage tracking');
            console.log('');
            console.log(chalk.bold('Monitoring Commands:'));
            console.log('  pnpm mem:inbox --since 10m          # Check for signals from agents');
            console.log('  pnpm orchestrate:init-status -i ' + initIds[0] + '   # Check progress');
            console.log('  pnpm orchestrate:monitor            # Live agent activity');
            return;
        }
        // WU-1202: Output spawn content for actual execution (not dry-run)
        // WU-2375: Format varies by client capability (XML for Claude, markdown for others)
        console.log('');
        console.log(chalk.bold('Spawn Commands:'));
        console.log(formatExecutionPlanWithEmbeddedSpawns(plan, clientName));
        console.log(chalk.green(`${LOG_PREFIX} Execution plan output complete.`));
        if (!clientName || clientName === 'claude-code') {
            console.log(chalk.cyan('Copy the spawn XML above to execute agents.'));
        }
        else {
            console.log(chalk.cyan('Copy the prompts above to your agent platform.'));
        }
    }
    catch (error) {
        if (error instanceof ProcessExitError) {
            throw error;
        }
        const message = `${LOG_PREFIX} Error: ${getErrorMessage(error)}`;
        console.error(chalk.red(message));
        throw new ProcessExitError(message, EXIT_CODES.ERROR);
    }
});
export async function main() {
    await program.parseAsync(process.argv);
}
if (import.meta.main) {
    void runCLI(main);
}
//# sourceMappingURL=orchestrate-initiative.js.map