"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildTaskCurrentLifecycleEvidence = buildTaskCurrentLifecycleEvidence;
exports.buildMilestoneCurrentLifecycleEvidence = buildMilestoneCurrentLifecycleEvidence;
exports.readRequiredDocument = readRequiredDocument;
exports.resolveRepositoryPath = resolveRepositoryPath;
exports.parseMarkdownDocument = parseMarkdownDocument;
exports.trimSectionContent = trimSectionContent;
exports.collectReadinessSectionIssues = collectReadinessSectionIssues;
exports.isResolvedOpenQuestions = isResolvedOpenQuestions;
exports.collectTaskSummaryPaths = collectTaskSummaryPaths;
exports.collectTaskDirectorySlugs = collectTaskDirectorySlugs;
exports.collectTaskDefinitionPathsInDeclaredOrder = collectTaskDefinitionPathsInDeclaredOrder;
exports.collectContractToRuntimeHandoffIssues = collectContractToRuntimeHandoffIssues;
exports.taskReferencesFrozenContractEvidence = taskReferencesFrozenContractEvidence;
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const errors_1 = require("../../errors");
const paths_1 = require("../../paths");
const artifact_policy_projection_1 = require("../artifact-policy-projection");
const planning_artifact_document_1 = require("../planning-artifact-document");
const planning_document_utils_1 = require("../planning-document-utils");
const child_drift_1 = require("./child-drift");
function buildTaskCurrentLifecycleEvidence(options) {
    const evidence = [];
    if (options.reviewMode === 'readiness' && options.taskReadiness === 'ready_to_implement') {
        evidence.push(`task definition '${options.taskDefinitionPath}' declares readiness 'ready_to_implement'`);
    }
    if (options.summaryState?.implementationStatus === 'completed' && options.summaryState.artifactStatus === 'completed') {
        evidence.push(`paired implementation summary '${options.summaryState.path}' is completed`);
    }
    else if (options.summaryState?.substantiveEvidence === true) {
        evidence.push(`paired implementation summary '${options.summaryState.path}' contains current execution evidence`);
    }
    return evidence;
}
function buildMilestoneCurrentLifecycleEvidence(options) {
    const evidence = [];
    if (options.completedTaskSummaryPaths.length > 0) {
        evidence.push(`${options.completedTaskSummaryPaths.length} completed task implementation summary artifact(s) are present`);
    }
    if (options.reconciliationPath !== null && options.incompleteTaskSummaryPaths.length === 0) {
        evidence.push(`paired milestone reconciliation '${options.reconciliationPath}' is present for all declared task evidence`);
    }
    return evidence;
}
function readRequiredDocument(absolutePath, relativePath, expectedArtifactType) {
    if (!node_fs_1.default.existsSync(absolutePath)) {
        throw (0, errors_1.createUsageError)(`Artifact not found at '${relativePath}'.`);
    }
    const document = parseMarkdownDocument(relativePath, node_fs_1.default.readFileSync(absolutePath, 'utf8'));
    const artifactType = (0, planning_document_utils_1.readTopLevelField)(document.frontMatterLines, 'artifact_type')?.trim() ?? null;
    if (artifactType !== expectedArtifactType) {
        throw (0, errors_1.createUsageError)(`Artifact '${relativePath}' must use artifact_type: ${expectedArtifactType}.`, [
            `Found: ${artifactType ?? '(missing)'}`,
        ]);
    }
    return document;
}
function resolveRepositoryPath(repositoryRoot, inputPath, label) {
    try {
        if (label === 'phase-overview') {
            return (0, paths_1.resolvePlanningOverviewInputPath)(repositoryRoot, {
                layer: 'phase',
                inputPath,
            });
        }
        if (label === 'milestone-overview') {
            return (0, paths_1.resolvePlanningOverviewInputPath)(repositoryRoot, {
                layer: 'milestone',
                inputPath,
            });
        }
        const parsed = (0, paths_1.parseRepositoryRelativePath)(inputPath);
        return {
            relative: parsed.normalizedPath,
            absolute: node_path_1.default.join(repositoryRoot, parsed.normalizedPath),
        };
    }
    catch (error) {
        throw (0, errors_1.createUsageError)(`Invalid --${label} path '${inputPath}'.`, [
            error instanceof Error ? error.message : String(error),
        ]);
    }
}
function parseMarkdownDocument(filePath, text) {
    const parsed = (0, planning_artifact_document_1.parsePlanningArtifactDocument)(text);
    if (!parsed.hasFrontMatter) {
        if (parsed.diagnostics.some((diagnostic) => diagnostic.code === 'unterminated-front-matter')) {
            throw (0, errors_1.createUsageError)(`Artifact '${filePath}' has malformed YAML front matter.`);
        }
        throw (0, errors_1.createUsageError)(`Artifact '${filePath}' is missing YAML front matter.`);
    }
    const sections = new Map();
    for (const section of parsed.sections) {
        sections.set(section.heading, section.contentText.trim());
    }
    return {
        rawText: text,
        frontMatterLines: parsed.frontMatterLines,
        sections,
    };
}
function trimSectionContent(lines) {
    return lines.join('\n').replace(/^\n+/, '').replace(/\n+$/, '').trim();
}
function collectReadinessSectionIssues(document, filePath, requiredSections, blockingIssues) {
    for (const sectionName of requiredSections) {
        const sectionText = document.sections.get(sectionName);
        if (sectionText === undefined) {
            blockingIssues.push(`Artifact '${filePath}' is missing required section '${sectionName}'.`);
            continue;
        }
        if ((0, child_drift_1.isPlaceholderContent)(sectionText)) {
            blockingIssues.push(`Section '${sectionName}' in '${filePath}' is still incomplete.`);
        }
    }
    const openQuestionsText = document.sections.get('Open Questions');
    if (openQuestionsText !== undefined && !isResolvedOpenQuestions(openQuestionsText)) {
        blockingIssues.push(`Artifact '${filePath}' still has unresolved open questions.`);
    }
}
function isResolvedOpenQuestions(text) {
    const normalized = text.trim().toLowerCase();
    return (normalized === '- none currently.' ||
        normalized === 'none currently.' ||
        normalized === '- none.' ||
        normalized === 'none.');
}
function collectTaskSummaryPaths(repositoryRoot, milestoneOverviewPath) {
    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 [];
    }
    return node_fs_1.default
        .readdirSync(tasksDirectory, { withFileTypes: true })
        .filter((entry) => entry.isDirectory())
        .map((entry) => node_path_1.default.join(tasksDirectory, entry.name, 'implementation-summary.md'))
        .filter((absolutePath) => node_fs_1.default.existsSync(absolutePath))
        .map((absolutePath) => {
        return (0, planning_document_utils_1.toRepositoryLikePath)(node_path_1.default.relative(repositoryRoot, absolutePath));
    })
        .sort();
}
function collectTaskDirectorySlugs(repositoryRoot, milestoneOverviewPath) {
    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 [];
    }
    return node_fs_1.default
        .readdirSync(tasksDirectory, { withFileTypes: true })
        .filter((entry) => entry.isDirectory())
        .map((entry) => entry.name)
        .sort();
}
function collectTaskDefinitionPathsInDeclaredOrder(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, 'task-definition.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 node_fs_1.default
        .readdirSync(tasksDirectory, { withFileTypes: true })
        .filter((entry) => entry.isDirectory())
        .map((entry) => node_path_1.default.join(tasksDirectory, entry.name, 'task-definition.md'))
        .filter((absolutePath) => node_fs_1.default.existsSync(absolutePath))
        .map((absolutePath) => {
        return (0, planning_document_utils_1.toRepositoryLikePath)(node_path_1.default.relative(repositoryRoot, absolutePath));
    })
        .sort();
}
function collectContractToRuntimeHandoffIssues(options) {
    const taskDefinitionPaths = collectTaskDefinitionPathsInDeclaredOrder(options.repositoryRoot, options.milestoneOverviewPath, options.declaredTaskSlugs);
    let contractTaskSeen = false;
    for (const taskDefinitionPath of taskDefinitionPaths) {
        const absolutePath = node_path_1.default.join(options.repositoryRoot, taskDefinitionPath);
        const taskText = node_fs_1.default.readFileSync(absolutePath, 'utf8');
        const taskDocument = parseMarkdownDocument(taskDefinitionPath, taskText);
        const artifactType = (0, planning_document_utils_1.readTopLevelField)(taskDocument.frontMatterLines, 'artifact_type')?.trim() ?? null;
        if (artifactType !== 'task_definition') {
            continue;
        }
        const evidenceProfile = (0, artifact_policy_projection_1.projectArtifactPolicy)(taskText).evidenceProfile;
        if (evidenceProfile === 'contract') {
            contractTaskSeen = true;
            continue;
        }
        if ((evidenceProfile === 'runtime' || evidenceProfile === 'hybrid') && contractTaskSeen) {
            if (!taskReferencesFrozenContractEvidence(taskText)) {
                return [
                    `Runtime handoff task '${taskDefinitionPath}' follows contract work but does not reference frozen contract evidence. Add a repository-relative frozen-contract evidence link before treating this milestone as closeout-ready.`,
                ];
            }
            return [];
        }
    }
    return [];
}
function taskReferencesFrozenContractEvidence(taskText) {
    return /frozen[- ]contract evidence/i.test(taskText) && /\.day-shift\/[^\s`)\]]+/.test(taskText);
}
