"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractSummaryChangedPathEvidence = extractSummaryChangedPathEvidence;
exports.readSupportedDescriptiveChangedPath = readSupportedDescriptiveChangedPath;
exports.withChangedPathRecovery = withChangedPathRecovery;
exports.completionEvidenceFinding = completionEvidenceFinding;
exports.uniqueCompletionEvidenceFindings = uniqueCompletionEvidenceFindings;
exports.hasConcreteValidationEvidence = hasConcreteValidationEvidence;
exports.hasValidationExceptionIntent = hasValidationExceptionIntent;
exports.hasCompleteStructuredValidationException = hasCompleteStructuredValidationException;
exports.hasConcreteAcceptanceEvidence = hasConcreteAcceptanceEvidence;
exports.normalizeEvidenceText = normalizeEvidenceText;
exports.trimSectionContent = trimSectionContent;
// Responsibility-focused implementation extracted from the public compatibility facade.
const semantic_evidence_1 = require("../semantic-evidence");
function extractSummaryChangedPathEvidence(sectionText) {
    const semanticEvidence = (0, semantic_evidence_1.readChangedPathEvidence)(sectionText);
    const evidenceByLine = new Map(semanticEvidence.map((entry) => [entry.line, entry]));
    const evidence = [];
    for (const [index, line] of sectionText.split(/\r?\n/).entries()) {
        const lineNumber = index + 1;
        if (line.trim() === "")
            continue;
        const existing = evidenceByLine.get(lineNumber);
        if (existing?.state === "path") {
            evidence.push(existing);
            continue;
        }
        const bullet = line.match(/^-\s+(.+?)\s*$/);
        if (bullet !== null) {
            const rawText = bullet[1].trim();
            const descriptive = readSupportedDescriptiveChangedPath(rawText, lineNumber);
            if (descriptive !== null) {
                evidence.push(descriptive);
                continue;
            }
        }
        if (existing !== undefined) {
            evidence.push(withChangedPathRecovery(existing));
            continue;
        }
        evidence.push({
            state: "prose",
            rawText: line.trim(),
            line: lineNumber,
            column: line.search(/\S/) + 1,
            message: `Changed Paths line ${lineNumber} is prose-only evidence. Rewrite it as one top-level bullet in the form '- \`repository/relative/path\`'.`
        });
    }
    return evidence;
}
function readSupportedDescriptiveChangedPath(rawText, lineNumber) {
    const match = rawText.match(/^(`[^`\r\n]+`|\[[^\]\r\n]+\]\(\s*(?:<[^>\r\n]+>|[^\s)]+)(?:\s+["'][^"'\r\n]*["'])?\s*\)|\S+?)(?:\s*:\s+|\s+(?:—|–)\s+)(.+)$/);
    if (match === null)
        return null;
    const candidateToken = match[1].trim();
    const description = match[2].trim();
    const pathLikeDescriptionEvidence = [
        ...description.matchAll(/`[^`\r\n]+`|\[[^\]\r\n]+\]\([^)]+\)|(?:^|\s)(?:\.\.?\/|[A-Za-z0-9_.-]+\/)\S+/g)
    ];
    if (pathLikeDescriptionEvidence.length > 0) {
        return {
            state: "prose",
            rawText,
            line: lineNumber,
            column: 3,
            message: `Changed Paths entry '${rawText}' is ambiguous because its description contains another path-like reference (line ${lineNumber}). Split it into one canonical '- \`repository/relative/path\`' bullet per path.`
        };
    }
    const candidateEvidence = (0, semantic_evidence_1.readChangedPathEvidence)(`- ${candidateToken}`)[0];
    if (candidateEvidence === undefined)
        return null;
    if (candidateEvidence.state !== "path" || candidateEvidence.path === undefined) {
        return withChangedPathRecovery({
            ...candidateEvidence,
            rawText,
            line: lineNumber
        });
    }
    return {
        state: "path",
        rawText,
        line: lineNumber,
        column: 3,
        path: candidateEvidence.path,
        message: `Changed Paths line ${lineNumber} resolves descriptive evidence to repository path '${candidateEvidence.path}' and build normalizes it to a canonical path bullet.`
    };
}
function withChangedPathRecovery(evidence) {
    if (evidence.state === "placeholder") {
        return {
            ...evidence,
            message: `${evidence.message} Replace line ${evidence.line} with '- \`repository/relative/path\`' after implementation changes exist.`
        };
    }
    if (evidence.state === "invalid") {
        return {
            ...evidence,
            message: `${evidence.message} Use a contained repository-relative path with no glob, absolute prefix, or parent traversal.`
        };
    }
    const pathLikeReferences = [
        ...evidence.rawText.matchAll(/`[^`\r\n]+`|\[[^\]\r\n]+\]\([^)]+\)|(?:^|\s)(?:\.\.?\/|[A-Za-z0-9_.-]+\/)\S+/g)
    ];
    if (pathLikeReferences.length > 1) {
        return {
            ...evidence,
            message: `Changed Paths entry '${evidence.rawText}' is ambiguous because it contains multiple path-like references (line ${evidence.line}). Split it into one canonical '- \`repository/relative/path\`' bullet per path.`
        };
    }
    return {
        ...evidence,
        message: `${evidence.message} Rewrite line ${evidence.line} as '- \`repository/relative/path\`' or use one path-first descriptive bullet with ':' or an en/em dash.`
    };
}
function completionEvidenceFinding(message) {
    if (/baseline/i.test(message)) {
        return {
            code: "missing-runtime-baseline",
            artifact: "implementation_summary",
            field: "attempts.runtime_attribution_baseline",
            message
        };
    }
    if (/fresh_runtime_paths is stale|current-cycle-ineligible|stale.*target/i.test(message)) {
        return {
            code: "stale-runtime-target-evidence",
            artifact: "implementation_summary",
            field: "runtime_attribution.fresh_runtime_paths",
            message
        };
    }
    if (/freshly attributable runtime-eligible path|runtime-eligible changed path|Runtime Delta target/i.test(message)) {
        return {
            code: "missing-runtime-target-evidence",
            artifact: "implementation_summary",
            field: "runtime_attribution.fresh_runtime_paths",
            message
        };
    }
    if (/validation/i.test(message)) {
        return {
            code: "incomplete-required-validation",
            artifact: "implementation_summary",
            field: "attempts.validation_results",
            message
        };
    }
    if (/acceptance|criterion/i.test(message)) {
        return {
            code: "unauthored-acceptance-evidence",
            artifact: "implementation_summary",
            field: "runtime_attribution.satisfied_criterion_ids",
            message
        };
    }
    if (/Contract-mode.*runtime|contract.*runtime implementation/i.test(message)) {
        return {
            code: "fabricated-runtime-evidence",
            artifact: "implementation_summary",
            field: "runtime_attribution",
            message
        };
    }
    return {
        code: "incomplete-summary-evidence",
        artifact: "implementation_summary",
        field: "closeout_evidence",
        message
    };
}
function uniqueCompletionEvidenceFindings(findings) {
    const seen = new Set();
    const uniqueFindings = [];
    for (const finding of findings) {
        const identity = `${finding.code}\0${finding.artifact}\0${finding.field}\0${finding.message}`;
        if (seen.has(identity))
            continue;
        seen.add(identity);
        uniqueFindings.push(finding);
    }
    return uniqueFindings;
}
function hasConcreteValidationEvidence(sectionText) {
    const normalized = normalizeEvidenceText(sectionText);
    if (normalized === "") {
        return false;
    }
    return /`[^`]+`/.test(sectionText)
        || /\b(?:pnpm|npm|node|tsc|cargo|go test|pytest|vitest|jest)\b/i.test(normalized)
        || /\b(?:diff|numstat|stat|wc -l)\b/i.test(normalized)
        || /\b(?:inspect(?:ed|ion)?|review(?:ed)? changed|no-write review|skipped|substituted|blocked|inconclusive)\b/i.test(normalized)
        || /(?:^|\s)(?:\.day-shift|src|tests|dist|docs)\//.test(normalized);
}
function hasValidationExceptionIntent(sectionText) {
    const normalized = normalizeEvidenceText(sectionText);
    return /\b(?:skipped|could not run|unable to run|blocked|validation exception|substituted|substitute evidence)\b/i.test(normalized);
}
function hasCompleteStructuredValidationException(sectionText) {
    return [
        /\bplanned command\b/i,
        /\b(?:blocker|environment blocker|dependency blocker)\b/i,
        /\bsubstitute evidence\b/i,
        /\bresidual risk\b/i,
        /\bfollow-up (?:validation )?(?:command|path)\b/i
    ].every((pattern) => pattern.test(sectionText));
}
function hasConcreteAcceptanceEvidence(sectionText) {
    const normalized = normalizeEvidenceText(sectionText);
    if (normalized === "") {
        return false;
    }
    if (/^(?:passed|complete|completed|done|satisfied|accepted|implemented|met)[\s.:-]*$/i.test(normalized)) {
        return false;
    }
    return /`[^`]+`/.test(sectionText)
        || /\b(?:changed paths?|validation|command|test|diff|inspection|evidence|read-only|no-write|implemented|reports?|flags?|accepts?|rejects?|classifies|metadata|summary|review)\b/i.test(normalized)
        || /(?:^|\s)(?:\.day-shift|src|tests|dist|docs)\//.test(normalized);
}
function normalizeEvidenceText(sectionText) {
    return sectionText
        .split(/\r?\n/)
        .map((line) => line.trim().replace(/^[-*]\s+/, ""))
        .filter((line) => line !== "")
        .join(" ")
        .trim();
}
function trimSectionContent(lines) {
    const joined = lines.join("\n");
    return joined.replace(/^\n+/, "").replace(/\n+$/, "").trim();
}
