"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createTaskReadinessReviewCommand = createTaskReadinessReviewCommand;
const errors_1 = require("../../../lib/errors");
const output_1 = require("../../../lib/output");
const global_format_1 = require("../global-format");
const runtime_contract_1 = require("../../../lib/runtime/runtime-contract");
const task_readiness_review_1 = require("../../../lib/planning/task-readiness-review");
const review_output_contracts_1 = require("../../../lib/planning/review-output-contracts");
async function createTaskReadinessReviewCommand() {
    const { Command } = await import("commander");
    const command = new Command("readiness-review");
    command
        .description("Evaluate task readiness as a read-only, no-write evidence surface and report missing evidence, dependency blockers, and sequencing issues.")
        .requiredOption("--task-definition <path>", "Repository-relative path to the task-definition.md file to review.")
        .requiredOption("--reviewed-by <actor>", "Explicit non-empty readiness reviewer identity.")
        .requiredOption("--reviewed-at <timestamp>", "Explicit ISO-8601 readiness review time.")
        .addHelpText("after", [
        "",
        "Readiness ordering:",
        "  Run link materialize --dry-run for the selected task first and materialize any safe candidates before this review.",
        "  Supply both --reviewed-by and --reviewed-at so the emitted evidence is explicit and reproducible.",
        "",
        "Validation coverage:",
        "  When .day-shift/test-partitions.json exists, readiness qualifies exact registered test facades and shared-suite partition ownership without executing tests.",
        "  Coverage output distinguishes proven coverage, proven omission, and unknown dynamic or unregistered selection; review remains read-only.",
        "",
        "Contract-impact preflight:",
        "  When .day-shift/contract-impact.json exists, exact producer relationships are checked before readiness authorization.",
        "  Schema v2 separates writable targets, generated outputs, read-only evidence, frozen dependencies, enforcers, validations, and unknown producers.",
        "  Missing required writable/generated scope, immutable targets, invalid enforcers, or blocking-policy unknown producers prevent authorization."
    ].join("\n"))
        .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.", [`Received: ${String((0, global_format_1.getGlobalFormat)(commandInstance))}`]);
        }
        const repositoryContext = (0, runtime_contract_1.createRepositoryContext)((0, runtime_contract_1.detectRepositoryRoot)(), false);
        const options = commandInstance.opts();
        const result = (0, task_readiness_review_1.reviewTaskReadiness)(repositoryContext.root, {
            taskDefinitionPath: options.taskDefinition,
            reviewedBy: options.reviewedBy,
            reviewedAt: options.reviewedAt
        });
        (0, output_1.emitSuccess)({
            command: "task readiness-review",
            format,
            text: renderTaskReadinessReviewText(result),
            data: {
                ...result,
                reviewResult: result,
                detectionSource: repositoryContext.detectionSource,
                writeCapable: false,
                noWriteBoundary: (0, review_output_contracts_1.getReviewOutputContract)("task readiness-review").noWriteBoundary,
                reviewOutputContract: (0, review_output_contracts_1.getReviewOutputContract)("task readiness-review"),
            },
            findings: [...result.findings]
        });
    });
    return command;
}
function renderTaskReadinessReviewText(result) {
    const lines = [
        (0, output_1.renderTerminalHeading)("Task readiness review", "title").trimEnd(),
        "",
        (0, output_1.renderTerminalSection)({
            heading: "Summary",
            fields: [
                { label: "Task definition", value: result.taskDefinitionPath },
                { label: "Readiness review ID", value: result.readinessReviewId },
                { label: "Task revision", value: result.taskRevision },
                { label: "Protocol version", value: result.protocolVersion },
                { label: "Reviewed by", value: result.reviewedBy },
                { label: "Reviewed at", value: result.reviewedAt },
                { label: "No-write review surface", value: "yes" },
                { label: "Authored readiness", value: result.authoredReadiness ?? "(missing)" },
                { label: "Reviewed readiness", value: result.reviewedReadiness ?? "(missing)" },
                { label: "Readiness status", value: result.readinessStatus },
                { label: "Authorization state", value: result.authorizationState },
                { label: "Authorization revision", value: result.authorizationRevision },
                { label: "Current attempt state", value: result.currentAttemptState.state },
                { label: "Current attempt ID", value: result.currentAttemptState.attemptId ?? "(none)" },
                { label: "Current baseline ID", value: result.currentAttemptState.baselineId ?? "(none)" },
                { label: "Next-action reason", value: result.nextAction.reasonCode },
                { label: "Next-action command", value: result.nextAction.argv?.join(" ") ?? "(not callable)" }
            ],
            lines: [(0, output_1.renderTerminalBoundary)({ kind: "read-only" })]
        }),
        "",
        (0, output_1.renderTerminalSection)({
            heading: "Review Output Contract",
            lines: (0, review_output_contracts_1.renderReviewOutputContractLines)()
        }),
        "",
        "Missing Evidence:"
    ];
    appendIssueLines(lines, result.missingEvidence);
    lines.push("", "Dependency Blockers:");
    appendIssueLines(lines, result.dependencyBlockers);
    lines.push("", "Sequencing Issues:");
    appendIssueLines(lines, result.sequencingIssues);
    lines.push("", `Paired Implementation Summary: ${result.pairedImplementationSummaryPath}`, `Implementation Handoff Status: ${result.handoffStatus}`, "Handoff Blockers:");
    appendIssueLines(lines, result.handoffBlockers);
    lines.push("");
    if (result.reviewBoundaryKind === "lightweight-task-summary") {
        lines.push(`Review Boundary: lightweight task summary (${result.pairedImplementationSummaryPath})`);
    }
    else {
        lines.push(`Milestone Reconciliation Path: ${result.milestoneReconciliationPath}`);
    }
    lines.push("Review Boundary Warnings:");
    appendIssueLines(lines, result.reviewBoundaryWarnings);
    lines.push("", `Validation Coverage Manifest: ${result.validationCoverage.manifestPath} (${result.validationCoverage.manifestState})`, "Validation Coverage:");
    if (result.validationCoverage.assessments.length === 0) {
        lines.push("- (none)");
    }
    else {
        for (const assessment of result.validationCoverage.assessments) {
            lines.push(`- ${assessment.targetPath}: ${assessment.state}; required=${assessment.requiredPartitionIds.join(",")}; covered=${assessment.coveredPartitionIds.join(",") || "(none)"}`);
        }
    }
    lines.push("", "Recovery Guidance:");
    appendIssueLines(lines, result.recoveryGuidance);
    lines.push("", `Contract Impact: ${result.contractImpact.contractPath} (${result.contractImpact.contractState})`, `Contract Impact Unknown Policy: ${result.contractImpact.unknownPolicy}`, `Contract Impact Fingerprint: ${result.contractImpact.fingerprint}`, `Complete Relationships: ${result.contractImpact.complete.length}`, `Missing Required Impact: ${result.contractImpact.missingRequired.length}`, `Missing Writable Scope: ${result.contractImpact.missingWritable.length}`, `Missing Generated Outputs: ${result.contractImpact.missingGenerated.length}`, `Writable Paths: ${result.contractImpact.writablePaths.length}`, `Generated Outputs: ${result.contractImpact.generatedOutputs.length}`, `Read-only Dependencies: ${result.contractImpact.readOnlyDependencies.length}`, `Frozen Dependencies: ${result.contractImpact.frozenDependencies.length}`, `Enforcing Contracts: ${result.contractImpact.enforcedBy.length}`, `Validation Commands: ${result.contractImpact.validationCommands.length}`, `Immutable Declared Targets: ${result.contractImpact.immutableTargets.length}`, `Advisory Impact: ${result.contractImpact.advisory.length}`, `Unknown Impact: ${result.contractImpact.unknown.length}`);
    if (result.findings.length > 0) {
        lines.push("", (0, output_1.renderValidationFindingsText)(result.findings, "Structured Findings"));
    }
    return lines.join("\n");
}
function appendIssueLines(lines, issues) {
    if (issues.length === 0) {
        lines.push("- (none)");
        return;
    }
    for (const issue of issues) {
        lines.push(`- ${issue}`);
    }
}
