"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createMilestoneNewCommand = createMilestoneNewCommand;
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 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");
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/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("--milestone-title <title>", "Optional explicit milestone H1 title. Defaults to title-cased milestone slug.")
        .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 result = (0, full_set_expansion_1.createMilestoneFullSetWorkspaces)(repositoryContext.root, {
                phaseOverviewPath: options.phaseOverview
            });
            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,
                    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
                    })),
                    assistiveSuggestion,
                    workflowProvenance: {
                        method: "cli",
                        cliCommand: result.workflowCliCommand
                    },
                    commandWriteSummary: persistedArtifactLicenseReminder.commandWriteSummary,
                    persistedArtifactLicenseReminder
                }
            });
            return;
        }
        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
        });
        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,
                assistiveSuggestion,
                workflowProvenance: {
                    method: workflowProvenance.workflowProvenance,
                    cliCommand: workflowProvenance.workflowCliCommand
                },
                commandWriteSummary: persistedArtifactLicenseReminder.commandWriteSummary,
                persistedArtifactLicenseReminder
            }
        });
    });
    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(", ")}`,
        `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}`,
        "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");
}
