"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.assertTaskProjectionRefreshAllowed = assertTaskProjectionRefreshAllowed;
exports.taskRuntimeAttributionRequired = taskRuntimeAttributionRequired;
const node_fs_1 = __importDefault(require("node:fs"));
const errors_1 = require("../../errors");
const output_1 = require("../../output");
const authoring_policy_1 = require("../authoring-policy");
const artifact_parsing_1 = require("./artifact-parsing");
function assertTaskProjectionRefreshAllowed(options) {
    const findings = options.comparison.drift.map((entry) => (0, output_1.createBlockingValidationFinding)({
        code: "PLANNING_SCAFFOLD_PROJECTION_DRIFT",
        message: `Materialized task '${options.taskDefinitionRelativePath}' has ${entry.kind} scaffold projection drift at '${entry.field}'.`,
        path: options.taskDefinitionRelativePath,
        blockingReason: "invalid-command-input",
        recovery: "Rerun with --recover-scaffold only if the generated task pair is still lifecycle-untouched; otherwise preserve the task evidence and revise the parent or record separate discovered work.",
        evidence: {
            category: "planning-review",
            details: {
                field: entry.field,
                driftKind: entry.kind,
                expectedParentProjection: entry.expected,
                observedChildProjection: entry.observed,
                noWriteRequired: true
            }
        }
    }));
    if (!options.refreshRequested) {
        throw (0, errors_1.createInvalidConfigError)(`Current parent scaffold projection does not match '${options.taskDefinitionRelativePath}'.`, [
            ...findings.map((finding) => finding.message),
            "No task artifact write was attempted. Use --recover-scaffold as a separate preservation-first refresh only before lifecycle evidence exists."
        ], findings);
    }
    const recordedRevision = (0, authoring_policy_1.readPlanningScaffoldProjectionRevision)(options.observedText);
    const observedRevision = (0, authoring_policy_1.planningScaffoldProjectionRevision)(options.comparison.observed);
    const taskFrontMatter = (0, artifact_parsing_1.extractFrontMatter)(options.taskDefinitionPath, options.observedText);
    const status = (0, artifact_parsing_1.readTopLevelField)(taskFrontMatter.lines, "status")?.trim() ?? null;
    const readiness = (0, artifact_parsing_1.readTopLevelField)(taskFrontMatter.lines, "readiness")?.trim() ?? null;
    const summaryText = node_fs_1.default.existsSync(options.implementationSummaryPath)
        ? node_fs_1.default.readFileSync(options.implementationSummaryPath, "utf8")
        : "";
    const summaryFrontMatter = summaryText === ""
        ? null
        : (0, artifact_parsing_1.extractFrontMatter)(options.implementationSummaryPath, summaryText);
    const currentAttemptId = summaryFrontMatter === null
        ? null
        : (0, artifact_parsing_1.readTopLevelField)(summaryFrontMatter.lines, "current_attempt_id")?.trim() ?? null;
    const attempts = summaryFrontMatter === null
        ? null
        : (0, artifact_parsing_1.readTopLevelField)(summaryFrontMatter.lines, "attempts")?.trim() ?? null;
    const lifecycleUntouched = status === "draft"
        && readiness === "needs_more_evidence"
        && (recordedRevision === observedRevision
            || recordedRevision === (0, authoring_policy_1.legacyPlanningScaffoldProjectionRevision)(options.comparison.observed))
        && currentAttemptId === "null"
        && attempts === "[]"
        && /Pending\. This implementation summary is initialized/u.test(summaryText);
    if (lifecycleUntouched)
        return;
    throw (0, errors_1.createInvalidConfigError)(`Scaffold refresh is unavailable for '${options.taskDefinitionRelativePath}' because preservation-first lifecycle checks did not prove an untouched generated pair.`, [
        `Recorded projection: ${recordedRevision ?? "(missing)"}.`,
        `Observed projection: ${observedRevision}.`,
        `Task readiness/status: ${readiness ?? "(missing)"}/${status ?? "(missing)"}.`,
        `Current attempt: ${currentAttemptId ?? "(missing)"}; attempts: ${attempts ?? "(missing)"}.`,
        "No task artifact write was attempted; existing authored or lifecycle evidence was preserved."
    ], findings.map((finding) => ({
        ...finding,
        code: "PLANNING_SCAFFOLD_REFRESH_UNAVAILABLE"
    })));
}
function taskRuntimeAttributionRequired(executionMode, runtimeAcceptance) {
    return runtimeAcceptance?.required === true && executionMode !== "contract";
}
