"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SLICE_NEW_RUNTIME_SEMANTICS = void 0;
exports.createSliceNewCommand = createSliceNewCommand;
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 assistive_suggestions_1 = require("../../../lib/planning/assistive-suggestions");
const slice_generation_1 = require("../../../lib/planning/slice-generation");
const workflow_provenance_1 = require("../../../lib/planning/workflow-provenance");
const persisted_artifact_reminder_1 = require("../persisted-artifact-reminder");
exports.SLICE_NEW_RUNTIME_SEMANTICS = {
    conditionalInputs: [],
    dependentInputs: [],
    conflictingInputs: [{ inputs: ["spec-id", "slice-id"] }],
    mutableFields: ["depth", "destination", "linked_slice.slice", "linked_slice.path"],
    genericGuards: [{
            id: "exactly-one-slice-selector",
            description: "Exactly one of specId or sliceId is required."
        }, {
            id: "canonical-governed-destination",
            description: "New slices are written only beneath .day-shift/planning/governed/<implementation-order>-<slice-slug>/."
        }],
    failureTaxonomy: {
        missingRequiredInput: "invalid-input",
        invalidField: "invalid-input",
        invalidRepositoryState: "invalid-config"
    },
    recoveries: [],
    exactExamples: [[
            "day-shift", "slice", "new", "--spec-id", "spec-registry-commands", "--dry-run"
        ]]
};
async function createSliceNewCommand() {
    const { Command } = await import("commander");
    const command = new Command("new");
    command
        .description("Create or update an ordered slice workspace from registered spec context.")
        .option("--spec-id <id>", "Select slice context from a specific registered spec id.")
        .option("--slice-id <id>", "Select slice context from linked_slice.slice id.")
        .option("--dry-run", "Preview the exact scaffold and registry writes without mutation.")
        .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();
        const result = (0, slice_generation_1.createSliceWorkspace)(repositoryContext.root, {
            specId: options.specId,
            sliceId: options.sliceId,
            dryRun: options.dryRun === true
        });
        const assistiveSuggestion = (0, assistive_suggestions_1.suggestNextPhaseForSlice)({
            repositoryRoot: repositoryContext.root,
            sliceOverviewPath: (0, paths_1.toRepositoryRelativePath)(repositoryContext.root, result.overviewPath)
        });
        const persistedArtifactLicenseReminder = (0, persisted_artifact_reminder_1.applyPlanningCommandPersistedArtifactReminderWrites)({
            repositoryContext,
            commandWriteSummary: result.commandWriteSummary,
            format
        });
        const workflowProvenance = (0, workflow_provenance_1.buildCliWorkflowProvenance)([
            options.specId
                ? `day-shift slice new --spec-id ${result.selectedSpecId}`
                : `day-shift slice new --slice-id ${result.selectedSliceId}`,
            options.dryRun === true ? '--dry-run' : ''
        ].filter((value) => value !== "").join(" "));
        (0, output_1.emitSuccess)({
            command: "slice new",
            format,
            text: renderSliceNewText(result, repositoryContext.root, assistiveSuggestion, workflowProvenance.workflowCliCommand),
            data: {
                repositoryRoot: repositoryContext.root,
                detectionSource: repositoryContext.detectionSource,
                selectedSpecId: result.selectedSpecId,
                selectedSliceId: result.selectedSliceId,
                implementationOrder: result.implementationOrder,
                sliceSlug: result.sliceSlug,
                orderedSliceDirectoryName: result.orderedSliceDirectoryName,
                workflowLevel: result.workflowLevel,
                canonicalSliceId: result.canonicalSliceId,
                dryRun: result.dryRun,
                paths: {
                    specIndexPath: (0, paths_1.toRepositoryRelativePath)(repositoryContext.root, result.specIndexPath),
                    sliceDirectoryPath: (0, paths_1.toRepositoryRelativePath)(repositoryContext.root, result.sliceDirectoryPath),
                    overviewPath: (0, paths_1.toRepositoryRelativePath)(repositoryContext.root, result.overviewPath),
                    decisionsGitkeepPath: (0, paths_1.toRepositoryRelativePath)(repositoryContext.root, result.decisionsGitkeepPath),
                    notesGitkeepPath: (0, paths_1.toRepositoryRelativePath)(repositoryContext.root, result.notesGitkeepPath)
                },
                actions: {
                    overview: result.overviewAction,
                    decisionsGitkeep: result.decisionsGitkeepAction,
                    notesGitkeep: result.notesGitkeepAction,
                    registry: result.registryAction
                },
                requiresRefinement: result.requiresRefinement,
                contributingSpecIds: result.contributingSpecIds,
                application: result.application,
                workflowProvenance: {
                    method: workflowProvenance.workflowProvenance,
                    cliCommand: workflowProvenance.workflowCliCommand
                },
                commandWriteSummary: persistedArtifactLicenseReminder.commandWriteSummary,
                persistedArtifactLicenseReminder,
                assistiveSuggestion
            }
        });
    });
    (0, output_1.attachCommandRuntimeSemantics)(command, exports.SLICE_NEW_RUNTIME_SEMANTICS);
    return command;
}
function renderSliceNewText(result, repositoryRoot, assistiveSuggestion, workflowCliCommand) {
    return [
        result.dryRun ? "Slice workspace preview is ready." : "Slice workspace is ready.",
        `Dry run: ${result.dryRun ? "yes" : "no"}`,
        `Selected spec id: ${result.selectedSpecId}`,
        `Selected slice id: ${result.selectedSliceId}`,
        `Implementation order: ${result.implementationOrder}`,
        `Slice slug: ${result.sliceSlug}`,
        `Workflow level: ${result.workflowLevel ?? "legacy/current"}`,
        `Canonical slice id: ${result.canonicalSliceId ?? "(none)"}`,
        `Slice directory: ${(0, paths_1.toRepositoryRelativePath)(repositoryRoot, result.sliceDirectoryPath)}`,
        `Overview: ${(0, paths_1.toRepositoryRelativePath)(repositoryRoot, result.overviewPath)} (${result.overviewAction})`,
        `Decisions gitkeep: ${(0, paths_1.toRepositoryRelativePath)(repositoryRoot, result.decisionsGitkeepPath)} (${result.decisionsGitkeepAction})`,
        `Notes gitkeep: ${(0, paths_1.toRepositoryRelativePath)(repositoryRoot, result.notesGitkeepPath)} (${result.notesGitkeepAction})`,
        `Spec registry: ${result.registryAction}`,
        `Contributing specs: ${result.contributingSpecIds.join(", ")}`,
        "Refinement required: yes; replace scaffold phase placeholders with declared ordered phase slugs before phase creation.",
        `Write outcome: ${result.application.outcome}`,
        `Changed paths: ${result.application.changedPaths.join(", ") || "(none)"}`,
        `${result.dryRun ? "Previewed" : "Scaffolded"} via: ${workflowCliCommand}`,
        ...(0, assistive_suggestions_1.renderAssistiveSuggestionText)(assistiveSuggestion)
    ].join("\n");
}
