"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createWorkflowCompileCommand = createWorkflowCompileCommand;
const errors_1 = require("../../../lib/errors");
const output_1 = require("../../../lib/output");
const planning_navigation_1 = require("../../../lib/planning/planning-navigation");
const lifecycle_flight_plan_1 = require("../../../lib/planning/lifecycle-flight-plan");
const runtime_contract_1 = require("../../../lib/runtime/runtime-contract");
const global_format_1 = require("../global-format");
async function createWorkflowCompileCommand() {
    const { Command } = await import('commander');
    const command = new Command('compile');
    command
        .description('Compile a named lifecycle profile and canonical phase artifact into a revision-bound read-only gate graph.')
        .requiredOption('--profile <identity>', 'Exact lifecycle profile identity from the authoritative workflow guide.')
        .requiredOption('--artifact <path>', 'Repository-relative canonical phase-overview.md path to compile.')
        .option('--run-directory <path>', 'Optional canonical .day-shift/runs/run-<run-id> manifest used to project current gate evidence.')
        .option('--actor <identity>', 'Optional observed actor used only to resolve command skeleton inputs.')
        .option('--at <timestamp>', 'Optional observed ISO-8601 time used only to resolve command skeleton inputs.')
        .option('--metadata-posture <posture>', 'Optional observed posture: read-only or sync-on-clean-review.')
        .option('--authorization <state>', 'Optional observed authority state: authorized or not-authorized; compilation never grants authority.')
        .option('--expected-plan-revision <sha256>', 'Optional prior plan revision that must still match all canonical inputs.')
        .addHelpText('after', '\nSupported formats: text, json.\nRead-only: compilation performs no gate, write, selection, or authorization.\nUse --detail full or --page-lane gates --page-size <n> to recover the complete graph.')
        .action((_, commandInstance) => {
        const format = (0, output_1.resolveOutputFormat)((0, global_format_1.getGlobalFormat)(commandInstance));
        if (format === null) {
            throw (0, errors_1.createUnsupportedOutputFormatError)({
                received: (0, global_format_1.getGlobalFormat)(commandInstance),
                commandBoundary: 'workflow compile command output format',
            });
        }
        const repositoryContext = resolveRepositoryContext(commandInstance);
        const options = commandInstance.opts();
        let plan;
        try {
            plan = (0, planning_navigation_1.compileWorkflowForArtifact)({
                repositoryRoot: repositoryContext.root,
                profile: options.profile,
                artifactPath: options.artifact,
                runDirectory: options.runDirectory,
                actor: options.actor,
                observedAt: options.at,
                metadataPosture: options.metadataPosture,
                authorization: options.authorization,
                expectedPlanRevision: options.expectedPlanRevision,
            });
        }
        catch (error) {
            if (!(error instanceof lifecycle_flight_plan_1.LifecycleFlightPlanCompileError))
                throw error;
            throw (0, errors_1.createUsageError)(`${error.code}: ${error.message}`, error.findings.map((finding) => `${finding.path}:${finding.line ?? 1} [${finding.code}] ${finding.message}`));
        }
        const data = shouldProjectCompact(format)
            ? {
                repositoryRoot: repositoryContext.root,
                detectionSource: repositoryContext.detectionSource,
                ...(0, planning_navigation_1.projectCompactWorkflowFlightPlan)(plan),
            }
            : {
                repositoryRoot: repositoryContext.root,
                detectionSource: repositoryContext.detectionSource,
                ...plan,
            };
        (0, output_1.emitSuccess)({
            command: 'workflow compile',
            format,
            text: (0, planning_navigation_1.renderWorkflowFlightPlan)(plan),
            data,
            findings: plan.findings.map((finding) => ({
                code: finding.code,
                severity: finding.severity,
                path: finding.path,
                message: finding.message,
            })),
        });
    });
    return command;
}
function shouldProjectCompact(format) {
    if (format !== 'json')
        return false;
    if (process.argv.some((token) => token === '--page-lane' || token.startsWith('--page-lane=')))
        return false;
    const detailIndex = process.argv.findIndex((token) => token === '--detail');
    const explicitDetail = detailIndex >= 0
        ? process.argv[detailIndex + 1]
        : process.argv.find((token) => token.startsWith('--detail='))?.slice('--detail='.length);
    return explicitDetail === undefined || explicitDetail === 'compact';
}
function resolveRepositoryContext(commandInstance) {
    const rootCommand = (commandInstance?.parent?.parent ?? commandInstance);
    if (rootCommand?.configRepositoryContext)
        return rootCommand.configRepositoryContext;
    return (0, runtime_contract_1.createRepositoryContext)((0, runtime_contract_1.detectRepositoryRoot)(), false);
}
