"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MILESTONE_NEW_RUNTIME_SEMANTICS = void 0;
exports.createMilestoneNewCommand = createMilestoneNewCommand;
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const errors_1 = require("../../../lib/errors");
const output_1 = require("../../../lib/output");
const paths_1 = require("../../../lib/paths");
const global_format_1 = require("../global-format");
const runtime_contract_1 = require("../../../lib/runtime/runtime-contract");
const cli_constants_1 = require("../../../lib/config/cli-constants");
const full_set_expansion_1 = require("../../../lib/planning/full-set-expansion");
const milestone_generation_1 = require("../../../lib/planning/milestone-generation");
const assistive_suggestions_1 = require("../../../lib/planning/assistive-suggestions");
const workflow_provenance_1 = require("../../../lib/planning/workflow-provenance");
const persisted_artifact_reminder_1 = require("../persisted-artifact-reminder");
exports.MILESTONE_NEW_RUNTIME_SEMANTICS = {
    conditionalInputs: [{ input: 'milestone-slug', whenInput: 'full-set', equals: false }],
    dependentInputs: [{ input: 'phase-review-result', requires: ['full-set'] }],
    conflictingInputs: [
        { inputs: ['milestone-slug', 'full-set'] },
        { inputs: ['milestone-title', 'full-set'] },
        { inputs: ['milestone-title', 'recover-scaffold'] },
    ],
    mutableFields: [],
    genericGuards: [
        {
            id: 'paired-milestone-scaffold',
            description: 'Milestone overview and reconciliation are validated and created as one pair.',
        },
        {
            id: 'recover-untouched-milestone-scaffold',
            description: 'Recovery replaces only an untouched CLI-generated draft overview paired with its default pending reconciliation and no task workspace.',
        },
        {
            id: 'phase-authoring-readiness-receipt',
            description: 'A full-set invocation that would create a missing milestone requires the exact current zero-blocker phase authoring readiness receipt; a fully materialized canonical no-op does not.',
        },
    ],
    failureTaxonomy: {
        missingRequiredInput: 'invalid-input',
        invalidField: 'invalid-input',
        invalidRepositoryState: 'invalid-config',
    },
    recoveries: [],
    exactExamples: [
        [
            'day-shift',
            'milestone',
            'new',
            '--phase-overview',
            '.day-shift/planning/governed/05-planning-artifacts/phases/01-contract/phase-overview.md',
            '--full-set',
            '--phase-review-result',
            '.day-shift/runs/run-example/phase-review.json',
        ],
    ],
};
async function createMilestoneNewCommand() {
    const { Command } = await import('commander');
    const command = new Command('new');
    command
        .description('Create or update an ordered milestone workspace from an existing phase overview.')
        .requiredOption('--phase-overview <path>', 'Repository-relative path to the parent phase overview (for example .day-shift/planning/governed/05-planning-artifacts/phases/02-hierarchy-and-generation-flow/phase-overview.md).')
        .option('--milestone-slug <slug>', 'Canonical milestone slug (ordered when sequence matters, for example 01-define-contract).')
        .option('--full-set', 'Create every declared milestone from the selected phase overview.')
        .option('--phase-review-result <path>', 'Repository-local complete JSON phase review result; required when --full-set would create a missing milestone.')
        .option('--milestone-title <title>', 'Optional explicit milestone H1 title. Defaults to title-cased milestone slug.')
        .option('--recover-scaffold', 'Replace an untouched CLI-generated draft milestone pair after exact eligibility and revision checks.')
        .action((_, commandInstance) => {
        const format = (0, output_1.resolveOutputFormat)((0, global_format_1.getGlobalFormat)(commandInstance));
        if (format === null) {
            throw (0, errors_1.createUsageError)('Output format must be one of: text, json.', [
                `Received: ${String((0, global_format_1.getGlobalFormat)(commandInstance))}`,
            ]);
        }
        const repositoryContext = (0, runtime_contract_1.createRepositoryContext)((0, runtime_contract_1.detectRepositoryRoot)(), false);
        const options = commandInstance.opts();
        if (options.fullSet === true) {
            const materialization = (0, milestone_generation_1.inspectMilestoneFullSetMaterialization)(repositoryContext.root, {
                phaseOverviewPath: options.phaseOverview,
            });
            let phaseAuthoringReceipt = null;
            if (!materialization.fullyMaterialized) {
                if (typeof options.phaseReviewResult !== 'string' || options.phaseReviewResult.trim() === '') {
                    throw (0, errors_1.createUsageError)('Milestone full-set creation requires --phase-review-result with the exact current clean phase authoring readiness receipt.', [
                        `Missing canonical milestone pairs: ${materialization.missingMilestoneSlugs.join(', ') || '(declarations unavailable)'}.`,
                        `Run day-shift phase review --phase-overview ${materialization.phaseOverviewPath} --format json, save the complete result, and pass that file without changing the phase.`,
                        'No milestone artifact write was attempted.',
                    ]);
                }
                phaseAuthoringReceipt = (0, milestone_generation_1.assertCurrentPhaseAuthoringReviewResult)(repositoryContext.root, {
                    phaseOverviewPath: options.phaseOverview,
                    phaseReviewResult: readPhaseAuthoringReviewResult(repositoryContext.root, options.phaseReviewResult),
                });
            }
            const result = (0, full_set_expansion_1.createMilestoneFullSetWorkspaces)(repositoryContext.root, {
                phaseOverviewPath: options.phaseOverview,
                recoverScaffold: options.recoverScaffold,
            });
            const assistiveSuggestion = (0, assistive_suggestions_1.suggestNextMilestoneFromPhase)({
                repositoryRoot: repositoryContext.root,
                phaseOverviewPath: result.phaseOverviewPath,
                currentMilestoneSlug: result.declaredMilestoneSlugs[result.declaredMilestoneSlugs.length - 1] ?? '',
            });
            const persistedArtifactLicenseReminder = (0, persisted_artifact_reminder_1.applyPlanningCommandPersistedArtifactReminderWrites)({
                repositoryContext,
                commandWriteSummary: result.commandWriteSummary,
                format,
            });
            (0, output_1.emitSuccess)({
                command: 'milestone new',
                format,
                text: renderMilestoneFullSetText(result, repositoryContext.root, assistiveSuggestion, result.workflowCliCommand),
                data: {
                    repositoryRoot: repositoryContext.root,
                    detectionSource: repositoryContext.detectionSource,
                    mode: 'full-set',
                    phaseOverviewPath: result.phaseOverviewPath,
                    declaredMilestoneSlugs: result.declaredMilestoneSlugs,
                    createdCount: result.createdCount,
                    keptCount: result.keptCount,
                    refreshedCount: result.refreshedCount,
                    phaseAuthoringReceipt: {
                        required: !materialization.fullyMaterialized,
                        reason: materialization.fullyMaterialized
                            ? 'fully-materialized-canonical-no-op'
                            : 'missing-milestone-create',
                        receiptId: phaseAuthoringReceipt?.receiptId ?? null,
                        phaseRevision: phaseAuthoringReceipt?.phaseRevision ?? null,
                        missingMilestoneSlugs: materialization.missingMilestoneSlugs,
                    },
                    requiresRefinement: result.requiresRefinement,
                    application: result.application,
                    milestoneWorkspaces: result.milestoneWorkspaces.map((workspace) => ({
                        slice: workspace.slice,
                        phase: workspace.phase,
                        planningDepth: workspace.planningDepth,
                        milestoneSlug: workspace.milestoneSlug,
                        milestoneTitle: workspace.milestoneTitle,
                        paths: {
                            phaseOverviewPath: workspace.phaseOverviewPath,
                            milestonesDirectoryPath: (0, paths_1.toRepositoryRelativePath)(repositoryContext.root, workspace.milestonesDirectoryPath),
                            milestoneDirectoryPath: (0, paths_1.toRepositoryRelativePath)(repositoryContext.root, workspace.milestoneDirectoryPath),
                            overviewPath: (0, paths_1.toRepositoryRelativePath)(repositoryContext.root, workspace.overviewPath),
                            reconciliationPath: (0, paths_1.toRepositoryRelativePath)(repositoryContext.root, workspace.reconciliationPath),
                        },
                        actions: {
                            milestonesDirectory: workspace.milestonesDirectoryAction,
                            overview: workspace.overviewAction,
                            reconciliation: workspace.reconciliationAction,
                        },
                        contributingSpecIds: workspace.contributingSpecIds,
                        scaffoldEvidence: workspace.scaffoldEvidence,
                        scaffoldProjection: workspace.scaffoldProjection,
                    })),
                    assistiveSuggestion,
                    workflowProvenance: {
                        method: 'cli',
                        cliCommand: result.workflowCliCommand,
                    },
                    commandWriteSummary: persistedArtifactLicenseReminder.commandWriteSummary,
                    persistedArtifactLicenseReminder,
                },
            });
            return;
        }
        if (options.phaseReviewResult !== undefined) {
            throw (0, errors_1.createUsageError)('--phase-review-result is supported only with --full-set.', [
                'Single milestone creation retains its existing creation-authoritative scaffold validation boundary.',
            ]);
        }
        if (options.milestoneSlug === undefined ||
            options.milestoneSlug === null ||
            String(options.milestoneSlug).trim() === '') {
            throw (0, errors_1.createUsageError)('Missing required --milestone-slug option.', [
                'Provide --milestone-slug for single milestone generation or add --full-set to expand declared milestones.',
            ]);
        }
        const result = (0, milestone_generation_1.createMilestoneWorkspace)(repositoryContext.root, {
            phaseOverviewPath: options.phaseOverview,
            milestoneSlug: options.milestoneSlug,
            milestoneTitle: options.milestoneTitle,
            recoverScaffold: options.recoverScaffold,
        });
        const assistiveSuggestion = (0, assistive_suggestions_1.suggestNextMilestoneFromPhase)({
            repositoryRoot: repositoryContext.root,
            phaseOverviewPath: result.phaseOverviewPath,
            currentMilestoneSlug: result.milestoneSlug,
        });
        const persistedArtifactLicenseReminder = (0, persisted_artifact_reminder_1.applyPlanningCommandPersistedArtifactReminderWrites)({
            repositoryContext,
            commandWriteSummary: result.commandWriteSummary,
            format,
        });
        const workflowProvenance = (0, workflow_provenance_1.buildCliWorkflowProvenance)(`day-shift milestone new --phase-overview ${result.phaseOverviewPath} --milestone-slug ${result.milestoneSlug}`);
        (0, output_1.emitSuccess)({
            command: 'milestone new',
            format,
            text: renderMilestoneNewText(result, repositoryContext.root, assistiveSuggestion, workflowProvenance.workflowCliCommand),
            data: {
                repositoryRoot: repositoryContext.root,
                detectionSource: repositoryContext.detectionSource,
                slice: result.slice,
                phase: result.phase,
                planningDepth: result.planningDepth,
                milestoneSlug: result.milestoneSlug,
                milestoneTitle: result.milestoneTitle,
                paths: {
                    phaseOverviewPath: result.phaseOverviewPath,
                    milestonesDirectoryPath: (0, paths_1.toRepositoryRelativePath)(repositoryContext.root, result.milestonesDirectoryPath),
                    milestoneDirectoryPath: (0, paths_1.toRepositoryRelativePath)(repositoryContext.root, result.milestoneDirectoryPath),
                    overviewPath: (0, paths_1.toRepositoryRelativePath)(repositoryContext.root, result.overviewPath),
                    reconciliationPath: (0, paths_1.toRepositoryRelativePath)(repositoryContext.root, result.reconciliationPath),
                },
                actions: {
                    milestonesDirectory: result.milestonesDirectoryAction,
                    overview: result.overviewAction,
                    reconciliation: result.reconciliationAction,
                },
                contributingSpecIds: result.contributingSpecIds,
                requiresRefinement: result.requiresRefinement,
                scaffoldEvidence: result.scaffoldEvidence,
                scaffoldProjection: result.scaffoldProjection,
                application: result.application,
                assistiveSuggestion,
                workflowProvenance: {
                    method: workflowProvenance.workflowProvenance,
                    cliCommand: workflowProvenance.workflowCliCommand,
                },
                commandWriteSummary: persistedArtifactLicenseReminder.commandWriteSummary,
                persistedArtifactLicenseReminder,
            },
        });
    });
    (0, output_1.attachCommandRuntimeSemantics)(command, exports.MILESTONE_NEW_RUNTIME_SEMANTICS);
    return command;
}
function renderMilestoneNewText(result, repositoryRoot, assistiveSuggestion, workflowCliCommand) {
    return [
        'Milestone workspace is ready.',
        `Slice: ${result.slice}`,
        `Phase: ${result.phase}`,
        `Milestone slug: ${result.milestoneSlug}`,
        `Milestone title: ${result.milestoneTitle}`,
        `Phase overview: ${result.phaseOverviewPath}`,
        `Milestones directory: ${(0, paths_1.toRepositoryRelativePath)(repositoryRoot, result.milestonesDirectoryPath)} (${result.milestonesDirectoryAction})`,
        `Milestone overview: ${(0, paths_1.toRepositoryRelativePath)(repositoryRoot, result.overviewPath)} (${result.overviewAction})`,
        `Milestone reconciliation: ${(0, paths_1.toRepositoryRelativePath)(repositoryRoot, result.reconciliationPath)} (${result.reconciliationAction})`,
        `Contributing specs: ${result.contributingSpecIds.join(', ')}`,
        `Refinement required: ${result.requiresRefinement ? 'yes' : 'no'}.`,
        `Write outcome: ${result.application.outcome}`,
        `Scaffolded via: ${workflowCliCommand}`,
        ...(0, assistive_suggestions_1.renderAssistiveSuggestionText)(assistiveSuggestion),
    ].join('\n');
}
function renderMilestoneFullSetText(result, repositoryRoot, assistiveSuggestion, workflowCliCommand) {
    return [
        'Milestone full-set expansion is ready.',
        `Phase overview: ${result.phaseOverviewPath}`,
        `Declared milestones: ${result.declaredMilestoneSlugs.join(', ')}`,
        `Created: ${result.createdCount}`,
        `Kept: ${result.keptCount}`,
        `Refreshed: ${result.refreshedCount}`,
        `Refinement required: ${result.requiresRefinement ? 'yes' : 'no'}.`,
        `Write outcome: ${result.application.outcome}`,
        'Milestone workspaces:',
        ...result.milestoneWorkspaces.map((workspace) => {
            return [
                `- ${workspace.milestoneSlug}`,
                `  Milestone title: ${workspace.milestoneTitle}`,
                `  Overview: ${(0, paths_1.toRepositoryRelativePath)(repositoryRoot, workspace.overviewPath)} (${workspace.overviewAction})`,
                `  Reconciliation: ${(0, paths_1.toRepositoryRelativePath)(repositoryRoot, workspace.reconciliationPath)} (${workspace.reconciliationAction})`,
            ].join('\n');
        }),
        `Scaffolded via: ${workflowCliCommand}`,
        ...(0, assistive_suggestions_1.renderAssistiveSuggestionText)(assistiveSuggestion),
    ].join('\n');
}
function readPhaseAuthoringReviewResult(repositoryRoot, inputPath) {
    let repositoryPath;
    try {
        repositoryPath = (0, paths_1.parseRepositoryRelativePath)(inputPath).normalizedPath;
    }
    catch (error) {
        throw (0, errors_1.createUsageError)('--phase-review-result must be a repository-relative JSON file path.', [
            error instanceof Error ? error.message : String(error),
        ]);
    }
    const absolutePath = node_path_1.default.join(repositoryRoot, repositoryPath);
    const before = node_fs_1.default.lstatSync(absolutePath, { throwIfNoEntry: false });
    if (before === undefined || !before.isFile() || before.isSymbolicLink()) {
        throw (0, errors_1.createUsageError)('--phase-review-result must identify a non-symlink regular JSON file.');
    }
    if (before.size <= 0 || before.size > cli_constants_1.CLI_MAX_REVIEW_RESULT_BYTES) {
        throw (0, errors_1.createUsageError)('--phase-review-result must be non-empty and no larger than 2 MiB.');
    }
    const bytes = node_fs_1.default.readFileSync(absolutePath);
    const after = node_fs_1.default.lstatSync(absolutePath, { throwIfNoEntry: false });
    if (after === undefined ||
        after.size !== before.size ||
        after.mtimeMs !== before.mtimeMs ||
        after.ino !== before.ino) {
        throw (0, errors_1.createUsageError)('--phase-review-result changed while it was being inspected.');
    }
    try {
        return JSON.parse(bytes.toString('utf8'));
    }
    catch {
        throw (0, errors_1.createUsageError)('--phase-review-result must contain valid UTF-8 JSON.');
    }
}
