"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseDeclaredChildSlugs = parseDeclaredChildSlugs;
exports.collectMilestoneChildDriftIssues = collectMilestoneChildDriftIssues;
exports.collectPhaseChildDriftIssues = collectPhaseChildDriftIssues;
exports.readSummaryArtifactState = readSummaryArtifactState;
exports.hasSubstantiveSummaryEvidence = hasSubstantiveSummaryEvidence;
exports.readMilestoneArtifactState = readMilestoneArtifactState;
exports.isPlaceholderContent = isPlaceholderContent;
exports.documentHasPlaceholderContent = documentHasPlaceholderContent;
exports.appendIssueLines = appendIssueLines;
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const paths_1 = require("../../paths");
const planning_document_utils_1 = require("../planning-document-utils");
const task_lifecycle_1 = require("../task-lifecycle");
const contracts_1 = require("./contracts");
const lifecycle_evidence_1 = require("./lifecycle-evidence");
function parseDeclaredChildSlugs(sectionText) {
    if (sectionText === undefined) {
        return [];
    }
    const slugs = [];
    for (const line of sectionText.split(/\r?\n/)) {
        const declaration = (0, planning_document_utils_1.parseDeclaredChildSlugBullet)(line);
        if (declaration !== null) {
            const hrefPath = declaration.href?.split("#", 1)[0].replace(/\\/gu, "/").replace(/\/+$/u, "");
            const hrefFile = hrefPath === undefined ? null : node_path_1.default.posix.basename(hrefPath);
            const slug = hrefFile === "task-definition.md"
                || hrefFile === "milestone-overview.md"
                || hrefFile === "phase-overview.md"
                ? node_path_1.default.posix.basename(node_path_1.default.posix.dirname(hrefPath))
                : declaration.slug;
            slugs.push(slug);
        }
    }
    return slugs;
}
function collectMilestoneChildDriftIssues(options) {
    const declared = new Set(options.declaredTaskSlugs);
    const observed = new Set(options.observedTaskSlugs);
    for (const slug of options.declaredTaskSlugs) {
        const taskDirectoryPath = (0, planning_document_utils_1.toRepositoryLikePath)(node_path_1.default.join(node_path_1.default.dirname(options.milestoneOverviewPath), 'tasks', slug));
        const summaryPath = (0, planning_document_utils_1.toRepositoryLikePath)(node_path_1.default.join(taskDirectoryPath, 'implementation-summary.md'));
        if (!observed.has(slug)) {
            options.blockingIssues.push(`Milestone overview '${options.milestoneOverviewPath}' declares task '${slug}' but child task directory '${taskDirectoryPath}' is missing. Recommended command: day-shift task new --milestone-overview ${options.milestoneOverviewPath} --task-slug ${slug}.`);
            continue;
        }
        if (!options.taskSummaryPaths.includes(summaryPath)) {
            options.blockingIssues.push(`Milestone overview '${options.milestoneOverviewPath}' declares task '${slug}' but child implementation summary '${summaryPath}' is missing. Recommended command: day-shift implementation-summary build --task-definition ${taskDirectoryPath}/task-definition.md.`);
        }
    }
    for (const slug of options.observedTaskSlugs) {
        if (!declared.has(slug)) {
            options.warnings.push(`Observed task child '${slug}' under '${options.milestoneOverviewPath}' is not declared in the parent Tasks section. Review the parent overview or move the child artifact before closeout.`);
        }
    }
    if (options.milestoneStatus === 'completed' &&
        (options.blockingIssues.length > 0 || options.incompleteTaskSummaryPaths.length > 0)) {
        options.blockingIssues.push(`Milestone overview '${options.milestoneOverviewPath}' has status 'completed' while declared child task evidence is missing or incomplete. Recommended command: day-shift milestone review --milestone-overview ${options.milestoneOverviewPath}.`);
    }
}
function collectPhaseChildDriftIssues(options) {
    const declared = new Set(options.declaredMilestoneSlugs);
    const observed = new Set(options.observedMilestoneSlugs);
    for (const slug of options.declaredMilestoneSlugs) {
        const milestoneDirectoryPath = (0, planning_document_utils_1.toRepositoryLikePath)(node_path_1.default.join(node_path_1.default.dirname(options.phaseOverviewPath), 'milestones', slug));
        const milestoneResolution = (0, paths_1.resolvePlanningOverviewPath)(options.repositoryRoot, {
            layer: 'milestone',
            directoryPath: milestoneDirectoryPath,
        });
        const milestoneOverviewPath = milestoneResolution.selected?.path
            ?? (0, paths_1.composeCanonicalPlanningOverviewPath)('milestone', milestoneDirectoryPath);
        if (milestoneResolution.status === 'conflict') {
            options.blockingIssues.push(`Phase overview '${options.phaseOverviewPath}' declares milestone '${slug}' but child overview candidates conflict. ${milestoneResolution.message}`);
            continue;
        }
        if (!observed.has(slug) && options.allowMissingDeclaredChildren !== true) {
            options.blockingIssues.push(`Phase overview '${options.phaseOverviewPath}' declares milestone '${slug}' but child overview '${milestoneOverviewPath}' is missing. Recommended command: day-shift milestone new --phase-overview ${options.phaseOverviewPath} --milestone-slug ${slug}.`);
        }
    }
    for (const slug of options.observedMilestoneSlugs) {
        if (!declared.has(slug)) {
            options.warnings.push(`Observed milestone child '${slug}' under '${options.phaseOverviewPath}' is not declared in the parent Milestones section. Review the parent overview or move the child artifact before closeout.`);
        }
    }
    const incompleteDeclaredMilestones = options.milestoneStates.filter((state) => {
        const slug = node_path_1.default.basename(node_path_1.default.dirname(state.overviewPath));
        return declared.has(slug) && (state.reconciliationPath === null ||
            state.reconciliationStatus !== 'completed' ||
            state.incompleteTaskSummaryPaths.length > 0);
    });
    if (options.phaseStatus === 'completed' && (options.blockingIssues.length > 0 || incompleteDeclaredMilestones.length > 0)) {
        options.blockingIssues.push(`Phase overview '${options.phaseOverviewPath}' has status 'completed' while declared child milestone evidence is missing or incomplete. Recommended command: day-shift phase review --phase-overview ${options.phaseOverviewPath}.`);
    }
}
function readSummaryArtifactState(repositoryRoot, summaryPath) {
    const absolutePath = node_path_1.default.join(repositoryRoot, summaryPath);
    if (!node_fs_1.default.existsSync(absolutePath)) {
        return null;
    }
    const text = node_fs_1.default.readFileSync(absolutePath, 'utf8');
    const document = (0, lifecycle_evidence_1.parseMarkdownDocument)(summaryPath, text);
    const lifecycle = (0, task_lifecycle_1.projectImplementationSummaryLifecycle)(text).value;
    return {
        path: summaryPath,
        implementationStatus: lifecycle.currentAttempt?.implementationStatus
            ?? lifecycle.legacyImplementationStatus,
        reviewDisposition: lifecycle.currentAttempt?.reviewDisposition
            ?? lifecycle.legacyReviewDisposition,
        artifactStatus: (0, planning_document_utils_1.readTopLevelField)(document.frontMatterLines, 'status')?.trim() ?? null,
        substantiveEvidence: hasSubstantiveSummaryEvidence(document),
    };
}
function hasSubstantiveSummaryEvidence(document) {
    const changedPaths = document.sections.get('Changed Paths');
    const validation = document.sections.get('Validation Performed');
    const summary = document.sections.get('Summary');
    return !isPlaceholderContent(changedPaths) || !isPlaceholderContent(validation) || !isPlaceholderContent(summary);
}
function readMilestoneArtifactState(repositoryRoot, overviewPath) {
    const overviewDocument = (0, lifecycle_evidence_1.readRequiredDocument)(node_path_1.default.join(repositoryRoot, overviewPath), overviewPath, 'milestone_overview');
    const reconciliationPath = (0, planning_document_utils_1.toRepositoryLikePath)(node_path_1.default.join(node_path_1.default.dirname(overviewPath), 'reconciliation.md'));
    const reconciliationAbsolute = node_path_1.default.join(repositoryRoot, reconciliationPath);
    const completedTaskSummaryPaths = [];
    const incompleteTaskSummaryPaths = [];
    for (const summaryPath of (0, lifecycle_evidence_1.collectTaskSummaryPaths)(repositoryRoot, overviewPath)) {
        const summaryState = readSummaryArtifactState(repositoryRoot, summaryPath);
        if (summaryState?.implementationStatus === 'completed'
            && (summaryState.reviewDisposition === 'accepted'
                || summaryState.reviewDisposition === 'accepted_with_follow_up')) {
            completedTaskSummaryPaths.push(summaryPath);
        }
        else {
            incompleteTaskSummaryPaths.push(summaryPath);
        }
    }
    return {
        overviewPath,
        status: (0, planning_document_utils_1.readTopLevelField)(overviewDocument.frontMatterLines, 'status')?.trim() ?? null,
        reconciliationPath: node_fs_1.default.existsSync(reconciliationAbsolute) ? reconciliationPath : null,
        reconciliationStatus: node_fs_1.default.existsSync(reconciliationAbsolute)
            ? ((0, planning_document_utils_1.readTopLevelField)((0, lifecycle_evidence_1.parseMarkdownDocument)(reconciliationPath, node_fs_1.default.readFileSync(reconciliationAbsolute, 'utf8')).frontMatterLines, 'reconciliation_status')?.trim() ?? null)
            : null,
        completedTaskSummaryPaths,
        incompleteTaskSummaryPaths,
    };
}
function isPlaceholderContent(text) {
    if (text === undefined) {
        return true;
    }
    if (text.trim() === '') {
        return true;
    }
    if (contracts_1.PLACEHOLDER_PATTERN.test(text)) {
        return true;
    }
    return contracts_1.PLACEHOLDER_EXACT_VALUES.has(text.trim());
}
function documentHasPlaceholderContent(text) {
    return contracts_1.RECONCILIATION_SECTION_NAMES.some((sectionName) => {
        const document = (0, lifecycle_evidence_1.parseMarkdownDocument)('reconciliation.md', text);
        return isPlaceholderContent(document.sections.get(sectionName));
    });
}
function appendIssueLines(lines, issues) {
    if (issues.length === 0) {
        lines.push('- (none)');
        return;
    }
    for (const issue of issues) {
        lines.push(`- ${issue}`);
    }
}
