"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.reviewImplementationCompletionEvidence = reviewImplementationCompletionEvidence;
// Responsibility-focused implementation extracted from the public compatibility facade.
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const artifact_policy_projection_1 = require("../artifact-policy-projection");
const front_matter_utils_1 = require("../front-matter-utils");
const task_lifecycle_1 = require("../task-lifecycle");
const task_validation_1 = require("../task-validation");
const document_paths_1 = require("./document-paths");
const evidence_1 = require("./evidence");
const review_1 = require("./review");
/**
 * Projects the evidence gates that must pass before the current attempt can
 * transition its implementation status. This is a read-only subset of summary
 * closeout review: review disposition, attempt closure, task completion, and
 * reconciliation are deliberately outside this boundary.
 */
function reviewImplementationCompletionEvidence(repositoryRoot, options) {
    const taskDefinitionPath = (0, document_paths_1.resolveRepositoryPath)(repositoryRoot, options.taskDefinitionPath, "task-definition");
    const implementationSummaryPath = (0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.join(node_path_1.default.dirname(taskDefinitionPath.relative), "implementation-summary.md"));
    const implementationSummaryAbsolute = node_path_1.default.join(repositoryRoot, implementationSummaryPath);
    const taskDefinitionText = node_fs_1.default.readFileSync(taskDefinitionPath.absolute, "utf8");
    const summaryText = node_fs_1.default.readFileSync(implementationSummaryAbsolute, "utf8");
    const evidenceProfile = (0, artifact_policy_projection_1.projectArtifactPolicy)(taskDefinitionText).evidenceProfile;
    const lifecycle = (0, task_lifecycle_1.projectTaskLifecyclePair)({
        taskDefinition: taskDefinitionText,
        implementationSummary: summaryText
    });
    const attemptId = lifecycle.summary?.currentAttempt?.attemptId ?? null;
    const summaryReview = (0, review_1.reviewImplementationSummary)(repositoryRoot, {
        taskDefinitionPath: taskDefinitionPath.relative
    });
    const findings = summaryReview.blockingIssues
        .map((message) => (0, evidence_1.completionEvidenceFinding)(message));
    const currentValidations = attemptId === null
        ? []
        : (0, task_validation_1.readTaskValidationResults)(implementationSummaryPath, summaryText)
            .filter((validation) => validation.attemptId === attemptId
            && validation.evidenceBinding !== "preservation-only"
            && validation.recordingMode !== "closed-attempt-backfill");
    const validationIdentityProjection = (0, task_validation_1.projectTaskValidationIdentities)(currentValidations);
    const effectiveValidations = (0, task_validation_1.selectEffectiveTaskValidations)(currentValidations);
    const requiredValidations = effectiveValidations.filter((validation) => validation.required && validation.status !== "not_applicable");
    if (requiredValidations.length === 0) {
        findings.push({
            code: "incomplete-required-validation",
            artifact: "implementation_summary",
            field: "attempts.validation_results",
            message: "Implementation completion requires at least one current required validation result."
        });
    }
    for (const validation of requiredValidations) {
        const freshness = (0, task_validation_1.deriveTaskValidationFreshness)(repositoryRoot, validation);
        if (freshness.freshness === "stale") {
            findings.push({
                code: "incomplete-required-validation",
                artifact: "implementation_summary",
                field: "attempts.validation_results",
                message: `Required validation '${validation.validationId}' ('${validation.name}') is stale: ${freshness.reason}`
            });
            if (evidenceProfile === "runtime" || evidenceProfile === "hybrid") {
                findings.push({
                    code: "stale-runtime-target-evidence",
                    artifact: "implementation_summary",
                    field: "attempts.validation_results.observations",
                    message: `Runtime target observations bound to required validation '${validation.validationId}' ('${validation.name}') are stale: ${freshness.reason}`
                });
            }
            continue;
        }
        if (validation.status !== "passed" && validation.status !== "waived") {
            findings.push({
                code: "incomplete-required-validation",
                artifact: "implementation_summary",
                field: "attempts.validation_results",
                message: `Required validation '${validation.validationId}' ('${validation.name}') remains ${validation.status}.`
            });
        }
    }
    if (evidenceProfile === "contract") {
        if (/^runtime_attribution:\s*$/m.test(summaryText)
            || /^ {4}runtime_attribution_baseline:\s*/m.test(summaryText)) {
            findings.push({
                code: "fabricated-runtime-evidence",
                artifact: "implementation_summary",
                field: "runtime_attribution",
                message: "Contract completion cannot use or invent runtime-attribution baseline or summary evidence."
            });
        }
        const summaryDocument = (0, document_paths_1.parseMarkdownDocument)(implementationSummaryPath, summaryText);
        const changedPathEvidence = (0, evidence_1.extractSummaryChangedPathEvidence)(summaryDocument.sections.get("Changed Paths") ?? "");
        const changedPaths = changedPathEvidence
            .filter((entry) => entry.state === "path" && entry.path !== undefined)
            .map((entry) => entry.path);
        const currentPassedRequired = requiredValidations.filter((validation) => {
            if (validation.status !== "passed")
                return false;
            return (0, task_validation_1.deriveTaskValidationFreshness)(repositoryRoot, validation).freshness === "current";
        });
        for (const changedPath of changedPaths) {
            const covered = currentPassedRequired.some((validation) => [...validation.validationScope.paths, ...validation.validationScope.dependencies]
                .some((scopePath) => (0, document_paths_1.pathOverlapsAnyTarget)(changedPath, [scopePath])));
            if (!covered) {
                findings.push({
                    code: "contract-validation-not-applicable",
                    artifact: "implementation_summary",
                    field: "attempts.validation_results.validation_scope",
                    message: `Contract changed path '${changedPath}' is not covered by a current passed required validation scope.`
                });
            }
        }
    }
    const uniqueFindings = (0, evidence_1.uniqueCompletionEvidenceFindings)(findings);
    return {
        evidenceProfile,
        attemptId,
        applicable: uniqueFindings.length === 0,
        currentValidationCount: effectiveValidations.length,
        requiredValidationCount: requiredValidations.length,
        validationIdentityProjection,
        findings: uniqueFindings
    };
}
