"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.collectArtifactGaps = collectArtifactGaps;
exports.collectStructuredTaskGaps = collectStructuredTaskGaps;
exports.resolveStructuredTaskDefinitionPath = resolveStructuredTaskDefinitionPath;
exports.collectLightweightTaskGaps = collectLightweightTaskGaps;
exports.collectDeclaredChildGaps = collectDeclaredChildGaps;
exports.collectTaskSummariesForMilestone = collectTaskSummariesForMilestone;
exports.areAllKnownTaskImplementationSummariesCompleteForMilestone = areAllKnownTaskImplementationSummariesCompleteForMilestone;
exports.areAllTaskImplementationSummariesComplete = areAllTaskImplementationSummariesComplete;
exports.areAllDeclaredMilestonesReconciled = areAllDeclaredMilestonesReconciled;
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const paths_1 = require("../../paths");
const ordered_root_identity_1 = require("../ordered-root-identity");
const planning_document_utils_1 = require("../planning-document-utils");
const artifact_discovery_1 = require("./artifact-discovery");
const document_support_1 = require("./document-support");
function collectArtifactGaps(repositoryRoot, record, gapMap) {
    switch (record.artifactType) {
        case "work_overview":
            collectStructuredTaskGaps(repositoryRoot, record, gapMap);
            return;
        case "slice_overview":
            if (record.planningDepth === "lightweight") {
                collectLightweightTaskGaps(repositoryRoot, record, gapMap);
                return;
            }
            collectDeclaredChildGaps(repositoryRoot, record, "Phases", "phase_overview", gapMap);
            return;
        case "phase_overview":
            for (const finding of (0, document_support_1.phaseScaffoldRefinementFindings)(repositoryRoot, record)) {
                (0, document_support_1.addGap)(gapMap, finding);
            }
            collectDeclaredChildGaps(repositoryRoot, record, "Milestones", "milestone_overview", gapMap);
            return;
        case "milestone_overview": {
            const reconciliationPath = (0, document_support_1.pairedReconciliationPath)(record.path);
            const reconciliationRecord = (0, artifact_discovery_1.readArtifactIfExists)(repositoryRoot, reconciliationPath);
            const allTaskSummariesComplete = areAllTaskImplementationSummariesComplete(repositoryRoot, record.path);
            if (allTaskSummariesComplete && reconciliationRecord === null) {
                (0, document_support_1.addGap)(gapMap, {
                    code: "MISSING_ARTIFACT",
                    path: reconciliationPath,
                    message: `Expected milestone reconciliation '${reconciliationPath}' is missing for '${record.path}'.`
                });
            }
            else if (allTaskSummariesComplete
                && reconciliationRecord !== null
                && !(0, document_support_1.isCompletedReconciliation)(reconciliationRecord)) {
                (0, document_support_1.addGap)(gapMap, {
                    code: "INCOMPLETE_ARTIFACT",
                    path: reconciliationPath,
                    message: `Milestone reconciliation '${reconciliationPath}' is present but still incomplete after all task implementation summaries are complete.`
                });
            }
            const taskSlugs = (0, document_support_1.readDeclaredChildSlugsFromDocument)(record.document, "Tasks");
            for (const taskSlug of taskSlugs) {
                const taskDefinitionPath = (0, planning_document_utils_1.toRepositoryLikePath)(node_path_1.default.posix.join(node_path_1.default.posix.dirname(record.path), "tasks", taskSlug, "task-definition.md"));
                const taskDirectory = (0, paths_1.resolveRepositoryRelativePath)(repositoryRoot, (0, paths_1.parseRepositoryRelativePath)(node_path_1.default.posix.dirname(taskDefinitionPath)));
                if (!node_fs_1.default.existsSync(taskDirectory)) {
                    (0, document_support_1.addGap)(gapMap, {
                        code: "MISSING_ARTIFACT",
                        path: taskDefinitionPath,
                        message: `Declared task '${taskSlug}' is missing task definition '${taskDefinitionPath}'.`
                    });
                    continue;
                }
                const taskRecord = (0, artifact_discovery_1.readArtifactIfExists)(repositoryRoot, taskDefinitionPath);
                if (taskRecord === null) {
                    (0, document_support_1.addGap)(gapMap, {
                        code: "MISSING_ARTIFACT",
                        path: taskDefinitionPath,
                        message: `Declared task '${taskSlug}' is missing task definition '${taskDefinitionPath}'.`
                    });
                    continue;
                }
                collectArtifactGaps(repositoryRoot, taskRecord, gapMap);
            }
            return;
        }
        case "task_definition": {
            const taskIsClosed = (0, document_support_1.isClosedTaskDefinition)(record);
            const summaryPath = (0, document_support_1.pairedImplementationSummaryPath)(record.path);
            const summaryRecord = (0, artifact_discovery_1.readArtifactIfExists)(repositoryRoot, summaryPath);
            if (taskIsClosed && summaryRecord === null) {
                (0, document_support_1.addGap)(gapMap, {
                    code: "MISSING_ARTIFACT",
                    path: summaryPath,
                    message: `Expected implementation summary '${summaryPath}' is missing for task '${record.path}'.`
                });
                return;
            }
            if (taskIsClosed && summaryRecord !== null && !(0, document_support_1.isCompletedImplementationSummary)(summaryRecord)) {
                (0, document_support_1.addGap)(gapMap, {
                    code: "INCOMPLETE_ARTIFACT",
                    path: summaryPath,
                    message: `Implementation summary '${summaryPath}' is present but still incomplete.`
                });
            }
            if (summaryRecord !== null
                && (0, document_support_1.isCompletedImplementationSummary)(summaryRecord)
                && record.status !== "completed") {
                (0, document_support_1.addGap)(gapMap, {
                    code: "STALE_PAIRING",
                    path: record.path,
                    message: `Task definition '${record.path}' still needs closeout metadata after completed implementation evidence.`
                });
            }
            return;
        }
        case "implementation_summary": {
            const taskDefinitionPath = (0, document_support_1.pairedTaskDefinitionPath)(record.path);
            if ((0, artifact_discovery_1.readArtifactIfExists)(repositoryRoot, taskDefinitionPath) === null) {
                (0, document_support_1.addGap)(gapMap, {
                    code: "MISSING_ARTIFACT",
                    path: taskDefinitionPath,
                    message: `Expected task definition '${taskDefinitionPath}' is missing for implementation summary '${record.path}'.`
                });
            }
            if (!(0, document_support_1.isCompletedImplementationSummary)(record)) {
                (0, document_support_1.addGap)(gapMap, {
                    code: "INCOMPLETE_ARTIFACT",
                    path: record.path,
                    message: `Implementation summary '${record.path}' still carries placeholder or incomplete execution evidence.`
                });
            }
            return;
        }
        case "reconciliation":
            if (!(0, document_support_1.isCompletedReconciliation)(record)) {
                (0, document_support_1.addGap)(gapMap, {
                    code: "INCOMPLETE_ARTIFACT",
                    path: record.path,
                    message: `Reconciliation '${record.path}' still carries placeholder or incomplete review evidence.`
                });
            }
            return;
        default:
            return (0, document_support_1.assertNever)(record.artifactType);
    }
}
function collectStructuredTaskGaps(repositoryRoot, workRecord, gapMap) {
    const taskSlugs = (0, document_support_1.readDeclaredChildSlugsFromDocument)(workRecord.document, "Task Plan");
    for (const taskSlug of taskSlugs) {
        const taskDefinitionPath = resolveStructuredTaskDefinitionPath(repositoryRoot, workRecord.path, taskSlug);
        const summaryPath = (0, document_support_1.pairedImplementationSummaryPath)(taskDefinitionPath);
        const taskRecord = (0, artifact_discovery_1.readArtifactIfExists)(repositoryRoot, taskDefinitionPath);
        if (taskRecord === null) {
            (0, document_support_1.addGap)(gapMap, {
                code: "MISSING_ARTIFACT",
                path: taskDefinitionPath,
                message: `Structured work overview '${workRecord.path}' declares direct task '${taskSlug}' but task definition '${taskDefinitionPath}' is missing.`
            });
            continue;
        }
        if ((0, artifact_discovery_1.readArtifactIfExists)(repositoryRoot, summaryPath) === null) {
            (0, document_support_1.addGap)(gapMap, {
                code: "MISSING_ARTIFACT",
                path: summaryPath,
                message: `Structured direct task '${taskSlug}' is missing paired implementation summary '${summaryPath}'.`
            });
        }
        collectArtifactGaps(repositoryRoot, taskRecord, gapMap);
    }
}
function resolveStructuredTaskDefinitionPath(repositoryRoot, workOverviewPath, taskIdentityOrBasename) {
    const collectionPath = (0, planning_document_utils_1.toRepositoryLikePath)(node_path_1.default.posix.join(node_path_1.default.posix.dirname(workOverviewPath), "tasks"));
    const directPath = (0, planning_document_utils_1.toRepositoryLikePath)(node_path_1.default.posix.join(collectionPath, taskIdentityOrBasename, "task-definition.md"));
    const direct = (0, paths_1.resolveRepositoryRelativePath)(repositoryRoot, (0, paths_1.parseRepositoryRelativePath)(directPath));
    if (node_fs_1.default.existsSync(direct) && node_fs_1.default.statSync(direct).isFile())
        return directPath;
    try {
        const inventory = (0, ordered_root_identity_1.inspectStructuredTaskCollectionSync)({ repositoryRoot, collectionPath });
        const matches = inventory.entries.filter((entry) => entry.taskId === taskIdentityOrBasename);
        return matches.length === 1 ? matches[0].taskDefinitionPath : directPath;
    }
    catch {
        return directPath;
    }
}
function collectLightweightTaskGaps(repositoryRoot, sliceRecord, gapMap) {
    const tasksDirectory = (0, paths_1.resolveRepositoryRelativePath)(repositoryRoot, (0, paths_1.parseRepositoryRelativePath)((0, planning_document_utils_1.toRepositoryLikePath)(node_path_1.default.posix.join(node_path_1.default.posix.dirname(sliceRecord.path), "tasks"))));
    if (!node_fs_1.default.existsSync(tasksDirectory)) {
        return;
    }
    const taskSlugs = node_fs_1.default.readdirSync(tasksDirectory).sort((left, right) => left.localeCompare(right));
    for (const taskSlug of taskSlugs) {
        const taskDefinitionPath = (0, planning_document_utils_1.toRepositoryLikePath)(node_path_1.default.posix.join(node_path_1.default.posix.dirname(sliceRecord.path), "tasks", taskSlug, "task-definition.md"));
        const taskRecord = (0, artifact_discovery_1.readArtifactIfExists)(repositoryRoot, taskDefinitionPath);
        if (taskRecord === null) {
            (0, document_support_1.addGap)(gapMap, {
                code: "MISSING_ARTIFACT",
                path: taskDefinitionPath,
                message: `Lightweight task directory '${taskSlug}' is missing task definition '${taskDefinitionPath}'.`
            });
            continue;
        }
        collectArtifactGaps(repositoryRoot, taskRecord, gapMap);
    }
}
function collectDeclaredChildGaps(repositoryRoot, record, sectionName, childArtifactType, gapMap) {
    const childSlugs = (0, document_support_1.readDeclaredChildSlugsFromDocument)(record.document, sectionName);
    const childDirectoryName = sectionName === "Phases" ? "phases" : "milestones";
    const childLayer = childArtifactType === "phase_overview" ? "phase" : "milestone";
    for (const childSlug of childSlugs) {
        const childDirectoryPath = (0, planning_document_utils_1.toRepositoryLikePath)(node_path_1.default.posix.join(node_path_1.default.posix.dirname(record.path), childDirectoryName, childSlug));
        const childDirectory = (0, paths_1.resolveRepositoryRelativePath)(repositoryRoot, (0, paths_1.parseRepositoryRelativePath)(childDirectoryPath));
        if (!node_fs_1.default.existsSync(childDirectory)) {
            const childOverviewPath = (0, paths_1.composeCanonicalPlanningOverviewPath)(childLayer, childDirectoryPath);
            (0, document_support_1.addGap)(gapMap, {
                code: "MISSING_ARTIFACT",
                path: childOverviewPath,
                message: `Declared ${childArtifactType === "phase_overview" ? "phase" : "milestone"} '${childSlug}' is missing overview '${childOverviewPath}'.`
            });
            continue;
        }
        const childResolution = (0, paths_1.resolvePlanningOverviewPath)(repositoryRoot, {
            layer: childLayer,
            directoryPath: childDirectoryPath
        });
        const childOverviewPath = childResolution.selected?.path
            ?? (0, paths_1.composeCanonicalPlanningOverviewPath)(childLayer, childDirectoryPath);
        const childRecord = childResolution.selected === null
            ? null
            : (0, artifact_discovery_1.readArtifactIfExists)(repositoryRoot, childOverviewPath);
        if (childResolution.status === "conflict") {
            (0, document_support_1.addGap)(gapMap, {
                code: "PATH_CONFLICT",
                path: childOverviewPath,
                message: childResolution.message
            });
            continue;
        }
        if (childRecord === null) {
            (0, document_support_1.addGap)(gapMap, {
                code: "MISSING_ARTIFACT",
                path: childOverviewPath,
                message: `Declared ${childArtifactType === "phase_overview" ? "phase" : "milestone"} '${childSlug}' is missing overview '${childOverviewPath}'.`
            });
            continue;
        }
        collectArtifactGaps(repositoryRoot, childRecord, gapMap);
    }
}
function collectTaskSummariesForMilestone(repositoryRoot, milestoneOverviewPath) {
    const taskDirectory = (0, paths_1.resolveRepositoryRelativePath)(repositoryRoot, (0, paths_1.parseRepositoryRelativePath)((0, planning_document_utils_1.toRepositoryLikePath)(node_path_1.default.posix.join(node_path_1.default.posix.dirname(milestoneOverviewPath), "tasks"))));
    if (!node_fs_1.default.existsSync(taskDirectory)) {
        return [];
    }
    const summaries = [];
    const taskChildren = node_fs_1.default.readdirSync(taskDirectory);
    for (const taskSlug of taskChildren) {
        const summaryPath = (0, planning_document_utils_1.toRepositoryLikePath)(node_path_1.default.posix.join(node_path_1.default.posix.dirname(milestoneOverviewPath), "tasks", taskSlug, "implementation-summary.md"));
        const summaryRecord = (0, artifact_discovery_1.readArtifactIfExists)(repositoryRoot, summaryPath);
        if (summaryRecord !== null) {
            summaries.push(summaryRecord);
        }
    }
    return summaries.sort((left, right) => left.path.localeCompare(right.path));
}
function areAllKnownTaskImplementationSummariesCompleteForMilestone(taskDefinitions, summaries, milestoneOverviewPath) {
    const taskPathPrefix = `${node_path_1.default.posix.dirname(milestoneOverviewPath)}/tasks/`;
    const taskRecords = taskDefinitions.filter((record) => record.path.startsWith(taskPathPrefix));
    if (taskRecords.length === 0) {
        return false;
    }
    return taskRecords.every((taskRecord) => {
        const summaryPath = (0, document_support_1.pairedImplementationSummaryPath)(taskRecord.path);
        const summaryRecord = summaries.find((record) => record.path === summaryPath) ?? null;
        return summaryRecord !== null && (0, document_support_1.isCompletedImplementationSummary)(summaryRecord);
    });
}
function areAllTaskImplementationSummariesComplete(repositoryRoot, milestoneOverviewPath) {
    const taskDirectory = (0, paths_1.resolveRepositoryRelativePath)(repositoryRoot, (0, paths_1.parseRepositoryRelativePath)((0, planning_document_utils_1.toRepositoryLikePath)(node_path_1.default.posix.join(node_path_1.default.posix.dirname(milestoneOverviewPath), "tasks"))));
    if (!node_fs_1.default.existsSync(taskDirectory)) {
        return false;
    }
    const taskChildren = node_fs_1.default.readdirSync(taskDirectory)
        .filter((taskSlug) => node_fs_1.default.statSync(node_path_1.default.join(taskDirectory, taskSlug)).isDirectory());
    if (taskChildren.length === 0) {
        return false;
    }
    return taskChildren.every((taskSlug) => {
        const summaryPath = (0, planning_document_utils_1.toRepositoryLikePath)(node_path_1.default.posix.join(node_path_1.default.posix.dirname(milestoneOverviewPath), "tasks", taskSlug, "implementation-summary.md"));
        const summaryRecord = (0, artifact_discovery_1.readArtifactIfExists)(repositoryRoot, summaryPath);
        return summaryRecord !== null && (0, document_support_1.isCompletedImplementationSummary)(summaryRecord);
    });
}
function areAllDeclaredMilestonesReconciled(repositoryRoot, phaseRecord) {
    const milestoneSlugs = (0, document_support_1.readDeclaredChildSlugsFromDocument)(phaseRecord.document, "Milestones");
    if (milestoneSlugs.length === 0)
        return false;
    return milestoneSlugs.every((milestoneSlug) => {
        const milestoneDirectoryPath = (0, planning_document_utils_1.toRepositoryLikePath)(node_path_1.default.posix.join(node_path_1.default.posix.dirname(phaseRecord.path), "milestones", milestoneSlug));
        const resolution = (0, paths_1.resolvePlanningOverviewPath)(repositoryRoot, {
            layer: "milestone",
            directoryPath: milestoneDirectoryPath
        });
        if (resolution.status === "conflict" || resolution.selected === null)
            return false;
        const reconciliationRecord = (0, artifact_discovery_1.readArtifactIfExists)(repositoryRoot, (0, document_support_1.pairedReconciliationPath)(resolution.selected.path));
        return reconciliationRecord !== null && (0, document_support_1.isCompletedReconciliation)(reconciliationRecord);
    });
}
