"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveReconciliationSelector = resolveReconciliationSelector;
exports.collectImplementationSummaryEvidenceIssues = collectImplementationSummaryEvidenceIssues;
exports.collectReconciliationRuntimeEvidenceIssues = collectReconciliationRuntimeEvidenceIssues;
exports.formatSummaryEvidenceIssueSuffix = formatSummaryEvidenceIssueSuffix;
exports.assertMatchingPlanningIdentity = assertMatchingPlanningIdentity;
exports.resolveExpectedPlanningValue = resolveExpectedPlanningValue;
exports.readRequiredTopLevelField = readRequiredTopLevelField;
exports.isAllowedExecutionMode = isAllowedExecutionMode;
exports.hasRuntimeImplementationClaim = hasRuntimeImplementationClaim;
exports.readRequiredUpstreamField = readRequiredUpstreamField;
exports.readTopLevelField = readTopLevelField;
exports.readUpstreamField = readUpstreamField;
exports.parseUpstreamSpecs = parseUpstreamSpecs;
exports.inferTaskTitleFromPath = inferTaskTitleFromPath;
exports.removeTemplateScaffoldContent = removeTemplateScaffoldContent;
exports.firstContentLine = firstContentLine;
exports.normalizeReviewLines = normalizeReviewLines;
exports.sectionContradictsTaskEvidence = sectionContradictsTaskEvidence;
exports.appendIssueLines = appendIssueLines;
// Responsibility-focused implementation extracted from the public compatibility facade.
const node_path_1 = __importDefault(require("node:path"));
const errors_1 = require("../../errors");
const declared_target_paths_1 = require("../../validation/declared-target-paths");
const documentation_path_classifier_1 = require("../../validation/documentation-path-classifier");
const front_matter_utils_1 = require("../front-matter-utils");
const contracts_1 = require("../implementation-summary/contracts");
const evidence_1 = require("../implementation-summary/evidence");
const semantic_placeholder_1 = require("../semantic-placeholder");
function resolveReconciliationSelector(options) {
    const hasMilestoneOverview = typeof options.milestoneOverviewPath === "string" && options.milestoneOverviewPath.trim() !== "";
    const hasTaskDefinition = typeof options.taskDefinitionPath === "string" && options.taskDefinitionPath.trim() !== "";
    const rationale = typeof options.taskReconciliationRationale === "string"
        ? options.taskReconciliationRationale.trim()
        : "";
    if (hasMilestoneOverview && hasTaskDefinition) {
        throw (0, errors_1.createUsageError)("Choose exactly one reconciliation source selector.", [
            "Use --milestone-overview for the default milestone reconciliation rollup.",
            "Use --task-definition only for an explicit task-level reconciliation exception."
        ]);
    }
    if (hasTaskDefinition) {
        if (rationale === "") {
            throw (0, errors_1.createUsageError)("Task-level reconciliation requires an explicit exception rationale.", [
                "Pass --rationale <text> with --task-definition to record why milestone-level reconciliation is not the selected rollup path.",
                "Use --milestone-overview for the default milestone reconciliation rollup."
            ]);
        }
        return { kind: "task", taskDefinitionPath: options.taskDefinitionPath, rationale };
    }
    if (hasMilestoneOverview) {
        return { kind: "milestone", milestoneOverviewPath: options.milestoneOverviewPath };
    }
    throw (0, errors_1.createUsageError)("Missing reconciliation source selector.", [
        "Use --milestone-overview for the default milestone reconciliation rollup.",
        "Use --task-definition only for an explicit task-level reconciliation exception."
    ]);
}
function collectImplementationSummaryEvidenceIssues(document) {
    const issues = [];
    for (const sectionName of contracts_1.IMPLEMENTATION_SUMMARY_SECTIONS) {
        const sectionText = document.sections.get(sectionName);
        if (sectionText === undefined) {
            issues.push(`Missing required section '${sectionName}'.`);
            continue;
        }
        if (sectionName !== "Changed Paths" && (0, semantic_placeholder_1.hasSemanticPlaceholderContent)(sectionText)) {
            issues.push(`Section '${sectionName}' still contains placeholder content.`);
        }
    }
    const changedPathsText = document.sections.get("Changed Paths");
    if (changedPathsText !== undefined) {
        const changedPathEvidence = (0, evidence_1.extractSummaryChangedPathEvidence)(changedPathsText);
        const concreteChangedPaths = changedPathEvidence.filter((entry) => entry.state === "path");
        if (concreteChangedPaths.length === 0) {
            issues.push("Changed Paths does not list concrete repository-relative changed paths.");
        }
        for (const entry of changedPathEvidence) {
            if (entry.state !== "path") {
                issues.push(entry.message);
            }
        }
    }
    const acceptanceCriteriaText = document.sections.get("Acceptance Criteria Results");
    if (acceptanceCriteriaText !== undefined
        && !(0, semantic_placeholder_1.hasSemanticPlaceholderContent)(acceptanceCriteriaText)
        && !(0, evidence_1.hasConcreteAcceptanceEvidence)(acceptanceCriteriaText)) {
        issues.push("Acceptance Criteria Results lacks concrete evidence tied to implementation or validation.");
    }
    const validationText = document.sections.get("Validation Performed");
    if (validationText !== undefined
        && !(0, semantic_placeholder_1.hasSemanticPlaceholderContent)(validationText)
        && !(0, evidence_1.hasConcreteValidationEvidence)(validationText)) {
        issues.push("Validation Performed lacks concrete command, inspection, or explicit validation-exception evidence.");
    }
    const deviationsText = document.sections.get("Deviations");
    if (deviationsText === undefined || (0, semantic_placeholder_1.hasSemanticPlaceholderContent)(deviationsText)) {
        issues.push("Deviations does not record either concrete deviations or an explicit none-state.");
    }
    const risksAndFollowUpsText = document.sections.get("Risks and Follow-Ups");
    if (risksAndFollowUpsText === undefined || (0, semantic_placeholder_1.hasSemanticPlaceholderContent)(risksAndFollowUpsText)) {
        issues.push("Risks and Follow-Ups does not record either concrete follow-up evidence or an explicit none-state.");
    }
    return [...new Set(issues)];
}
function collectReconciliationRuntimeEvidenceIssues(summary) {
    const executionMode = summary.executionMode?.trim() ?? "";
    if (executionMode !== "runtime" && executionMode !== "hybrid") {
        return [];
    }
    const issues = [];
    const changedPathsText = summary.changedPathsText;
    if (changedPathsText === undefined || changedPathsText === null) {
        issues.push(`Runtime or hybrid task summary '${summary.relativePath}' does not provide Changed Paths evidence for reconciliation runtime review.`);
        return issues;
    }
    const changedPathEvidence = (0, evidence_1.extractSummaryChangedPathEvidence)(changedPathsText);
    issues.push(...changedPathEvidence
        .filter((entry) => entry.state !== "path")
        .map((entry) => `${summary.relativePath}: ${entry.message}`));
    const concreteChangedPaths = changedPathEvidence
        .filter((entry) => entry.state === "path" && entry.path !== undefined)
        .map((entry) => entry.path);
    const runtimeEligibleChangedPaths = concreteChangedPaths.filter((changedPath) => (0, documentation_path_classifier_1.classifyDocumentationPath)(changedPath, {
        declaredTargetRole: (0, declared_target_paths_1.resolveDeclaredTargetPathRole)(summary.declaredTargetEvidence ?? [], changedPath)
    }).runtimeEligible);
    if (concreteChangedPaths.length === 0) {
        issues.push(`Runtime or hybrid task summary '${summary.relativePath}' does not list concrete repository-relative Changed Paths evidence for reconciliation runtime review.`);
    }
    else if (runtimeEligibleChangedPaths.length === 0) {
        issues.push(`Runtime or hybrid task summary '${summary.relativePath}' only lists documentation-only Changed Paths evidence; reconciliation requires runtime-eligible changed-path evidence.`);
    }
    if (summary.validationText === null || (0, semantic_placeholder_1.hasSemanticPlaceholderContent)(summary.validationText) || !(0, evidence_1.hasConcreteValidationEvidence)(summary.validationText)) {
        issues.push(`Runtime or hybrid task summary '${summary.relativePath}' does not provide concrete executable validation evidence for reconciliation runtime review.`);
    }
    return issues;
}
function formatSummaryEvidenceIssueSuffix(entry) {
    if (entry.evidenceIssues === undefined || entry.evidenceIssues.length === 0) {
        return "";
    }
    return `; evidence gaps: ${entry.evidenceIssues.join(" ")}`;
}
function assertMatchingPlanningIdentity(context, frontMatterLines, artifactPath, issues, keys) {
    for (const key of keys) {
        const expectedValue = resolveExpectedPlanningValue(context, key);
        const actualValue = readTopLevelField(frontMatterLines, key)?.trim() ?? null;
        if (actualValue !== expectedValue) {
            issues.push(`Metadata field '${key}' on '${artifactPath}' should be '${expectedValue}', found '${actualValue ?? "(missing)"}'.`);
        }
    }
}
function resolveExpectedPlanningValue(context, key) {
    switch (key) {
        case "slice":
            return context.slice;
        case "phase":
            return context.phase ?? "";
        case "milestone":
            return context.milestone ?? "";
        case "task":
            return "task" in context ? context.task : "";
        case "implementation_order":
            return "implementationOrder" in context ? context.implementationOrder ?? "" : "";
        case "planning_depth":
            return context.planningDepth;
        default:
            return "";
    }
}
function readRequiredTopLevelField(lines, filePath, key) {
    const value = readTopLevelField(lines, key)?.trim();
    if (!value) {
        throw (0, errors_1.createUsageError)(`Artifact '${filePath}' is missing required top-level field '${key}'.`);
    }
    return value;
}
function isAllowedExecutionMode(value) {
    return value === "runtime" || value === "contract" || value === "hybrid";
}
function hasRuntimeImplementationClaim(sections) {
    const claimText = [
        sections.get("Summary") ?? "",
        sections.get("Acceptance Criteria Results") ?? "",
        sections.get("Scope Classification") ?? ""
    ].join("\n");
    return /\b(?:implemented runtime|runtime implementation (?:landed|completed|done|shipped)|runtime behavior (?:changed|implemented|shipped)|changed runtime behavior|wired runtime|shipped runtime)\b/i.test(claimText);
}
function readRequiredUpstreamField(lines, filePath, key) {
    const value = readUpstreamField(lines, key)?.trim();
    if (!value) {
        throw (0, errors_1.createUsageError)(`Artifact '${filePath}' is missing required upstream field '${key}'.`);
    }
    return value;
}
function readTopLevelField(lines, key) {
    for (const line of lines) {
        if (/^\s/.test(line)) {
            continue;
        }
        const match = line.match(/^([A-Za-z0-9_]+):\s*(.*)$/);
        if (match !== null && match[1] === key) {
            return (0, front_matter_utils_1.parseScalar)(match[2]);
        }
    }
    return undefined;
}
function readUpstreamField(lines, key) {
    let inUpstream = false;
    for (const line of lines) {
        if (!inUpstream) {
            if (line.trim() === "upstream:") {
                inUpstream = true;
            }
            continue;
        }
        if (!/^\s/.test(line)) {
            break;
        }
        const match = line.match(/^\s{2}([A-Za-z0-9_]+):\s*(.*)$/);
        if (match !== null && match[1] === key) {
            return (0, front_matter_utils_1.parseScalar)(match[2]);
        }
    }
    return undefined;
}
function parseUpstreamSpecs(lines, filePath) {
    const entries = [];
    for (let index = 0; index < lines.length; index += 1) {
        const idMatch = lines[index].match(/^\s*-\s+id:\s*(.+)$/);
        if (idMatch === null) {
            continue;
        }
        const fields = new Map();
        let cursor = index + 1;
        for (; cursor < lines.length; cursor += 1) {
            const fieldMatch = lines[cursor].match(/^\s{6}([A-Za-z0-9_]+):\s*(.+)$/);
            if (fieldMatch === null)
                break;
            fields.set(fieldMatch[1], (0, front_matter_utils_1.parseScalar)(fieldMatch[2]));
        }
        const ref = fields.get("ref") ?? null;
        const depth = fields.get("depth") ?? null;
        const sourceType = fields.get("source_type") ?? null;
        const revision = fields.get("revision") ?? null;
        const readiness = fields.get("readiness") ?? null;
        const governedShape = depth !== null && sourceType !== null;
        const structuredShape = revision !== null;
        const partialGovernedShape = (depth === null) !== (sourceType === null);
        const orphanedReadiness = readiness !== null && revision === null;
        if (ref === null
            || (!governedShape && !structuredShape)
            || partialGovernedShape
            || orphanedReadiness) {
            throw (0, errors_1.createUsageError)(`Artifact '${filePath}' has malformed upstream.specs metadata near '${lines[index].trim()}'.`);
        }
        entries.push({
            id: (0, front_matter_utils_1.parseScalar)(idMatch[1]),
            depth,
            ref,
            sourceType,
            revision,
            readiness
        });
        index = cursor - 1;
    }
    return entries;
}
function inferTaskTitleFromPath(filePath) {
    return node_path_1.default.basename(node_path_1.default.dirname(filePath));
}
function removeTemplateScaffoldContent(value) {
    return value
        .split(/\r?\n/)
        .filter((line) => !contracts_1.TEMPLATE_SCAFFOLD_PATTERN.test(line.trim()))
        .join("\n")
        .replace(/\n{3,}/g, "\n\n")
        .trim();
}
function firstContentLine(value) {
    for (const line of value.split(/\r?\n/)) {
        const trimmed = line.trim();
        if (trimmed !== "") {
            return trimmed;
        }
    }
    return "(empty)";
}
function normalizeReviewLines(value) {
    const lines = value
        .split(/\r?\n/)
        .map((line) => line.trim())
        .filter((line) => line !== "");
    if (lines.length === 0) {
        return ["- (none)"];
    }
    return lines.map((line) => line.startsWith("- ") ? line : `- ${line}`);
}
function sectionContradictsTaskEvidence(sectionName, value, taskEvidence) {
    if (sectionName !== "Final Notes") {
        return false;
    }
    const normalized = value.toLowerCase();
    const claimsClosure = /\b(complete|completed|closed|accepted|sufficient|no blocking|ready for downstream)\b/.test(normalized);
    return claimsClosure && (taskEvidence.completed.length === 0 || taskEvidence.incomplete.length > 0);
}
function appendIssueLines(lines, issues) {
    if (issues.length === 0) {
        lines.push("- (none)");
        return;
    }
    for (const issue of issues) {
        lines.push(`- ${issue}`);
    }
}
