"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.reviewTaskPlanning = reviewTaskPlanning;
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const artifact_policy_projection_1 = require("../artifact-policy-projection");
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 task_readiness_review_1 = require("../task-readiness-review");
const child_drift_1 = require("./child-drift");
const lifecycle_evidence_1 = require("./lifecycle-evidence");
const rendering_1 = require("./rendering");
function reviewTaskPlanning(repositoryRoot, options) {
    const taskDefinitionPath = (0, lifecycle_evidence_1.resolveRepositoryPath)(repositoryRoot, options.taskDefinitionPath, 'task-definition');
    const taskDocument = (0, lifecycle_evidence_1.readRequiredDocument)(taskDefinitionPath.absolute, taskDefinitionPath.relative, 'task_definition');
    const taskStatus = (0, planning_document_utils_1.readTopLevelField)(taskDocument.frontMatterLines, 'status')?.trim() ?? null;
    const taskPolicy = (0, artifact_policy_projection_1.projectArtifactPolicy)(taskDocument.rawText);
    const taskReadiness = taskPolicy.lifecycle.readiness;
    const readinessResult = (0, task_readiness_review_1.inspectTaskReadiness)(repositoryRoot, {
        taskDefinitionPath: taskDefinitionPath.relative,
    });
    const implementationSummaryPath = (0, planning_document_utils_1.toRepositoryLikePath)(node_path_1.default.join(node_path_1.default.dirname(taskDefinitionPath.relative), 'implementation-summary.md'));
    const taskReconciliationPath = (0, planning_document_utils_1.toRepositoryLikePath)(node_path_1.default.join(node_path_1.default.dirname(taskDefinitionPath.relative), 'reconciliation.md'));
    const taskReconciliationAbsolute = node_path_1.default.join(repositoryRoot, taskReconciliationPath);
    const taskReconciliationExists = node_fs_1.default.existsSync(taskReconciliationAbsolute);
    const summaryState = (0, child_drift_1.readSummaryArtifactState)(repositoryRoot, implementationSummaryPath);
    const reviewMode = summaryState !== null && summaryState.substantiveEvidence
        ? 'evidence'
        : taskReconciliationExists
            ? 'evidence'
            : 'readiness';
    const blockingIssues = [];
    const warnings = [];
    const metadataHygieneFollowUps = [];
    const heuristicFindings = (0, planning_heuristics_1.collectPlanningHeuristicFindings)({
        artifactPath: taskDefinitionPath.relative,
        artifactFamily: 'task_definition',
        frontMatterLines: taskDocument.frontMatterLines,
        sections: taskDocument.sections,
        enabledRuleFamilies: ['planning-language', 'decomposition', 'target-path-hygiene', 'dependency-hygiene', 'stale-spec-risk', 'lightweight-promotion-pressure'],
        currentLifecycleEvidence: (0, lifecycle_evidence_1.buildTaskCurrentLifecycleEvidence)({
            taskDefinitionPath: taskDefinitionPath.relative,
            taskReadiness,
            summaryState,
            reviewMode,
        }),
    });
    warnings.push(...heuristicFindings.map((finding) => finding.message));
    warnings.push(...(0, authoring_policy_1.formatPlanningAuthoringIssues)((0, authoring_policy_1.auditPlanningArtifactAuthoring)({
        artifactPath: taskDefinitionPath.relative,
        artifactType: 'task_definition',
        markdownText: taskDocument.rawText,
        allowLegacyManualAlias: true,
        allowMissingProvenance: true,
    })));
    if (reviewMode === 'readiness') {
        blockingIssues.push(...readinessResult.missingEvidence, ...readinessResult.dependencyBlockers, ...readinessResult.sequencingIssues);
        warnings.push(...readinessResult.handoffBlockers, ...readinessResult.reviewBoundaryWarnings);
        if (readinessResult.readinessStatus === 'ready to implement' && taskReadiness !== 'ready_to_implement') {
            metadataHygieneFollowUps.push(`Task readiness review is sufficient, but readiness authorization is still '${taskReadiness ?? '(missing)'}'. Run day-shift task readiness-authorize with the revision-bound readiness review result; review output alone does not mutate lifecycle state.`);
        }
        const recoveryGuidance = (0, rendering_1.buildPlanningRecoveryGuidance)({
            repositoryRoot,
            artifactPath: taskDefinitionPath.relative,
            reviewKind: 'task',
            blockingIssues,
            warnings,
            metadataHygieneFollowUps,
        });
        const findings = (0, rendering_1.buildPlanningReviewFindings)({
            artifactPath: taskDefinitionPath.relative,
            reviewKind: 'task',
            blockingIssues,
            warnings,
            metadataHygieneFollowUps,
        }).concat(heuristicFindings);
        return {
            reviewMode,
            taskDefinitionPath: taskDefinitionPath.relative,
            implementationSummaryPath,
            taskReconciliationPath: taskReconciliationExists ? taskReconciliationPath : null,
            milestoneReconciliationPath: readinessResult.milestoneReconciliationPath,
            workflowTopology: readinessResult.workflowTopology,
            reviewBoundaryKind: readinessResult.reviewBoundaryKind,
            reconciliationArtifactKind: readinessResult.reconciliationArtifactKind,
            reconciliationRequired: readinessResult.reconciliationRequired,
            blockingIssues,
            warnings,
            metadataHygieneFollowUps,
            readinessStatus: readinessResult.readinessStatus,
            closeoutEvidenceStatus: null,
            modeBalance: null,
            recoveryGuidance,
            findings,
        };
    }
    const summaryResult = readinessResult.workflowTopology === null
        ? null
        : (0, implementation_summary_reconciliation_1.reviewImplementationSummary)(repositoryRoot, {
            taskDefinitionPath: taskDefinitionPath.relative,
        });
    if (readinessResult.workflowTopology === null) {
        blockingIssues.push(...taskPolicy.blockingFindings.map((finding) => finding.message));
    }
    else if (summaryResult !== null) {
        blockingIssues.push(...summaryResult.missingEvidence, ...summaryResult.alignmentIssues);
        warnings.push(...summaryResult.placeholderResidue, ...summaryResult.reviewNotes);
    }
    for (const warning of readinessResult.reviewBoundaryWarnings) {
        if (!warnings.includes(warning))
            warnings.push(warning);
    }
    const parentMilestoneOverviewPath = (0, planning_document_utils_1.readUpstreamField)(taskDocument.frontMatterLines, 'milestone_overview')?.trim() ?? null;
    let modeBalance = null;
    if (parentMilestoneOverviewPath !== null
        && node_fs_1.default.existsSync(node_path_1.default.join(repositoryRoot, parentMilestoneOverviewPath))) {
        modeBalance = (0, mode_balance_1.evaluateMilestoneModeBalance)(repositoryRoot, {
            milestoneOverviewPath: parentMilestoneOverviewPath,
            selectedTaskDefinitionPath: taskDefinitionPath.relative,
        });
        if (modeBalance.optedIn
            && modeBalance.breakoutTaskDefinitionPath === taskDefinitionPath.relative
            && !modeBalance.breakoutSatisfied) {
            modeBalance = (0, mode_balance_1.evaluateMilestoneModeBalance)(repositoryRoot, {
                milestoneOverviewPath: parentMilestoneOverviewPath,
                selectedTaskDefinitionPath: taskDefinitionPath.relative,
                requireBreakoutForCloseout: true,
            });
        }
        blockingIssues.push(...modeBalance.blockingIssues);
    }
    if (summaryResult?.closeoutEvidenceStatus === 'sufficient' && taskStatus !== 'completed') {
        metadataHygieneFollowUps.push(`Accepted completed implementation evidence permits explicit closure, but task status remains '${taskStatus ?? '(missing)'}' at '${taskDefinitionPath.relative}'. Recommended command: day-shift task close --task-definition ${taskDefinitionPath.relative} --dry-run, then rerun with --write after reviewing the paired transition.`);
    }
    if (taskReconciliationExists) {
        const taskReconciliationText = node_fs_1.default.readFileSync(taskReconciliationAbsolute, 'utf8');
        const reconciliationDocument = (0, lifecycle_evidence_1.parseMarkdownDocument)(taskReconciliationPath, taskReconciliationText);
        const artifactType = (0, planning_document_utils_1.readTopLevelField)(reconciliationDocument.frontMatterLines, 'artifact_type')?.trim() ?? null;
        if (artifactType !== 'reconciliation') {
            blockingIssues.push(`Task-level reconciliation exception artifact '${taskReconciliationPath}' must use artifact_type 'reconciliation'.`);
        }
        else {
            const reconciliationStatus = (0, planning_document_utils_1.readTopLevelField)(reconciliationDocument.frontMatterLines, 'reconciliation_status')?.trim() ?? null;
            const reconciliationArtifactStatus = (0, planning_document_utils_1.readTopLevelField)(reconciliationDocument.frontMatterLines, 'status')?.trim() ?? null;
            if ((0, child_drift_1.documentHasPlaceholderContent)(taskReconciliationText)) {
                warnings.push(`Task-level reconciliation exception artifact '${taskReconciliationPath}' still contains placeholder review content.`);
            }
            if (reconciliationStatus === 'completed' && reconciliationArtifactStatus !== 'completed') {
                metadataHygieneFollowUps.push(`Shared status for task-level reconciliation family 'reconciliation' should be 'completed' at '${taskReconciliationPath}' when reconciliation_status is 'completed'. Recommended command: day-shift reconciliation update --reconciliation ${taskReconciliationPath} --field status=completed.`);
            }
        }
    }
    const recoveryGuidance = (0, rendering_1.buildPlanningRecoveryGuidance)({
        repositoryRoot,
        artifactPath: taskDefinitionPath.relative,
        reviewKind: 'task',
        blockingIssues,
        warnings,
        metadataHygieneFollowUps,
        modeBalanceEvaluations: modeBalance === null ? [] : [modeBalance],
    });
    const findings = (0, rendering_1.buildPlanningReviewFindings)({
        artifactPath: taskDefinitionPath.relative,
        reviewKind: 'task',
        blockingIssues,
        warnings,
        metadataHygieneFollowUps,
    }).concat(heuristicFindings);
    return {
        reviewMode,
        taskDefinitionPath: taskDefinitionPath.relative,
        implementationSummaryPath,
        taskReconciliationPath: taskReconciliationExists ? taskReconciliationPath : null,
        milestoneReconciliationPath: readinessResult.milestoneReconciliationPath,
        workflowTopology: readinessResult.workflowTopology,
        reviewBoundaryKind: readinessResult.reviewBoundaryKind,
        reconciliationArtifactKind: readinessResult.reconciliationArtifactKind,
        reconciliationRequired: readinessResult.reconciliationRequired,
        blockingIssues,
        warnings,
        metadataHygieneFollowUps,
        readinessStatus: null,
        closeoutEvidenceStatus: summaryResult?.closeoutEvidenceStatus ?? 'insufficient',
        modeBalance,
        recoveryGuidance,
        findings,
    };
}
