"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildEvidenceReviewRecoveryGuidance = buildEvidenceReviewRecoveryGuidance;
exports.buildEvidenceReviewFindings = buildEvidenceReviewFindings;
exports.createValidationFindingForMetadataFollowUp = createValidationFindingForMetadataFollowUp;
exports.formatFindingCategoryCode = formatFindingCategoryCode;
exports.reconciliationSectionFindingCategory = reconciliationSectionFindingCategory;
exports.extractImplementationSummaryReferences = extractImplementationSummaryReferences;
exports.decodeMarkdownLinkDestination = decodeMarkdownLinkDestination;
exports.resolveImplementationSummaryReference = resolveImplementationSummaryReference;
exports.hasActionableReviewText = hasActionableReviewText;
exports.collectDeclaredLaterWorkEntries = collectDeclaredLaterWorkEntries;
exports.collectLaterDeclaredChildren = collectLaterDeclaredChildren;
exports.matchDeclaredLaterWork = matchDeclaredLaterWork;
// 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 output_1 = require("../../output");
const front_matter_utils_1 = require("../front-matter-utils");
const contracts_1 = require("../implementation-summary/contracts");
const document_paths_1 = require("../implementation-summary/document-paths");
const planning_document_utils_1 = require("../planning-document-utils");
const semantic_placeholder_1 = require("../semantic-placeholder");
function buildEvidenceReviewRecoveryGuidance(options) {
    const guidance = [];
    if (options.blockingIssues.length > 0) {
        guidance.push(`This ${options.reviewKind} review is read-only and applied no writes; repair the cited blocking findings in '${options.artifactPath}' through an explicit build, update, or metadata command before treating the review as closeout evidence.`);
    }
    if (options.warnings.length > 0) {
        guidance.push("Carry warnings forward as advisory evidence only; they do not authorize implicit status transitions or other writes.");
    }
    if (options.metadataHygieneFollowUps.length > 0) {
        guidance.push(`Apply metadata follow-ups only through an explicit update or sync command for '${options.artifactPath}' after the evidence is complete.`);
    }
    return guidance;
}
function buildEvidenceReviewFindings(options) {
    const reviewPrefix = options.reviewKind === "implementation-summary"
        ? "IMPLEMENTATION_SUMMARY_REVIEW"
        : "RECONCILIATION_REVIEW";
    if (options.issues !== undefined) {
        return [
            ...options.issues.map((issue) => {
                const code = `${reviewPrefix}_${formatFindingCategoryCode(issue.category)}`;
                const evidence = {
                    category: "planning-review",
                    details: {
                        category: issue.category,
                        blocking: issue.severity === "error",
                        reviewKind: options.reviewKind,
                        artifactPath: options.artifactPath
                    }
                };
                if (issue.severity === "error") {
                    return (0, output_1.createBlockingValidationFinding)({
                        code,
                        message: issue.message,
                        path: issue.path,
                        artifacts: issue.artifacts,
                        affectedPaths: issue.affectedPaths,
                        blockingReason: issue.category === "metadata-alignment"
                            ? "unsafe-scope-mismatch"
                            : "broken-traceability",
                        recovery: `This ${options.reviewKind} review is read-only and applied no writes; repair the ${issue.category} evidence in '${options.artifactPath}' through an explicit build, update, or metadata command before treating the review as closeout evidence.`,
                        evidence
                    });
                }
                return (0, output_1.createAdvisoryValidationFinding)({
                    code,
                    message: issue.message,
                    path: issue.path,
                    artifacts: issue.artifacts,
                    affectedPaths: issue.affectedPaths,
                    advisoryReason: issue.category === "review-concern"
                        ? "possible-discovered-work"
                        : "weak-evidence",
                    recovery: "Carry this reconciliation review finding forward as advisory evidence only; it does not authorize implicit status transitions or writes.",
                    evidence
                });
            }),
            ...options.metadataHygieneFollowUps.map((message) => createValidationFindingForMetadataFollowUp(reviewPrefix, options.artifactPath, message))
        ];
    }
    const changedPathPlaceholderFindings = options.reviewKind === "implementation-summary"
        ? options.changedPathPlaceholderFindings ?? []
        : [];
    const typedPlaceholderMessages = new Set(changedPathPlaceholderFindings.map((entry) => entry.message));
    return [
        ...changedPathPlaceholderFindings.map((entry) => (0, output_1.createBlockingValidationFinding)({
            code: "IMPLEMENTATION_SUMMARY_REVIEW_CHANGED_PATH_PLACEHOLDER",
            message: entry.message,
            path: options.artifactPath,
            affectedPaths: [{
                    role: "finding-location",
                    path: options.artifactPath,
                    description: `Changed Paths placeholder entry at line ${entry.line}`
                }],
            blockingReason: "invalid-command-input",
            recovery: `Replace Changed Paths line ${entry.line} ('${entry.rawText}') with one top-level '- \`repository/relative/path\`' bullet after implementation changes exist.`,
            evidence: {
                category: "planning-review",
                details: {
                    category: "changed-path-placeholder",
                    blocking: true,
                    reviewKind: options.reviewKind,
                    artifactPath: options.artifactPath,
                    line: entry.line,
                    rawText: entry.rawText,
                    semanticState: entry.state
                }
            }
        })),
        ...options.blockingIssues
            .filter((message) => !typedPlaceholderMessages.has(message))
            .map((message) => ({
            code: `${reviewPrefix}_BLOCKING`,
            message,
            severity: "error",
            path: options.artifactPath
        })),
        ...options.warnings.map((message) => ({
            code: `${reviewPrefix}_WARNING`,
            message,
            severity: "warning",
            path: options.artifactPath
        })),
        ...options.metadataHygieneFollowUps.map((message) => ({
            code: `${reviewPrefix}_METADATA_FOLLOW_UP`,
            message,
            severity: "informational",
            path: options.artifactPath
        }))
    ];
}
function createValidationFindingForMetadataFollowUp(reviewPrefix, artifactPath, message) {
    return (0, output_1.createAdvisoryValidationFinding)({
        code: `${reviewPrefix}_METADATA_FOLLOW_UP`,
        message,
        severity: "informational",
        level: "informational",
        path: artifactPath,
        advisoryReason: "weak-evidence",
        recovery: `Apply metadata follow-ups only through an explicit update or sync command for '${artifactPath}' after the evidence is complete.`,
        evidence: {
            category: "planning-review",
            details: {
                category: "metadata-alignment",
                blocking: false,
                artifactPath
            }
        }
    });
}
function formatFindingCategoryCode(category) {
    return category.replace(/-/g, "_").toUpperCase();
}
function reconciliationSectionFindingCategory(sectionName) {
    switch (sectionName) {
        case "Completed Task Summaries":
            return "task-summary-reference-health";
        case "Acceptance Criteria Review":
            return "acceptance-criteria-coverage";
        case "Validation Review":
            return "validation-coverage";
        case "Review Concerns":
        case "Discovered Work":
        case "Backlog Work":
        case "Accepted Residual Work":
        case "Follow-Up Tasks":
            return "review-concern";
        default:
            return "reconciliation-completeness";
    }
}
function extractImplementationSummaryReferences(text, sourceArtifactPath) {
    const references = new Set();
    for (const match of text.matchAll(contracts_1.IMPLEMENTATION_SUMMARY_REFERENCE_PATTERN)) {
        references.add(match[1]);
    }
    for (const match of text.matchAll(contracts_1.MARKDOWN_IMPLEMENTATION_SUMMARY_LINK_PATTERN)) {
        const linkedPath = decodeMarkdownLinkDestination(match[1]);
        if (linkedPath === null) {
            continue;
        }
        references.add(resolveImplementationSummaryReference(linkedPath, sourceArtifactPath));
    }
    return references;
}
function decodeMarkdownLinkDestination(destination) {
    try {
        return decodeURI(destination);
    }
    catch {
        return null;
    }
}
function resolveImplementationSummaryReference(referencePath, sourceArtifactPath) {
    if (referencePath.startsWith(".day-shift/")) {
        return (0, front_matter_utils_1.toRepositoryLikePath)(referencePath);
    }
    return (0, front_matter_utils_1.toRepositoryLikePath)(node_path_1.default.posix.normalize(node_path_1.default.posix.join(node_path_1.default.posix.dirname(sourceArtifactPath), referencePath)));
}
function hasActionableReviewText(text) {
    if (text === undefined || (0, semantic_placeholder_1.hasSemanticPlaceholderContent)(text)) {
        return false;
    }
    const normalized = text.trim().replace(/^[-*]\s+/gm, "").trim();
    if (normalized === "") {
        return false;
    }
    if (/^(none|none\.|no concerns\.?|no follow-up tasks\.?|none identified by build refresh\.?)$/i.test(normalized)) {
        return false;
    }
    if (/^no immediate evidence-gap concerns were detected during build refresh/i.test(normalized)) {
        return false;
    }
    if (/review is now complete/i.test(normalized)) {
        return false;
    }
    return true;
}
function collectDeclaredLaterWorkEntries(repositoryRoot, context) {
    return [
        ...collectLaterDeclaredChildren({
            repositoryRoot,
            sourcePath: context.phaseOverviewPath,
            sectionName: "Milestones",
            currentSlug: context.milestone,
            kind: "milestone"
        }),
        ...collectLaterDeclaredChildren({
            repositoryRoot,
            sourcePath: context.sliceOverviewPath,
            sectionName: "Phases",
            currentSlug: context.phase,
            kind: "phase"
        })
    ];
}
function collectLaterDeclaredChildren(options) {
    const sourceAbsolutePath = node_path_1.default.join(options.repositoryRoot, options.sourcePath);
    if (!node_fs_1.default.existsSync(sourceAbsolutePath)) {
        return [];
    }
    const document = (0, document_paths_1.parseMarkdownDocument)(options.sourcePath, node_fs_1.default.readFileSync(sourceAbsolutePath, "utf8"));
    const declaredSlugs = (0, planning_document_utils_1.readDeclaredChildSlugs)(document.sections.get(options.sectionName) ?? "");
    const currentIndex = declaredSlugs.indexOf(options.currentSlug);
    if (currentIndex === -1) {
        return [];
    }
    return declaredSlugs.slice(currentIndex + 1).map((slug) => ({
        kind: options.kind,
        slug,
        sourcePath: options.sourcePath
    }));
}
function matchDeclaredLaterWork(text, declaredLaterWork) {
    for (const entry of declaredLaterWork) {
        const expression = new RegExp(`(^|[^a-z0-9-])${(0, document_paths_1.escapeRegExp)(entry.slug)}([^a-z0-9-]|$)`, "iu");
        if (expression.test(text)) {
            return entry;
        }
    }
    return null;
}
