"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createPhaseNewCommand = createPhaseNewCommand;
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 phase_generation_1 = require("../../../lib/planning/phase-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 createPhaseNewCommand() {
    const { Command } = await import("commander");
    const command = new Command("new");
    command
        .description("Create or update an ordered phase workspace from an existing slice overview.")
        .requiredOption("--slice-overview <path>", "Repository-relative path to the parent slice overview (for example .day-shift/planning/05-planning-artifacts/slice-overview.md).")
        .option("--phase-slug <slug>", "Canonical phase slug (ordered when sequence matters, for example 01-runtime-and-context).")
        .option("--full-set", "Create every declared phase from the selected slice overview.")
        .option("--phase-title <title>", "Optional explicit phase H1 title. Defaults to title-cased phase 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.createPhaseFullSetWorkspaces)(repositoryContext.root, {
                sliceOverviewPath: options.sliceOverview
            });
            const assistiveSuggestion = (0, assistive_suggestions_1.suggestNextPhaseFromSlice)({
                repositoryRoot: repositoryContext.root,
                sliceOverviewPath: result.sliceOverviewPath,
                currentPhaseSlug: result.declaredPhaseSlugs[result.declaredPhaseSlugs.length - 1] ?? ""
            });
            const persistedArtifactLicenseReminder = (0, persisted_artifact_reminder_1.applyPlanningCommandPersistedArtifactReminderWrites)({
                repositoryContext,
                commandWriteSummary: result.commandWriteSummary,
                format
            });
            (0, output_1.emitSuccess)({
                command: "phase new",
                format,
                text: renderPhaseFullSetText(result, repositoryContext.root, assistiveSuggestion, result.workflowCliCommand),
                data: {
                    repositoryRoot: repositoryContext.root,
                    detectionSource: repositoryContext.detectionSource,
                    mode: "full-set",
                    sliceOverviewPath: result.sliceOverviewPath,
                    declaredPhaseSlugs: result.declaredPhaseSlugs,
                    createdCount: result.createdCount,
                    keptCount: result.keptCount,
                    phaseWorkspaces: result.phaseWorkspaces.map((workspace) => ({
                        slice: workspace.slice,
                        planningDepth: workspace.planningDepth,
                        phaseSlug: workspace.phaseSlug,
                        phaseTitle: workspace.phaseTitle,
                        paths: {
                            sliceOverviewPath: workspace.sliceOverviewPath,
                            phasesDirectoryPath: (0, paths_1.toRepositoryRelativePath)(repositoryContext.root, workspace.phasesDirectoryPath),
                            phaseDirectoryPath: (0, paths_1.toRepositoryRelativePath)(repositoryContext.root, workspace.phaseDirectoryPath),
                            overviewPath: (0, paths_1.toRepositoryRelativePath)(repositoryContext.root, workspace.overviewPath)
                        },
                        actions: {
                            phasesDirectory: workspace.phasesDirectoryAction,
                            overview: workspace.overviewAction
                        },
                        contributingSpecIds: workspace.contributingSpecIds
                    })),
                    assistiveSuggestion,
                    workflowProvenance: {
                        method: "cli",
                        cliCommand: result.workflowCliCommand
                    },
                    commandWriteSummary: persistedArtifactLicenseReminder.commandWriteSummary,
                    persistedArtifactLicenseReminder
                }
            });
            return;
        }
        if (options.phaseSlug === undefined || options.phaseSlug === null || String(options.phaseSlug).trim() === "") {
            throw (0, errors_1.createUsageError)("Missing required --phase-slug option.", ["Provide --phase-slug for single phase generation or add --full-set to expand declared phases."]);
        }
        const result = (0, phase_generation_1.createPhaseWorkspace)(repositoryContext.root, {
            sliceOverviewPath: options.sliceOverview,
            phaseSlug: options.phaseSlug,
            phaseTitle: options.phaseTitle
        });
        const assistiveSuggestion = (0, assistive_suggestions_1.suggestNextPhaseFromSlice)({
            repositoryRoot: repositoryContext.root,
            sliceOverviewPath: result.sliceOverviewPath,
            currentPhaseSlug: result.phaseSlug
        });
        const persistedArtifactLicenseReminder = (0, persisted_artifact_reminder_1.applyPlanningCommandPersistedArtifactReminderWrites)({
            repositoryContext,
            commandWriteSummary: result.commandWriteSummary,
            format
        });
        const workflowProvenance = (0, workflow_provenance_1.buildCliWorkflowProvenance)(`day-shift phase new --slice-overview ${result.sliceOverviewPath} --phase-slug ${result.phaseSlug}`);
        (0, output_1.emitSuccess)({
            command: "phase new",
            format,
            text: renderPhaseNewText(result, repositoryContext.root, assistiveSuggestion, workflowProvenance.workflowCliCommand),
            data: {
                repositoryRoot: repositoryContext.root,
                detectionSource: repositoryContext.detectionSource,
                slice: result.slice,
                planningDepth: result.planningDepth,
                phaseSlug: result.phaseSlug,
                phaseTitle: result.phaseTitle,
                paths: {
                    sliceOverviewPath: result.sliceOverviewPath,
                    phasesDirectoryPath: (0, paths_1.toRepositoryRelativePath)(repositoryContext.root, result.phasesDirectoryPath),
                    phaseDirectoryPath: (0, paths_1.toRepositoryRelativePath)(repositoryContext.root, result.phaseDirectoryPath),
                    overviewPath: (0, paths_1.toRepositoryRelativePath)(repositoryContext.root, result.overviewPath)
                },
                actions: {
                    phasesDirectory: result.phasesDirectoryAction,
                    overview: result.overviewAction
                },
                contributingSpecIds: result.contributingSpecIds,
                assistiveSuggestion,
                workflowProvenance: {
                    method: workflowProvenance.workflowProvenance,
                    cliCommand: workflowProvenance.workflowCliCommand
                },
                commandWriteSummary: persistedArtifactLicenseReminder.commandWriteSummary,
                persistedArtifactLicenseReminder
            }
        });
    });
    return command;
}
function renderPhaseNewText(result, repositoryRoot, assistiveSuggestion, workflowCliCommand) {
    return [
        "Phase workspace is ready.",
        `Slice: ${result.slice}`,
        `Phase slug: ${result.phaseSlug}`,
        `Phase title: ${result.phaseTitle}`,
        `Slice overview: ${result.sliceOverviewPath}`,
        `Phases directory: ${(0, paths_1.toRepositoryRelativePath)(repositoryRoot, result.phasesDirectoryPath)} (${result.phasesDirectoryAction})`,
        `Phase overview: ${(0, paths_1.toRepositoryRelativePath)(repositoryRoot, result.overviewPath)} (${result.overviewAction})`,
        `Contributing specs: ${result.contributingSpecIds.join(", ")}`,
        `Scaffolded via: ${workflowCliCommand}`,
        ...(0, assistive_suggestions_1.renderAssistiveSuggestionText)(assistiveSuggestion)
    ].join("\n");
}
function renderPhaseFullSetText(result, repositoryRoot, assistiveSuggestion, workflowCliCommand) {
    return [
        "Phase full-set expansion is ready.",
        `Slice overview: ${result.sliceOverviewPath}`,
        `Declared phases: ${result.declaredPhaseSlugs.join(", ")}`,
        `Created: ${result.createdCount}`,
        `Kept: ${result.keptCount}`,
        "Phase workspaces:",
        ...result.phaseWorkspaces.map((workspace) => {
            return [
                `- ${workspace.phaseSlug}`,
                `  Phase title: ${workspace.phaseTitle}`,
                `  Overview: ${(0, paths_1.toRepositoryRelativePath)(repositoryRoot, workspace.overviewPath)} (${workspace.overviewAction})`
            ].join("\n");
        }),
        `Scaffolded via: ${workflowCliCommand}`,
        ...(0, assistive_suggestions_1.renderAssistiveSuggestionText)(assistiveSuggestion)
    ].join("\n");
}
