"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.reviewMilestonePlanning = reviewMilestonePlanning;
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const authoring_policy_1 = require("../authoring-policy");
const implementation_summary_reconciliation_1 = require("../implementation-summary-reconciliation");
const mode_balance_1 = require("../mode-balance");
const planning_document_utils_1 = require("../planning-document-utils");
const planning_heuristics_1 = require("../planning-heuristics");
const runtime_acceptance_1 = require("../runtime-acceptance");
const scaffold_application_1 = require("../scaffold-application");
const child_drift_1 = require("./child-drift");
const contracts_1 = require("./contracts");
const documentation_loop_1 = require("./documentation-loop");
const lifecycle_evidence_1 = require("./lifecycle-evidence");
const rendering_1 = require("./rendering");
function reviewMilestonePlanning(repositoryRoot, options) {
    const milestoneOverviewPath = (0, lifecycle_evidence_1.resolveRepositoryPath)(repositoryRoot, options.milestoneOverviewPath, 'milestone-overview');
    const milestoneDocument = (0, lifecycle_evidence_1.readRequiredDocument)(milestoneOverviewPath.absolute, milestoneOverviewPath.relative, 'milestone_overview');
    const milestoneStatus = (0, planning_document_utils_1.readTopLevelField)(milestoneDocument.frontMatterLines, 'status')?.trim() ?? null;
    const reconciliationPath = (0, planning_document_utils_1.toRepositoryLikePath)(node_path_1.default.join(node_path_1.default.dirname(milestoneOverviewPath.relative), 'reconciliation.md'));
    const reconciliationAbsolute = node_path_1.default.join(repositoryRoot, reconciliationPath);
    const reconciliationExists = node_fs_1.default.existsSync(reconciliationAbsolute);
    const taskSummaryPaths = (0, lifecycle_evidence_1.collectTaskSummaryPaths)(repositoryRoot, milestoneOverviewPath.relative);
    const declaredTaskSlugs = (0, child_drift_1.parseDeclaredChildSlugs)(milestoneDocument.sections.get('Tasks'));
    const observedTaskSlugs = (0, lifecycle_evidence_1.collectTaskDirectorySlugs)(repositoryRoot, milestoneOverviewPath.relative);
    const completedTaskSummaryPaths = [];
    const incompleteTaskSummaryPaths = [];
    for (const summaryPath of taskSummaryPaths) {
        const summaryState = (0, child_drift_1.readSummaryArtifactState)(repositoryRoot, summaryPath);
        if (summaryState?.implementationStatus === 'completed') {
            completedTaskSummaryPaths.push(summaryPath);
        }
        else {
            incompleteTaskSummaryPaths.push(summaryPath);
        }
    }
    const reviewMode = completedTaskSummaryPaths.length > 0 || reconciliationExists ? 'evidence' : 'readiness';
    const blockingIssues = [];
    const warnings = [];
    const metadataHygieneFollowUps = [];
    const parentRuntimeAcceptance = (0, runtime_acceptance_1.inspectRuntimeAcceptance)({
        artifactPath: milestoneOverviewPath.relative,
        artifactKind: 'milestone',
        frontMatterLines: milestoneDocument.frontMatterLines,
        markdownText: milestoneDocument.rawText,
        requireExplicitForExecutableEvidence: false,
    });
    const runtimeCriterionOwnership = parentRuntimeAcceptance.metadata?.required === true
        ? (0, scaffold_application_1.inspectRuntimeCriterionOwnership)({
            milestoneMarkdownText: milestoneDocument.rawText,
            declaredChildSlugs: declaredTaskSlugs,
            parentCriterionIds: parentRuntimeAcceptance.metadata.criterionIds,
        })
        : null;
    blockingIssues.push(...parentRuntimeAcceptance.issues.map((issue) => `Parent runtime acceptance: ${issue}`), ...(runtimeCriterionOwnership?.issues ?? []));
    const heuristicFindings = (0, planning_heuristics_1.collectPlanningHeuristicFindings)({
        artifactPath: milestoneOverviewPath.relative,
        artifactFamily: 'milestone_overview',
        frontMatterLines: milestoneDocument.frontMatterLines,
        sections: milestoneDocument.sections,
        enabledRuleFamilies: ['planning-language', 'decomposition', 'stale-spec-risk'],
        currentLifecycleEvidence: (0, lifecycle_evidence_1.buildMilestoneCurrentLifecycleEvidence)({
            reconciliationPath: reconciliationExists ? reconciliationPath : null,
            completedTaskSummaryPaths,
            incompleteTaskSummaryPaths,
        }),
    });
    warnings.push(...heuristicFindings.map((finding) => finding.message));
    warnings.push(...(0, authoring_policy_1.formatPlanningAuthoringIssues)((0, authoring_policy_1.auditPlanningArtifactAuthoring)({
        artifactPath: milestoneOverviewPath.relative,
        artifactType: 'milestone_overview',
        markdownText: milestoneDocument.rawText,
        allowLegacyManualAlias: true,
        allowMissingProvenance: true,
    })));
    warnings.push(...(0, authoring_policy_1.formatParentDecompositionIssues)((0, authoring_policy_1.auditParentDecomposition)({
        artifactPath: milestoneOverviewPath.relative,
        markdownText: milestoneDocument.rawText,
        childKind: 'task',
        declaredChildSlugs: declaredTaskSlugs,
    })));
    const modeBalance = (0, mode_balance_1.evaluateMilestoneModeBalance)(repositoryRoot, {
        milestoneOverviewPath: milestoneOverviewPath.relative,
        requireBreakoutForCloseout: reviewMode === 'evidence'
            && declaredTaskSlugs.length > 0
            && completedTaskSummaryPaths.length === declaredTaskSlugs.length,
    });
    if (modeBalance.optedIn) {
        blockingIssues.push(...modeBalance.blockingIssues);
    }
    else {
        blockingIssues.push(...(0, lifecycle_evidence_1.collectContractToRuntimeHandoffIssues)({
            repositoryRoot,
            milestoneOverviewPath: milestoneOverviewPath.relative,
            declaredTaskSlugs,
        }), ...(0, documentation_loop_1.collectDocumentationLoopIssues)({
            repositoryRoot,
            milestoneOverviewPath: milestoneOverviewPath.relative,
            milestoneDocument,
            declaredTaskSlugs,
        }));
    }
    if (reviewMode === 'readiness') {
        (0, lifecycle_evidence_1.collectReadinessSectionIssues)(milestoneDocument, milestoneOverviewPath.relative, contracts_1.MILESTONE_REQUIRED_SECTIONS, blockingIssues);
        (0, child_drift_1.collectMilestoneChildDriftIssues)({
            milestoneOverviewPath: milestoneOverviewPath.relative,
            milestoneStatus,
            declaredTaskSlugs,
            observedTaskSlugs,
            taskSummaryPaths,
            completedTaskSummaryPaths,
            incompleteTaskSummaryPaths,
            blockingIssues,
            warnings,
        });
        return {
            reviewMode,
            milestoneOverviewPath: milestoneOverviewPath.relative,
            reconciliationPath: reconciliationExists ? reconciliationPath : null,
            completedTaskSummaryPaths,
            incompleteTaskSummaryPaths,
            blockingIssues,
            warnings,
            metadataHygieneFollowUps,
            closureEvidenceStatus: null,
            runtimeCriterionOwnership,
            modeBalance,
            recoveryGuidance: (0, rendering_1.buildPlanningRecoveryGuidance)({
                repositoryRoot,
                artifactPath: milestoneOverviewPath.relative,
                reviewKind: 'milestone',
                blockingIssues,
                warnings,
                metadataHygieneFollowUps,
                modeBalanceEvaluations: [modeBalance],
            }),
            findings: (0, rendering_1.buildPlanningReviewFindings)({
                artifactPath: milestoneOverviewPath.relative,
                reviewKind: 'milestone',
                blockingIssues,
                warnings,
                metadataHygieneFollowUps,
            }).concat(heuristicFindings),
        };
    }
    if (completedTaskSummaryPaths.length === 0) {
        blockingIssues.push('No completed task implementation summaries were found for this milestone.');
    }
    (0, child_drift_1.collectMilestoneChildDriftIssues)({
        milestoneOverviewPath: milestoneOverviewPath.relative,
        milestoneStatus,
        declaredTaskSlugs,
        observedTaskSlugs,
        taskSummaryPaths,
        completedTaskSummaryPaths,
        incompleteTaskSummaryPaths,
        blockingIssues,
        warnings,
    });
    if (incompleteTaskSummaryPaths.length > 0) {
        warnings.push(...incompleteTaskSummaryPaths.map((summaryPath) => {
            return `Task summary '${summaryPath}' is not complete yet.`;
        }));
    }
    let closureEvidenceStatus = null;
    if (!reconciliationExists) {
        warnings.push(`Milestone reconciliation '${reconciliationPath}' is missing, so milestone review coverage is incomplete.`);
    }
    else {
        const reconciliationResult = (0, implementation_summary_reconciliation_1.reviewReconciliation)(repositoryRoot, {
            milestoneOverviewPath: milestoneOverviewPath.relative,
        });
        closureEvidenceStatus = reconciliationResult.closureEvidenceStatus;
        blockingIssues.push(...reconciliationResult.evidenceGaps, ...reconciliationResult.alignmentIssues);
        warnings.push(...reconciliationResult.placeholderResidue, ...reconciliationResult.reviewConcerns);
        if (reconciliationResult.reconciliationStatus === 'completed' &&
            reconciliationResult.artifactStatus === 'completed' &&
            milestoneStatus !== 'completed') {
            metadataHygieneFollowUps.push(`Shared status for milestone overview family 'milestone_overview' should be 'completed', found '${milestoneStatus ?? '(missing)'}' at '${milestoneOverviewPath.relative}' after completed reconciliation evidence. Recommended command: day-shift milestone update --milestone-overview ${milestoneOverviewPath.relative} --field status=completed.`);
        }
    }
    return {
        reviewMode,
        milestoneOverviewPath: milestoneOverviewPath.relative,
        reconciliationPath: reconciliationExists ? reconciliationPath : null,
        completedTaskSummaryPaths,
        incompleteTaskSummaryPaths,
        blockingIssues,
        warnings,
        metadataHygieneFollowUps,
        closureEvidenceStatus,
        runtimeCriterionOwnership,
        modeBalance,
        recoveryGuidance: (0, rendering_1.buildPlanningRecoveryGuidance)({
            repositoryRoot,
            artifactPath: milestoneOverviewPath.relative,
            reviewKind: 'milestone',
            blockingIssues,
            warnings,
            metadataHygieneFollowUps,
            modeBalanceEvaluations: [modeBalance],
        }),
        findings: (0, rendering_1.buildPlanningReviewFindings)({
            artifactPath: milestoneOverviewPath.relative,
            reviewKind: 'milestone',
            blockingIssues,
            warnings,
            metadataHygieneFollowUps,
        }).concat(heuristicFindings),
    };
}
