"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createSpecReviewCommand = createSpecReviewCommand;
exports.renderSpecificationReviewText = renderSpecificationReviewText;
const errors_1 = require("../../../lib/errors");
const output_1 = require("../../../lib/output");
const spec_review_1 = require("../../../lib/spec-review");
const runtime_contract_1 = require("../../../lib/runtime/runtime-contract");
const global_format_1 = require("../global-format");
async function createSpecReviewCommand() {
    const { Command } = await import("commander");
    const command = new Command("review");
    command
        .description("Review a registered canonical specification as a complete read-only, no-write findings surface.")
        .requiredOption("--spec <path>", "Repository-relative canonical specification path.")
        .option("--reviewed-at <timestamp>", "ISO-8601 review time; defaults to the current time.")
        .option("--reviewed-by <actor>", "Review actor; defaults to the current process actor.")
        .action((_, commandInstance) => {
        const format = (0, output_1.resolveOutputFormat)((0, global_format_1.getGlobalFormat)(commandInstance));
        if (format === null) {
            throw (0, errors_1.createUsageError)("Output format must be one of: text, json.");
        }
        const repository = (0, runtime_contract_1.createRepositoryContext)((0, runtime_contract_1.detectRepositoryRoot)(), false);
        const options = commandInstance.opts();
        let result;
        try {
            result = (0, spec_review_1.reviewSpecificationSync)(repository.root, {
                specPath: options.spec,
                reviewedAt: options.reviewedAt ?? new Date().toISOString(),
                reviewedBy: options.reviewedBy ?? process.env.DAY_SHIFT_REVIEWER ?? process.env.USER ?? "unknown"
            });
        }
        catch (error) {
            throw normalizeReviewError(error, options.spec);
        }
        (0, output_1.emitSuccess)({
            command: "spec review",
            format,
            text: renderSpecificationReviewText(result),
            data: result,
            findings: [...result.findings]
        });
    });
    return command;
}
function renderSpecificationReviewText(result) {
    const lines = [
        (0, output_1.renderTerminalHeading)("Specification review", "title").trimEnd(),
        "",
        (0, output_1.renderTerminalSection)({
            heading: "Review Identity",
            fields: [
                { label: "review_id", value: result.review_id },
                { label: "spec_id", value: result.spec_id },
                { label: "spec_path", value: result.spec_path },
                { label: "spec_revision", value: result.spec_revision },
                { label: "protocol_version", value: result.protocol_version },
                { label: "reviewed_at", value: result.reviewed_at },
                { label: "reviewed_by", value: result.reviewed_by }
            ],
            lines: [(0, output_1.renderTerminalBoundary)({ kind: "read-only" })]
        }),
        "",
        (0, output_1.renderTerminalSection)({
            heading: "Counts",
            fields: Object.entries(result.counts).map(([label, value]) => ({ label, value }))
        }),
        "",
        (0, output_1.renderTerminalSection)({
            heading: "Recommendations",
            fields: [
                { label: "planning_readiness_recommendation", value: result.planning_readiness_recommendation.status },
                { label: "planning_readiness_reason", value: result.planning_readiness_recommendation.reason },
                { label: "workflow_level_recommendation", value: result.workflow_level_recommendation.level },
                { label: "workflow_recommendation_advisory", value: result.workflow_level_recommendation.advisory }
            ],
            lines: result.workflow_level_recommendation.reasons.map((reason) => `- ${reason}`)
        }),
        "",
        "Findings:"
    ];
    for (const finding of result.findings) {
        lines.push(`- [${finding.severity}] ${finding.code} (${finding.category}, ${finding.status}): ${finding.message}`);
    }
    lines.push("", `Unresolved Findings: ${result.unresolved_findings.length === 0 ? "(none)" : result.unresolved_findings.map((finding) => finding.code).join(", ")}`, `Waived Findings: ${result.waived_findings.length === 0 ? "(none)" : result.waived_findings.map((finding) => finding.code).join(", ")}`, `Read Only: ${result.read_only ? "yes" : "no"}`, `No-write Boundary: ${result.no_write_boundary}`);
    return lines.join("\n");
}
function normalizeReviewError(error, specPath) {
    if (error instanceof errors_1.RuntimeError)
        return error;
    if (error instanceof spec_review_1.SpecificationReviewError) {
        return new errors_1.RuntimeError({
            message: "Specification review could not complete.",
            code: `SPEC_REVIEW_${error.code.replace(/-/g, "_").toUpperCase()}`,
            exitCode: error.code === "invalid-input" ? errors_1.RuntimeExitCode.USAGE : errors_1.RuntimeExitCode.ERROR,
            details: [error.message, "No specification, registry, readiness, review, state, or planning files were written."],
            findings: [{
                    code: `SPEC_REVIEW_${error.code.replace(/-/g, "_").toUpperCase()}`,
                    severity: "error",
                    message: error.message,
                    path: specPath,
                    noWriteBoundary: "Specification review failures are no-write outcomes."
                }]
        });
    }
    throw error;
}
