"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.collectDocumentationLoopIssues = collectDocumentationLoopIssues;
exports.collectBreakoutTaskRequirementIssues = collectBreakoutTaskRequirementIssues;
exports.taskHasCompleteRuntimeDeltaEvidence = taskHasCompleteRuntimeDeltaEvidence;
exports.collectTaskSummaryPathsInDeclaredOrder = collectTaskSummaryPathsInDeclaredOrder;
exports.milestoneHasRuntimeAcceptanceCriteria = milestoneHasRuntimeAcceptanceCriteria;
exports.collectMilestoneOverviewPaths = collectMilestoneOverviewPaths;
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const paths_1 = require("../../paths");
const documentation_path_classifier_1 = require("../../validation/documentation-path-classifier");
const artifact_policy_projection_1 = require("../artifact-policy-projection");
const planning_document_utils_1 = require("../planning-document-utils");
const semantic_evidence_1 = require("../semantic-evidence");
const child_drift_1 = require("./child-drift");
const lifecycle_evidence_1 = require("./lifecycle-evidence");
function collectDocumentationLoopIssues(options) {
    if (!milestoneHasRuntimeAcceptanceCriteria(options.milestoneDocument)) {
        return [];
    }
    const milestoneDirectory = node_path_1.default.dirname(node_path_1.default.join(options.repositoryRoot, options.milestoneOverviewPath));
    const tasksDirectory = node_path_1.default.join(milestoneDirectory, 'tasks');
    const summaryEntries = options.declaredTaskSlugs.map((taskSlug, taskIndex) => {
        return {
            taskSlug,
            taskIndex,
            summaryPath: (0, planning_document_utils_1.toRepositoryLikePath)(node_path_1.default.relative(options.repositoryRoot, node_path_1.default.join(tasksDirectory, taskSlug, 'implementation-summary.md'))),
        };
    });
    let previousDocumentationOnlySummary = null;
    for (const entry of summaryEntries) {
        const summaryPath = entry.summaryPath;
        if (!node_fs_1.default.existsSync(node_path_1.default.join(options.repositoryRoot, summaryPath))) {
            previousDocumentationOnlySummary = null;
            continue;
        }
        const summaryState = (0, child_drift_1.readSummaryArtifactState)(options.repositoryRoot, summaryPath);
        if (summaryState?.implementationStatus !== 'completed' || summaryState.artifactStatus !== 'completed') {
            previousDocumentationOnlySummary = null;
            continue;
        }
        const summaryText = node_fs_1.default.readFileSync(node_path_1.default.join(options.repositoryRoot, summaryPath), 'utf8');
        const summaryDocument = (0, lifecycle_evidence_1.parseMarkdownDocument)(summaryPath, summaryText);
        const changedPaths = (0, semantic_evidence_1.readChangedPaths)(summaryDocument.sections.get('Changed Paths') ?? '');
        const documentationOnly = changedPaths.length > 0 && changedPaths.every((changedPath) => {
            return (0, documentation_path_classifier_1.classifyDocumentationPath)(changedPath).category === 'documentation-only';
        });
        if (!documentationOnly) {
            previousDocumentationOnlySummary = null;
            continue;
        }
        if (previousDocumentationOnlySummary !== null) {
            const issues = [
                `Documentation loop detected: completed summaries '${previousDocumentationOnlySummary}' and '${summaryPath}' changed only documentation-classified paths while milestone runtime acceptance criteria remain pending. The next accepted task must be runtime or hybrid breakout work before more contract refinement is accepted.`,
            ];
            issues.push(...collectBreakoutTaskRequirementIssues({
                repositoryRoot: options.repositoryRoot,
                milestoneOverviewPath: options.milestoneOverviewPath,
                declaredTaskSlugs: options.declaredTaskSlugs,
                previousSummaryPath: previousDocumentationOnlySummary,
                currentSummaryPath: summaryPath,
                nextTaskIndex: entry.taskIndex + 1,
            }));
            return issues;
        }
        previousDocumentationOnlySummary = summaryPath;
    }
    return [];
}
function collectBreakoutTaskRequirementIssues(options) {
    const nextTaskSlug = options.declaredTaskSlugs[options.nextTaskIndex];
    if (nextTaskSlug === undefined) {
        return [
            `Documentation loop breakout required after summaries '${options.previousSummaryPath}' and '${options.currentSummaryPath}', but no following declared task exists. Request a separate runtime or hybrid breakout task with Runtime Delta evidence and frozen contract evidence before accepting more contract refinement.`,
        ];
    }
    const nextTaskPath = (0, planning_document_utils_1.toRepositoryLikePath)(node_path_1.default.relative(options.repositoryRoot, node_path_1.default.join(node_path_1.default.dirname(node_path_1.default.join(options.repositoryRoot, options.milestoneOverviewPath)), 'tasks', nextTaskSlug, 'task-definition.md')));
    if (!node_fs_1.default.existsSync(node_path_1.default.join(options.repositoryRoot, nextTaskPath))) {
        return [
            `Documentation loop breakout task '${nextTaskSlug}' is declared after summaries '${options.previousSummaryPath}' and '${options.currentSummaryPath}', but its task definition is missing. Request a separate runtime or hybrid breakout task with Runtime Delta evidence and frozen contract evidence before accepting more contract refinement.`,
        ];
    }
    const taskText = node_fs_1.default.readFileSync(node_path_1.default.join(options.repositoryRoot, nextTaskPath), 'utf8');
    const taskDocument = (0, lifecycle_evidence_1.parseMarkdownDocument)(nextTaskPath, taskText);
    const evidenceProfile = (0, artifact_policy_projection_1.projectArtifactPolicy)(taskText).evidenceProfile;
    const issues = [];
    if (evidenceProfile !== 'runtime' && evidenceProfile !== 'hybrid') {
        issues.push(`Documentation loop breakout task '${nextTaskPath}' must use evidence_profile: runtime or evidence_profile: hybrid before more contract refinement is accepted.`);
    }
    if (!taskHasCompleteRuntimeDeltaEvidence(taskDocument)) {
        issues.push(`Documentation loop breakout task '${nextTaskPath}' must include complete Runtime Delta evidence before more contract refinement is accepted.`);
    }
    if (!(0, lifecycle_evidence_1.taskReferencesFrozenContractEvidence)(taskText)) {
        issues.push(`Documentation loop breakout task '${nextTaskPath}' must reference frozen contract evidence before more contract refinement is accepted.`);
    }
    return issues;
}
function taskHasCompleteRuntimeDeltaEvidence(taskDocument) {
    const runtimeDelta = (0, semantic_evidence_1.readRuntimeDeltaEvidence)(taskDocument.sections);
    if (runtimeDelta.sectionText === null || runtimeDelta.sectionText.trim().length === 0) {
        return false;
    }
    if (/not applicable|before changing this task|pending:/i.test(runtimeDelta.sectionText)) {
        return false;
    }
    return runtimeDelta.missingKinds.length === 0;
}
function collectTaskSummaryPathsInDeclaredOrder(repositoryRoot, milestoneOverviewPath, declaredTaskSlugs) {
    const milestoneDirectory = node_path_1.default.dirname(node_path_1.default.join(repositoryRoot, milestoneOverviewPath));
    const tasksDirectory = node_path_1.default.join(milestoneDirectory, 'tasks');
    if (!node_fs_1.default.existsSync(tasksDirectory)) {
        return [];
    }
    const declaredPaths = declaredTaskSlugs
        .map((slug) => node_path_1.default.join(tasksDirectory, slug, 'implementation-summary.md'))
        .filter((absolutePath) => node_fs_1.default.existsSync(absolutePath));
    if (declaredPaths.length > 0) {
        return declaredPaths.map((absolutePath) => {
            return (0, planning_document_utils_1.toRepositoryLikePath)(node_path_1.default.relative(repositoryRoot, absolutePath));
        });
    }
    return (0, lifecycle_evidence_1.collectTaskSummaryPaths)(repositoryRoot, milestoneOverviewPath);
}
function milestoneHasRuntimeAcceptanceCriteria(document) {
    const acceptanceCriteria = document.sections.get('Acceptance Criteria') ?? '';
    return /\bruntime\b|\bRuntime Delta\b|non-documentation code|executable validation/i.test(acceptanceCriteria);
}
function collectMilestoneOverviewPaths(repositoryRoot, phaseOverviewPath) {
    const phaseDirectory = node_path_1.default.dirname(node_path_1.default.join(repositoryRoot, phaseOverviewPath));
    const milestonesDirectory = node_path_1.default.join(phaseDirectory, 'milestones');
    if (!node_fs_1.default.existsSync(milestonesDirectory)) {
        return [];
    }
    return node_fs_1.default
        .readdirSync(milestonesDirectory, { withFileTypes: true })
        .filter((entry) => entry.isDirectory())
        .flatMap((entry) => {
        const milestoneDirectoryPath = (0, planning_document_utils_1.toRepositoryLikePath)(node_path_1.default.relative(repositoryRoot, node_path_1.default.join(milestonesDirectory, entry.name)));
        const resolution = (0, paths_1.resolvePlanningOverviewPath)(repositoryRoot, {
            layer: 'milestone',
            directoryPath: milestoneDirectoryPath,
        });
        return resolution.selected === null ? [] : [resolution.selected.path];
    })
        .sort();
}
