"use strict";
// src/cli/StoryExecuteCommand.ts
// v1.17.0 — `openlife story execute <id>` Commander subcommand.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.registerStoryExecuteCommand = registerStoryExecuteCommand;
function emitJson(obj) {
    process.stdout.write(`${JSON.stringify(obj, null, 2)}\n`);
}
async function executeCmd(id, opts) {
    const { StoryExecutor } = await Promise.resolve().then(() => __importStar(require('../orchestrator/story/StoryExecutor')));
    const executor = new StoryExecutor();
    const result = await executor.run(id, {
        maxIters: opts.maxIters ? parseInt(opts.maxIters, 10) : undefined,
        persona: opts.persona,
        stopAfter: opts.stopAfter,
        force: opts.force,
        dryRunTests: opts.dryRunTests,
        planOnly: opts.planOnly,
        adapter: opts.adapter,
    });
    if (opts.json) {
        emitJson(result);
        if (!result.ok && result.status !== 'plan-only')
            process.exitCode = 1;
        return;
    }
    // Human-readable rendering.
    if (result.status === 'plan-only') {
        // The executor already wrote the plan. Nothing more here.
        return;
    }
    if (result.status === 'completed') {
        process.stdout.write(`\n✓ Story ${result.storyId} completed in ${result.iterations} iteration(s) (${(result.durationMs / 1000).toFixed(1)}s)\n`);
        process.stdout.write(`  ACs checked this run: ${result.acsCheckedThisRun}\n`);
        process.stdout.write(`  Local commits: ${result.commits.length} (${result.commits.join(', ')})\n`);
        if (result.branch)
            process.stdout.write(`  Branch: ${result.branch}\n`);
        process.stdout.write(`\n  Run \`openlife ship\` to push (v1.18+) or \`git push -u origin ${result.branch || 'HEAD'}\`\n`);
        return;
    }
    // halted / failed
    process.stderr.write(`\n❌ Story ${result.storyId} ${result.status}: ${result.reason || 'unknown'}\n`);
    process.stderr.write(`  Iterations: ${result.iterations}\n`);
    process.stderr.write(`  ACs checked: ${result.acsCheckedThisRun}\n`);
    if (result.errors && result.errors.length > 0) {
        process.stderr.write(`  Errors:\n`);
        for (const e of result.errors.slice(0, 10))
            process.stderr.write(`    - ${e}\n`);
        if (result.errors.length > 10)
            process.stderr.write(`    …and ${result.errors.length - 10} more\n`);
    }
    process.exitCode = 1;
}
function registerStoryExecuteCommand(storyCommand) {
    storyCommand
        .command('execute <id>')
        .description('v1.17.0 — Autonomously execute a story to Done via the persona loop.')
        .option('--max-iters <n>', 'Cap on iterations (default 10, max 50)')
        .option('--persona <name>', 'Force a single persona for all iterations')
        .option('--stop-after <persona>', 'Halt after this persona (e.g. --stop-after=builder skips QA gate)')
        .option('--force', 'Allow a dirty working tree')
        .option('--dry-run-tests', 'Skip running tests (use when source mutation is dry)')
        .option('--plan-only', 'Print plan + persona pick without executing')
        .option('--adapter <id>', 'Force host adapter: claude | gemini | codex | mock')
        .option('--json', 'Emit JSON result instead of human-readable.')
        .action((id, opts) => { void executeCmd(id, opts); });
}
