"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createWorkflowExplainCommand = createWorkflowExplainCommand;
const errors_1 = require("../../../lib/errors");
const output_1 = require("../../../lib/output");
const planning_navigation_1 = require("../../../lib/planning/planning-navigation");
const runtime_contract_1 = require("../../../lib/runtime/runtime-contract");
const global_format_1 = require("../global-format");
async function createWorkflowExplainCommand() {
    const { Command } = await import("commander");
    const command = new Command("explain");
    command
        .description("Select a planning artifact and report its read-only workflow, prompt handoff, and next boundary.")
        .requiredOption("--artifact <path>", "Repository-relative planning artifact path to inspect; no files are changed.")
        .addHelpText("after", "\nSupported formats: text, json.\nRead-only: no files are changed.")
        .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 explain command output format"
            });
        }
        const repositoryContext = resolveRepositoryContext(commandInstance);
        const options = commandInstance.opts();
        const result = (0, planning_navigation_1.explainWorkflowForArtifact)({
            repositoryRoot: repositoryContext.root,
            artifactPath: options.artifact
        });
        (0, output_1.emitSuccess)({
            command: "workflow explain",
            format,
            text: (0, planning_navigation_1.renderWorkflowExplainResult)(result),
            data: {
                repositoryRoot: repositoryContext.root,
                detectionSource: repositoryContext.detectionSource,
                artifactPath: result.artifactPath,
                artifactType: result.artifactType,
                workflowPath: result.workflowPath,
                promptPath: result.promptPath,
                promptResolution: result.promptResolution,
                trustLanes: planning_navigation_1.WORKFLOW_EXPLAIN_TRUST_LANES,
                explanation: result.explanation,
                nextBoundary: result.nextBoundary
            }
        });
    });
    return command;
}
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);
}
