"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PHASE_NEW_RUNTIME_SEMANTICS = void 0;
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");
exports.PHASE_NEW_RUNTIME_SEMANTICS = {
    conditionalInputs: [{ input: "phase-slug", whenInput: "full-set", equals: false }],
    dependentInputs: [],
    conflictingInputs: [
        { inputs: ["phase-slug", "full-set"] },
        { inputs: ["phase-title", "full-set"] }
    ],
    mutableFields: [],
    genericGuards: [{
            id: "declared-phase-only",
            description: "The selected phase slug must already be declared by the canonical Governed slice parent."
        }],
    failureTaxonomy: {
        missingRequiredInput: "invalid-input",
        invalidField: "invalid-input",
        invalidRepositoryState: "invalid-config"
    },
    recoveries: [],
    exactExamples: [[
            "day-shift", "phase", "new", "--slice-overview",
            ".day-shift/planning/governed/05-planning-artifacts/slice-overview.md",
            "--full-set"
        ]]
};
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/governed/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
            });
            const postCreateActions = buildPhaseFullSetPostCreateActions(result);
            (0, output_1.emitSuccess)({
                command: "phase new",
                format,
                text: renderPhaseFullSetText(result, repositoryContext.root, assistiveSuggestion, result.workflowCliCommand, postCreateActions),
                data: {
                    repositoryRoot: repositoryContext.root,
                    detectionSource: repositoryContext.detectionSource,
                    mode: "full-set",
                    sliceOverviewPath: result.sliceOverviewPath,
                    declaredPhaseSlugs: result.declaredPhaseSlugs,
                    createdCount: result.createdCount,
                    keptCount: result.keptCount,
                    requiresRefinement: result.requiresRefinement,
                    pendingRefinementPaths: result.pendingRefinementPaths,
                    application: result.application,
                    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,
                        requiresRefinement: workspace.requiresRefinement,
                        refinementIssues: workspace.refinementIssues,
                        scaffoldEvidence: workspace.scaffoldEvidence
                    })),
                    postCreateActions,
                    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,
                requiresRefinement: result.requiresRefinement,
                refinementIssues: result.refinementIssues,
                scaffoldEvidence: result.scaffoldEvidence,
                application: result.application,
                assistiveSuggestion,
                workflowProvenance: {
                    method: workflowProvenance.workflowProvenance,
                    cliCommand: workflowProvenance.workflowCliCommand
                },
                commandWriteSummary: persistedArtifactLicenseReminder.commandWriteSummary,
                persistedArtifactLicenseReminder
            }
        });
    });
    (0, output_1.attachCommandRuntimeSemantics)(command, exports.PHASE_NEW_RUNTIME_SEMANTICS);
    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(", ")}`,
        `Refinement required: ${result.requiresRefinement ? "yes" : "no"}.`,
        ...(result.refinementIssues.length === 0
            ? []
            : [
                "Refinement findings:",
                ...result.refinementIssues.map((issue) => `- ${issue.reason}`)
            ]),
        `Write outcome: ${result.application.outcome}`,
        `Scaffolded via: ${workflowCliCommand}`,
        ...(0, assistive_suggestions_1.renderAssistiveSuggestionText)(assistiveSuggestion)
    ].join("\n");
}
function renderPhaseFullSetText(result, repositoryRoot, assistiveSuggestion, workflowCliCommand, postCreateActions) {
    return [
        "Phase full-set expansion is ready.",
        `Slice overview: ${result.sliceOverviewPath}`,
        `Declared phases: ${result.declaredPhaseSlugs.join(", ")}`,
        `Created: ${result.createdCount}`,
        `Kept: ${result.keptCount}`,
        `Refinement required: ${result.requiresRefinement ? "yes" : "no"}.`,
        `Pending refinement paths: ${result.pendingRefinementPaths.length === 0 ? "none" : result.pendingRefinementPaths.join(", ")}`,
        `Write outcome: ${result.application.outcome}`,
        "Phase workspaces:",
        ...result.phaseWorkspaces.map((workspace) => {
            return [
                `- ${workspace.phaseSlug}`,
                `  Phase title: ${workspace.phaseTitle}`,
                `  Overview: ${(0, paths_1.toRepositoryRelativePath)(repositoryRoot, workspace.overviewPath)} (${workspace.overviewAction})`,
                `  Refinement required: ${workspace.requiresRefinement ? "yes" : "no"}`
            ].join("\n");
        }),
        "Post-create actions (recommended only; not executed):",
        ...postCreateActions.map((action) => {
            const condition = action.condition === "always"
                ? ""
                : " (optional; only after the dry-run reports safe changes)";
            return `- ${action.command}${condition}`;
        }),
        `Scaffolded via: ${workflowCliCommand}`,
        ...(0, assistive_suggestions_1.renderAssistiveSuggestionText)(assistiveSuggestion)
    ].join("\n");
}
function buildPhaseFullSetPostCreateActions(result) {
    const sliceOverviewPath = result.sliceOverviewPath;
    const parentActions = [
        {
            id: "parent-links-check",
            targetPath: sliceOverviewPath,
            command: `day-shift validation links-check --scope planning --artifact ${sliceOverviewPath}`,
            writeCapable: false,
            automatic: false,
            condition: "always"
        },
        {
            id: "parent-materialization-dry-run",
            targetPath: sliceOverviewPath,
            command: `day-shift link materialize --dry-run --artifact ${sliceOverviewPath}`,
            writeCapable: false,
            automatic: false,
            condition: "always"
        },
        {
            id: "parent-materialization-write",
            targetPath: sliceOverviewPath,
            command: `day-shift link materialize --write --artifact ${sliceOverviewPath} --validation-evidence-id <evidence-id>`,
            writeCapable: true,
            automatic: false,
            condition: "after-safe-materialization-dry-run"
        }
    ];
    const childActions = result.phaseWorkspaces.map((workspace) => {
        const overviewPath = (0, paths_1.toRepositoryRelativePath)(result.repositoryRoot, workspace.overviewPath);
        return {
            id: "child-smoke-check",
            targetPath: overviewPath,
            command: `day-shift validation smoke --scope planning --artifact ${overviewPath}`,
            writeCapable: false,
            automatic: false,
            condition: "always"
        };
    });
    return [...parentActions, ...childActions];
}
