"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.isCanonicalGovernedSliceRoot = isCanonicalGovernedSliceRoot;
exports.parseMarkdownDocument = parseMarkdownDocument;
exports.readDeclaredChildSlugsFromDocument = readDeclaredChildSlugsFromDocument;
exports.childSlugFromHref = childSlugFromHref;
exports.pairedImplementationSummaryPath = pairedImplementationSummaryPath;
exports.pairedTaskDefinitionPath = pairedTaskDefinitionPath;
exports.pairedReconciliationPath = pairedReconciliationPath;
exports.isCompletedImplementationSummary = isCompletedImplementationSummary;
exports.isClosedTaskDefinition = isClosedTaskDefinition;
exports.isCompletedReconciliation = isCompletedReconciliation;
exports.hasAuthoredSectionPlaceholderContent = hasAuthoredSectionPlaceholderContent;
exports.addGap = addGap;
exports.phaseScaffoldRefinementFindings = phaseScaffoldRefinementFindings;
exports.appendLines = appendLines;
exports.isRecognizedArtifactFilename = isRecognizedArtifactFilename;
exports.isPlanningArtifactType = isPlanningArtifactType;
exports.assertNever = assertNever;
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 authoring_policy_1 = require("../authoring-policy");
const planning_artifact_document_1 = require("../planning-artifact-document");
const planning_document_utils_1 = require("../planning-document-utils");
const semantic_placeholder_1 = require("../semantic-placeholder");
const structured_task_plan_1 = require("../structured-task-plan");
const task_lifecycle_1 = require("../task-lifecycle");
const scaffold_target_path_policy_1 = require("../scaffold-target-path-policy");
function isCanonicalGovernedSliceRoot(record) {
    if ((0, planning_document_utils_1.readTopLevelField)(record.document.frontMatterLines, "workflow_level") !== "governed") {
        return false;
    }
    return /^\.day-shift\/planning\/governed\/[^/]+\/slice-overview\.md$/.test(record.path);
}
function parseMarkdownDocument(filePath, rawText) {
    const parsed = (0, planning_artifact_document_1.parsePlanningArtifactDocument)(rawText);
    if (!parsed.hasFrontMatter) {
        const malformed = parsed.diagnostics.some((diagnostic) => diagnostic.code === "unterminated-front-matter");
        if (malformed) {
            throw (0, errors_1.createInvalidConfigError)(`Planning artifact '${filePath}' has malformed YAML front matter.`, [
                "Expected a closing front-matter fence."
            ]);
        }
        throw (0, errors_1.createInvalidConfigError)(`Planning artifact '${filePath}' is missing YAML front matter.`, [
            "Expected the document to start with a front-matter fence."
        ]);
    }
    const sections = new Map();
    for (const section of parsed.sections) {
        sections.set(section.heading, section.contentText.trim());
    }
    return {
        frontMatterLines: parsed.frontMatterLines,
        sections,
        rawText
    };
}
function readDeclaredChildSlugsFromDocument(document, sectionName) {
    const sectionText = document.sections.get(sectionName);
    if (sectionText === undefined) {
        return [];
    }
    if (sectionName === 'Task Plan') {
        const taskPlan = (0, structured_task_plan_1.parseStructuredTaskPlan)(document.rawText);
        const taskRoots = taskPlan.declarations.flatMap((declaration) => {
            if (declaration.mappingStatus === 'valid' && declaration.orderedTaskRootName !== null) {
                return [declaration.orderedTaskRootName];
            }
            if (declaration.mappingStatus === 'invalid')
                return [];
            const fallback = declaration.referenceKind === 'markdown-link'
                ? childSlugFromHref(declaration.referenceValue, declaration.referenceLabel)
                : declaration.referenceLabel;
            return fallback === '' ? [] : [fallback];
        });
        return [...new Set(taskRoots)];
    }
    const slugs = [];
    for (const line of sectionText.split(/\r?\n/u)) {
        const declaration = (0, planning_document_utils_1.parseDeclaredChildSlugBullet)(line);
        if (declaration === null) {
            continue;
        }
        const slug = declaration.href === undefined
            ? declaration.slug
            : childSlugFromHref(declaration.href, declaration.slug);
        if (slug !== "" && !slugs.includes(slug)) {
            slugs.push(slug);
        }
    }
    return slugs;
}
function childSlugFromHref(href, fallback) {
    const hrefPath = href.split("#", 1)[0].replace(/\\/gu, "/").replace(/\/+$/u, "");
    const fileName = node_path_1.default.posix.basename(hrefPath);
    if (fileName === "phase-overview.md"
        || fileName === "milestone-overview.md"
        || fileName === "task-definition.md") {
        return node_path_1.default.posix.basename(node_path_1.default.posix.dirname(hrefPath));
    }
    return fallback;
}
function pairedImplementationSummaryPath(taskDefinitionPath) {
    return (0, planning_document_utils_1.toRepositoryLikePath)(node_path_1.default.posix.join(node_path_1.default.posix.dirname(taskDefinitionPath), "implementation-summary.md"));
}
function pairedTaskDefinitionPath(implementationSummaryPath) {
    return (0, planning_document_utils_1.toRepositoryLikePath)(node_path_1.default.posix.join(node_path_1.default.posix.dirname(implementationSummaryPath), "task-definition.md"));
}
function pairedReconciliationPath(milestoneOverviewPath) {
    return (0, planning_document_utils_1.toRepositoryLikePath)(node_path_1.default.posix.join(node_path_1.default.posix.dirname(milestoneOverviewPath), "reconciliation.md"));
}
function isCompletedImplementationSummary(record) {
    if (record.artifactType !== "implementation_summary"
        || hasAuthoredSectionPlaceholderContent(record.document)) {
        return false;
    }
    const projection = (0, task_lifecycle_1.projectImplementationSummaryLifecycle)(record.document.rawText).value;
    const implementationStatus = projection.currentAttempt?.implementationStatus
        ?? projection.legacyImplementationStatus;
    const disposition = projection.currentAttempt?.reviewDisposition
        ?? projection.legacyReviewDisposition;
    return implementationStatus === "completed"
        && (disposition === "accepted" || disposition === "accepted_with_follow_up");
}
function isClosedTaskDefinition(record) {
    return record.status === "completed" || record.status === "cancelled";
}
function isCompletedReconciliation(record) {
    return record.artifactType === "reconciliation"
        && record.reconciliationStatus === "completed"
        && record.status === "completed"
        && !hasAuthoredSectionPlaceholderContent(record.document);
}
function hasAuthoredSectionPlaceholderContent(document) {
    return [...document.sections.values()].some(semantic_placeholder_1.hasSemanticPlaceholderContent);
}
function addGap(gapMap, gap) {
    const details = gap.evidence?.details;
    const key = [
        gap.code,
        gap.path,
        details?.childSlug ?? "",
        details?.missingEvidenceKind ?? "",
        gap.message
    ].join("\u0000");
    if (!gapMap.has(key)) {
        gapMap.set(key, gap);
    }
}
function phaseScaffoldRefinementFindings(repositoryRoot, record) {
    if (record.artifactType !== "phase_overview")
        return [];
    const runtimeEvidencePathPolicy = (0, scaffold_target_path_policy_1.readPlanningScaffoldTargetPathPolicy)(repositoryRoot);
    const declaredMilestones = readDeclaredChildSlugsFromDocument(record.document, "Milestones");
    const missingMilestones = declaredMilestones.filter((childSlug) => {
        const childDirectoryPath = (0, planning_document_utils_1.toRepositoryLikePath)(node_path_1.default.posix.join(node_path_1.default.posix.dirname(record.path), "milestones", childSlug));
        const childDirectory = (0, paths_1.resolveRepositoryRelativePath)(repositoryRoot, (0, paths_1.parseRepositoryRelativePath)(childDirectoryPath));
        if (!node_fs_1.default.existsSync(childDirectory))
            return true;
        const resolution = (0, paths_1.resolvePlanningOverviewPath)(repositoryRoot, {
            layer: "milestone",
            directoryPath: childDirectoryPath
        });
        return resolution.status !== "conflict" && resolution.selected === null;
    });
    return missingMilestones.flatMap((childSlug) => (0, authoring_policy_1.projectPlanningScaffoldRefinementFindings)(record.path, (0, authoring_policy_1.inspectChildScaffoldEvidence)({
        markdownText: record.document.rawText,
        childKind: "milestone",
        childSlug,
        declaredChildSlugs: declaredMilestones,
        runtimeEvidencePathPolicy
    })));
}
function appendLines(lines, entries) {
    if (entries.length === 0) {
        lines.push("- (none)");
        return;
    }
    for (const entry of entries) {
        lines.push(`- ${entry}`);
    }
}
function isRecognizedArtifactFilename(relativePath) {
    return relativePath.endsWith("/overview.md")
        || relativePath.endsWith("/slice-overview.md")
        || relativePath.endsWith("/phase-overview.md")
        || relativePath.endsWith("/milestone-overview.md")
        || relativePath.endsWith("/task-definition.md")
        || relativePath.endsWith("/implementation-summary.md")
        || relativePath.endsWith("/reconciliation.md")
        || relativePath === "overview.md"
        || relativePath === "slice-overview.md"
        || relativePath === "phase-overview.md"
        || relativePath === "milestone-overview.md"
        || relativePath === "task-definition.md"
        || relativePath === "implementation-summary.md"
        || relativePath === "reconciliation.md";
}
function isPlanningArtifactType(value) {
    return value === "work_overview"
        || value === "slice_overview"
        || value === "phase_overview"
        || value === "milestone_overview"
        || value === "task_definition"
        || value === "implementation_summary"
        || value === "reconciliation";
}
function assertNever(value) {
    throw new Error(`Unexpected value: ${String(value)}`);
}
