"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.planningAuthoringSectionPolicies = planningAuthoringSectionPolicies;
exports.auditPlanningArtifactAuthoring = auditPlanningArtifactAuthoring;
exports.auditParentDecomposition = auditParentDecomposition;
exports.declaredPlanningChildSlugs = declaredPlanningChildSlugs;
exports.formatPlanningAuthoringIssues = formatPlanningAuthoringIssues;
exports.formatParentDecompositionIssues = formatParentDecompositionIssues;
const verb_policy_1 = require("./verb-policy");
const workflow_provenance_1 = require("./workflow-provenance");
const planning_document_utils_1 = require("./planning-document-utils");
const SECTION_POLICIES = {
    slice_overview: [
        { sectionName: "Purpose", sectionType: "purpose", intentCategory: "prose" },
        { sectionName: "Desired Outcome", sectionType: "general", intentCategory: "runtime-behavior" },
        { sectionName: "Scope", sectionType: "scope", intentCategory: "prose" },
        { sectionName: "Phases", sectionType: "milestones", intentCategory: "runtime-behavior" }
    ],
    phase_overview: [
        { sectionName: "Purpose", sectionType: "purpose", intentCategory: "prose" },
        { sectionName: "Scope", sectionType: "scope", intentCategory: "prose" },
        { sectionName: "Milestones", sectionType: "milestones", intentCategory: "runtime-behavior" },
        { sectionName: "Acceptance Criteria", sectionType: "general", intentCategory: "runtime-behavior" }
    ],
    milestone_overview: [
        { sectionName: "Purpose", sectionType: "purpose", intentCategory: "prose" },
        { sectionName: "Scope", sectionType: "scope", intentCategory: "prose" },
        { sectionName: "Tasks", sectionType: "tasks", intentCategory: "runtime-behavior" },
        { sectionName: "Acceptance Criteria", sectionType: "general", intentCategory: "runtime-behavior" }
    ],
    task_definition: [
        { sectionName: "Objective", sectionType: "task-body", intentCategory: "runtime-behavior" },
        { sectionName: "Current Behavior", sectionType: "task-body", intentCategory: "prose" },
        { sectionName: "Desired Behavior", sectionType: "task-body", intentCategory: "runtime-behavior" },
        { sectionName: "Acceptance Criteria", sectionType: "task-body", intentCategory: "runtime-behavior" },
        { sectionName: "Constraints", sectionType: "task-body", intentCategory: "prose" },
        { sectionName: "Lifecycle / Closure Expectations", sectionType: "task-body", intentCategory: "evidence" }
    ],
    implementation_summary: [
        { sectionName: "Summary", sectionType: "general", intentCategory: "evidence" },
        { sectionName: "Acceptance Criteria Results", sectionType: "general", intentCategory: "evidence" }
    ],
    reconciliation: [
        { sectionName: "Milestone Intent", sectionType: "general", intentCategory: "review" },
        { sectionName: "Acceptance Criteria Review", sectionType: "general", intentCategory: "review" }
    ]
};
const DECOMPOSITION_BOUNDARY_TERMS = [
    "implementation",
    "dependency",
    "validation",
    "rollback",
    "ownership"
];
function planningAuthoringSectionPolicies(artifactType) {
    return SECTION_POLICIES[artifactType];
}
function auditPlanningArtifactAuthoring(options) {
    const issues = [];
    const verbViolations = (0, verb_policy_1.auditDisallowedDefineUsage)({
        markdownText: options.markdownText,
        sectionPolicies: planningAuthoringSectionPolicies(options.artifactType)
    });
    issues.push(...verbViolations.map((violation) => planningVerbIssue(options, violation)));
    const frontMatter = readTopLevelFrontMatter(options.markdownText);
    const provenanceIssues = (0, workflow_provenance_1.inspectPlanningWorkflowProvenance)({
        artifactType: options.artifactType,
        workflowProvenance: frontMatter.get("workflow_provenance") ?? "",
        workflowCliCommand: frontMatter.get("workflow_cli_command") ?? "",
        workflowManualException: frontMatter.get("workflow_manual_exception") ?? "",
        allowLegacyManualAlias: options.allowLegacyManualAlias === true
    });
    issues.push(...provenanceIssues
        .filter((issue) => !(options.allowMissingProvenance === true && issue.code === "PLANNING_WORKFLOW_PROVENANCE_MISSING"))
        .map((issue) => planningProvenanceIssue(options, issue)));
    return issues;
}
function auditParentDecomposition(options) {
    const label = `${options.childKind}`;
    const escapedLabel = escapeRegExp(label);
    const countMatch = options.markdownText.match(new RegExp(`Target\\s+${escapedLabel}\\s+count:\\s*(\\d+)`, "i"));
    const rationaleMatch = options.markdownText.match(/Decomposition rationale:\s*([^\n]+)/i);
    const issues = [];
    if (countMatch === null) {
        issues.push({
            code: "PLANNING_DECOMPOSITION_TARGET_COUNT_MISSING",
            artifactPath: options.artifactPath,
            childKind: options.childKind,
            reason: `Parent must state 'Target ${label} count: N' before ${label} scaffolding.`
        });
    }
    if (rationaleMatch === null || isPlaceholderRationale(rationaleMatch[1])) {
        issues.push({
            code: "PLANNING_DECOMPOSITION_RATIONALE_MISSING",
            artifactPath: options.artifactPath,
            childKind: options.childKind,
            reason: `Parent must state an authored decomposition rationale before ${label} scaffolding.`
        });
    }
    if (countMatch !== null) {
        const targetCount = Number.parseInt(countMatch[1], 10);
        if (targetCount !== options.declaredChildSlugs.length) {
            issues.push({
                code: "PLANNING_DECOMPOSITION_COUNT_CONTRADICTION",
                artifactPath: options.artifactPath,
                childKind: options.childKind,
                reason: `Target ${label} count ${targetCount} contradicts ${options.declaredChildSlugs.length} declared ${label} slug${options.declaredChildSlugs.length === 1 ? "" : "s"}.`
            });
        }
    }
    if (rationaleMatch !== null && !isPlaceholderRationale(rationaleMatch[1])) {
        const rationale = rationaleMatch[1].trim().toLowerCase();
        if (!DECOMPOSITION_BOUNDARY_TERMS.some((term) => rationale.includes(term))) {
            issues.push({
                code: "PLANNING_DECOMPOSITION_RATIONALE_PATTERN_DERIVED",
                artifactPath: options.artifactPath,
                childKind: options.childKind,
                reason: "Decomposition rationale must name a concrete implementation, dependency, validation, rollback, or ownership boundary; familiar counts, names, numbering, and ordering are not evidence."
            });
        }
    }
    return issues;
}
function declaredPlanningChildSlugs(markdownText, sectionName) {
    const lines = markdownText.split(/\r?\n/);
    const sectionIndex = lines.findIndex((line) => line.trim() === `## ${sectionName}`);
    if (sectionIndex === -1) {
        return [];
    }
    const slugs = [];
    for (let index = sectionIndex + 1; index < lines.length; index += 1) {
        const line = lines[index].trim();
        if (line.startsWith("## ")) {
            break;
        }
        const declaration = (0, planning_document_utils_1.parseDeclaredChildSlugBullet)(line);
        if (declaration !== null) {
            slugs.push(declaration.slug);
        }
    }
    return slugs;
}
function formatPlanningAuthoringIssues(issues) {
    return issues.map((issue) => {
        const replacement = issue.suggestedVerb === "" ? "" : ` Suggested replacement: ${issue.suggestedVerb}.`;
        return `${issue.artifactPath} [${issue.sectionName}] ${issue.reason}${replacement}`;
    });
}
function formatParentDecompositionIssues(issues) {
    return issues.map((issue) => `${issue.artifactPath}: ${issue.reason}`);
}
function planningVerbIssue(options, violation) {
    return {
        code: "PLANNING_AUTHORING_VERB_INVALID",
        artifactPath: options.artifactPath,
        artifactType: options.artifactType,
        sectionName: violation.sectionName,
        reason: `${violation.reason} Sentence: ${violation.sentence}`,
        suggestedVerb: violation.suggestedVerb
    };
}
function planningProvenanceIssue(options, issue) {
    return {
        code: issue.code,
        artifactPath: options.artifactPath,
        artifactType: options.artifactType,
        sectionName: "front matter",
        reason: issue.message,
        suggestedVerb: ""
    };
}
function readTopLevelFrontMatter(markdownText) {
    const fields = new Map();
    const lines = markdownText.split(/\r?\n/);
    if (lines[0] !== "---") {
        return fields;
    }
    for (let index = 1; index < lines.length; index += 1) {
        if (lines[index] === "---") {
            break;
        }
        const match = lines[index].match(/^([A-Za-z0-9_]+):\s*(.*)$/);
        if (match !== null) {
            fields.set(match[1], parseScalarValue(match[2]));
        }
    }
    return fields;
}
function parseScalarValue(value) {
    const trimmed = value.trim();
    if (trimmed.length >= 2 && ((trimmed.startsWith('"') && trimmed.endsWith('"')) || (trimmed.startsWith("'") && trimmed.endsWith("'")))) {
        return trimmed.slice(1, -1);
    }
    return trimmed;
}
function isPlaceholderRationale(value) {
    const normalized = value.trim().toLowerCase();
    return normalized === "" || normalized === "pending" || normalized.includes("to be planned") || normalized.includes("replace with");
}
function escapeRegExp(value) {
    return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
