"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TASK_NEW_RUNTIME_SEMANTICS = void 0;
exports.createTaskNewCommand = createTaskNewCommand;
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 task_generation_1 = require("../../../lib/planning/task-generation");
const workflow_provenance_1 = require("../../../lib/planning/workflow-provenance");
const persisted_artifact_reminder_1 = require("../persisted-artifact-reminder");
exports.TASK_NEW_RUNTIME_SEMANTICS = {
    conditionalInputs: [
        { input: "milestone-overview", whenInput: "lightweight", equals: false },
        { input: "slice-overview", whenInput: "lightweight", equals: true },
        { input: "task-slug", whenInput: "full-set", equals: false }
    ],
    dependentInputs: [
        { input: "slice-overview", requires: ["lightweight"] }
    ],
    conflictingInputs: [
        { inputs: ["milestone-overview", "slice-overview"] },
        { inputs: ["lightweight", "milestone-overview"] },
        { inputs: ["lightweight", "full-set"] },
        { inputs: ["lightweight", "recover-scaffold"] },
        { inputs: ["task-slug", "full-set"] },
        { inputs: ["task-title", "full-set"] },
        { inputs: ["task-title", "recover-scaffold"] }
    ],
    mutableFields: [],
    genericGuards: [{
            id: "paired-task-scaffold",
            description: "Task definition and implementation summary are validated and created as one pair."
        }, {
            id: "recover-untouched-task-scaffold",
            description: "Recovery replaces only an untouched CLI-generated draft task definition paired with its default pending no-attempt implementation summary."
        }],
    failureTaxonomy: {
        missingRequiredInput: "invalid-input",
        invalidField: "invalid-input",
        invalidRepositoryState: "invalid-config"
    },
    recoveries: [],
    exactExamples: [[
            "day-shift", "task", "new", "--milestone-overview",
            ".day-shift/planning/governed/05-planning-artifacts/phases/01-contract/milestones/01-runtime/milestone-overview.md",
            "--full-set"
        ]]
};
async function createTaskNewCommand() {
    const { Command } = await import("commander");
    const command = new Command("new");
    command
        .description("Create or update an ordered task workspace from an existing milestone or lightweight slice overview.")
        .option("--milestone-overview <path>", "Repository-relative path to the parent milestone overview (for example .day-shift/planning/governed/05-planning-artifacts/phases/02-hierarchy-and-generation-flow/milestones/02-define-phase-and-milestone-generation-contract/milestone-overview.md).")
        .option("--slice-overview <path>", "Repository-relative path to the parent lightweight slice overview when using --lightweight.")
        .option("--lightweight", "Create a direct lightweight task workspace under the selected slice overview.")
        .option("--task-slug <slug>", "Canonical task slug (ordered when sequence matters, for example 01-define-contract).")
        .option("--full-set", "Create every declared task from the selected milestone overview.")
        .option("--task-title <title>", "Optional explicit task H1 title. Defaults to title-cased task slug.")
        .option("--recover-scaffold", "Replace an untouched CLI-generated draft task 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.lightweight === true) {
            if (options.milestoneOverview !== undefined) {
                throw (0, errors_1.createUsageError)("Cannot combine --lightweight with --milestone-overview.", ["Use --slice-overview for lightweight task creation or omit --lightweight for milestone-parented task creation."]);
            }
            if (options.fullSet === true) {
                throw (0, errors_1.createUsageError)("Cannot combine --lightweight with --full-set.", ["Create lightweight tasks one at a time with --slice-overview and --task-slug."]);
            }
            if (options.recoverScaffold === true) {
                throw (0, errors_1.createUsageError)("Cannot combine --lightweight with --recover-scaffold.", ["Task scaffold recovery is available only for standard milestone-parented task pairs."]);
            }
            if (options.sliceOverview === undefined || String(options.sliceOverview).trim() === "") {
                throw (0, errors_1.createUsageError)("Missing required --slice-overview option for lightweight task creation.", ["Provide --slice-overview with --lightweight."]);
            }
            if (options.taskSlug === undefined || options.taskSlug === null || String(options.taskSlug).trim() === "") {
                throw (0, errors_1.createUsageError)("Missing required --task-slug option.", ["Provide --task-slug for lightweight task generation."]);
            }
            const result = (0, task_generation_1.createLightweightTaskWorkspace)(repositoryContext.root, {
                sliceOverviewPath: options.sliceOverview,
                taskSlug: options.taskSlug,
                taskTitle: options.taskTitle
            });
            const persistedArtifactLicenseReminder = (0, persisted_artifact_reminder_1.applyPlanningCommandPersistedArtifactReminderWrites)({
                repositoryContext,
                commandWriteSummary: result.commandWriteSummary,
                format
            });
            const workflowProvenance = (0, workflow_provenance_1.buildCliWorkflowProvenance)(`day-shift task new --lightweight --slice-overview ${result.sliceOverviewPath} --task-slug ${result.taskSlug}`);
            (0, output_1.emitSuccess)({
                command: "task new",
                format,
                text: renderLightweightTaskNewText(result, repositoryContext.root, workflowProvenance.workflowCliCommand),
                data: {
                    repositoryRoot: repositoryContext.root,
                    detectionSource: repositoryContext.detectionSource,
                    mode: "lightweight",
                    slice: result.slice,
                    planningDepth: result.planningDepth,
                    taskSlug: result.taskSlug,
                    taskTitle: result.taskTitle,
                    paths: {
                        sliceOverviewPath: result.sliceOverviewPath,
                        tasksDirectoryPath: (0, paths_1.toRepositoryRelativePath)(repositoryContext.root, result.tasksDirectoryPath),
                        taskDirectoryPath: (0, paths_1.toRepositoryRelativePath)(repositoryContext.root, result.taskDirectoryPath),
                        taskDefinitionPath: (0, paths_1.toRepositoryRelativePath)(repositoryContext.root, result.taskDefinitionPath),
                        implementationSummaryPath: (0, paths_1.toRepositoryRelativePath)(repositoryContext.root, result.implementationSummaryPath)
                    },
                    actions: {
                        tasksDirectory: result.tasksDirectoryAction,
                        taskDefinition: result.taskDefinitionAction,
                        implementationSummary: result.implementationSummaryAction
                    },
                    contributingSpecIds: result.contributingSpecIds,
                    requiresRefinement: result.requiresRefinement,
                    application: result.application,
                    workflowProvenance: {
                        method: workflowProvenance.workflowProvenance,
                        cliCommand: workflowProvenance.workflowCliCommand
                    },
                    commandWriteSummary: persistedArtifactLicenseReminder.commandWriteSummary,
                    persistedArtifactLicenseReminder
                }
            });
            return;
        }
        if (options.sliceOverview !== undefined) {
            throw (0, errors_1.createUsageError)("Cannot use --slice-overview without --lightweight.", ["Use --milestone-overview for standard task creation or add --lightweight for slice-parented task creation."]);
        }
        if (options.milestoneOverview === undefined || String(options.milestoneOverview).trim() === "") {
            throw (0, errors_1.createUsageError)("Missing required --milestone-overview option.", ["Provide --milestone-overview for standard task generation or use --lightweight --slice-overview for lightweight task generation."]);
        }
        if (options.fullSet === true) {
            const result = (0, full_set_expansion_1.createTaskFullSetWorkspaces)(repositoryContext.root, {
                milestoneOverviewPath: options.milestoneOverview,
                recoverScaffold: options.recoverScaffold
            });
            const persistedArtifactLicenseReminder = (0, persisted_artifact_reminder_1.applyPlanningCommandPersistedArtifactReminderWrites)({
                repositoryContext,
                commandWriteSummary: result.commandWriteSummary,
                format
            });
            (0, output_1.emitSuccess)({
                command: "task new",
                format,
                text: renderTaskFullSetText(result, repositoryContext.root, result.workflowCliCommand),
                findings: result.taskWorkspaces.flatMap((workspace) => [
                    ...workspace.refinementFindings
                ]),
                data: {
                    repositoryRoot: repositoryContext.root,
                    detectionSource: repositoryContext.detectionSource,
                    mode: "full-set",
                    milestoneOverviewPath: result.milestoneOverviewPath,
                    declaredTaskSlugs: result.declaredTaskSlugs,
                    createdCount: result.createdCount,
                    keptCount: result.keptCount,
                    refreshedCount: result.refreshedCount,
                    requiresRefinement: result.requiresRefinement,
                    application: result.application,
                    taskWorkspaces: result.taskWorkspaces.map((workspace) => ({
                        slice: workspace.slice,
                        phase: workspace.phase,
                        milestone: workspace.milestone,
                        planningDepth: workspace.planningDepth,
                        taskSlug: workspace.taskSlug,
                        taskTitle: workspace.taskTitle,
                        paths: {
                            milestoneOverviewPath: workspace.milestoneOverviewPath,
                            tasksDirectoryPath: (0, paths_1.toRepositoryRelativePath)(repositoryContext.root, workspace.tasksDirectoryPath),
                            taskDirectoryPath: (0, paths_1.toRepositoryRelativePath)(repositoryContext.root, workspace.taskDirectoryPath),
                            taskDefinitionPath: (0, paths_1.toRepositoryRelativePath)(repositoryContext.root, workspace.taskDefinitionPath),
                            implementationSummaryPath: (0, paths_1.toRepositoryRelativePath)(repositoryContext.root, workspace.implementationSummaryPath)
                        },
                        actions: {
                            tasksDirectory: workspace.tasksDirectoryAction,
                            taskDefinition: workspace.taskDefinitionAction,
                            implementationSummary: workspace.implementationSummaryAction
                        },
                        contributingSpecIds: workspace.contributingSpecIds,
                        requiresRefinement: workspace.requiresRefinement,
                        refinementFindings: workspace.refinementFindings,
                        scaffoldEvidence: workspace.scaffoldEvidence,
                        scaffoldProjection: workspace.scaffoldProjection
                    })),
                    workflowProvenance: {
                        method: "cli",
                        cliCommand: result.workflowCliCommand
                    },
                    commandWriteSummary: persistedArtifactLicenseReminder.commandWriteSummary,
                    persistedArtifactLicenseReminder
                }
            });
            return;
        }
        if (options.taskSlug === undefined || options.taskSlug === null || String(options.taskSlug).trim() === "") {
            throw (0, errors_1.createUsageError)("Missing required --task-slug option.", ["Provide --task-slug for single task generation or add --full-set to expand declared tasks."]);
        }
        const result = (0, task_generation_1.createTaskWorkspace)(repositoryContext.root, {
            milestoneOverviewPath: options.milestoneOverview,
            taskSlug: options.taskSlug,
            taskTitle: options.taskTitle,
            recoverScaffold: options.recoverScaffold
        });
        const persistedArtifactLicenseReminder = (0, persisted_artifact_reminder_1.applyPlanningCommandPersistedArtifactReminderWrites)({
            repositoryContext,
            commandWriteSummary: result.commandWriteSummary,
            format
        });
        const workflowProvenance = (0, workflow_provenance_1.buildCliWorkflowProvenance)(`day-shift task new --milestone-overview ${result.milestoneOverviewPath} --task-slug ${result.taskSlug}`);
        (0, output_1.emitSuccess)({
            command: "task new",
            format,
            text: renderTaskNewText(result, repositoryContext.root, workflowProvenance.workflowCliCommand),
            findings: [...result.refinementFindings],
            data: {
                repositoryRoot: repositoryContext.root,
                detectionSource: repositoryContext.detectionSource,
                slice: result.slice,
                phase: result.phase,
                milestone: result.milestone,
                planningDepth: result.planningDepth,
                taskSlug: result.taskSlug,
                taskTitle: result.taskTitle,
                paths: {
                    milestoneOverviewPath: result.milestoneOverviewPath,
                    tasksDirectoryPath: (0, paths_1.toRepositoryRelativePath)(repositoryContext.root, result.tasksDirectoryPath),
                    taskDirectoryPath: (0, paths_1.toRepositoryRelativePath)(repositoryContext.root, result.taskDirectoryPath),
                    taskDefinitionPath: (0, paths_1.toRepositoryRelativePath)(repositoryContext.root, result.taskDefinitionPath),
                    implementationSummaryPath: (0, paths_1.toRepositoryRelativePath)(repositoryContext.root, result.implementationSummaryPath)
                },
                actions: {
                    tasksDirectory: result.tasksDirectoryAction,
                    taskDefinition: result.taskDefinitionAction,
                    implementationSummary: result.implementationSummaryAction
                },
                contributingSpecIds: result.contributingSpecIds,
                requiresRefinement: result.requiresRefinement,
                refinementFindings: result.refinementFindings,
                scaffoldEvidence: result.scaffoldEvidence,
                scaffoldProjection: result.scaffoldProjection,
                application: result.application,
                workflowProvenance: {
                    method: workflowProvenance.workflowProvenance,
                    cliCommand: workflowProvenance.workflowCliCommand
                },
                commandWriteSummary: persistedArtifactLicenseReminder.commandWriteSummary,
                persistedArtifactLicenseReminder
            }
        });
    });
    (0, output_1.attachCommandRuntimeSemantics)(command, exports.TASK_NEW_RUNTIME_SEMANTICS);
    return command;
}
function renderLightweightTaskNewText(result, repositoryRoot, workflowCliCommand) {
    return [
        "Lightweight task workspace is ready.",
        "Mode: lightweight",
        `Slice: ${result.slice}`,
        `Task slug: ${result.taskSlug}`,
        `Task title: ${result.taskTitle}`,
        `Slice overview: ${result.sliceOverviewPath}`,
        `Tasks directory: ${(0, paths_1.toRepositoryRelativePath)(repositoryRoot, result.tasksDirectoryPath)} (${result.tasksDirectoryAction})`,
        `Task definition: ${(0, paths_1.toRepositoryRelativePath)(repositoryRoot, result.taskDefinitionPath)} (${result.taskDefinitionAction})`,
        `Implementation summary: ${(0, paths_1.toRepositoryRelativePath)(repositoryRoot, result.implementationSummaryPath)} (${result.implementationSummaryAction})`,
        `Contributing specs: ${result.contributingSpecIds.join(", ")}`,
        `Refinement required: ${result.requiresRefinement ? "yes" : "no"}.`,
        `Scaffolded via: ${workflowCliCommand}`
    ].join("\n");
}
function renderTaskNewText(result, repositoryRoot, workflowCliCommand) {
    return [
        "Task workspace is ready.",
        `Slice: ${result.slice}`,
        `Phase: ${result.phase}`,
        `Milestone: ${result.milestone}`,
        `Task slug: ${result.taskSlug}`,
        `Task title: ${result.taskTitle}`,
        `Milestone overview: ${result.milestoneOverviewPath}`,
        `Tasks directory: ${(0, paths_1.toRepositoryRelativePath)(repositoryRoot, result.tasksDirectoryPath)} (${result.tasksDirectoryAction})`,
        `Task definition: ${(0, paths_1.toRepositoryRelativePath)(repositoryRoot, result.taskDefinitionPath)} (${result.taskDefinitionAction})`,
        `Implementation summary: ${(0, paths_1.toRepositoryRelativePath)(repositoryRoot, result.implementationSummaryPath)} (${result.implementationSummaryAction})`,
        `Contributing specs: ${result.contributingSpecIds.join(", ")}`,
        `Refinement required: ${result.requiresRefinement ? "yes" : "no"}.`,
        ...result.refinementFindings.map((finding) => `- ${finding.message}`),
        `Write outcome: ${result.application.outcome}`,
        `Scaffolded via: ${workflowCliCommand}`
    ].join("\n");
}
function renderTaskFullSetText(result, repositoryRoot, workflowCliCommand) {
    return [
        "Task full-set expansion is ready.",
        `Milestone overview: ${result.milestoneOverviewPath}`,
        `Declared tasks: ${result.declaredTaskSlugs.join(", ")}`,
        `Created: ${result.createdCount}`,
        `Kept: ${result.keptCount}`,
        `Refreshed: ${result.refreshedCount}`,
        `Refinement required: ${result.requiresRefinement ? "yes" : "no"}.`,
        ...result.taskWorkspaces.flatMap((workspace) => workspace.refinementFindings.map((finding) => `- ${finding.message}`)),
        `Write outcome: ${result.application.outcome}`,
        "Task workspaces:",
        ...result.taskWorkspaces.map((workspace) => {
            return [
                `- ${workspace.taskSlug}`,
                `  Task title: ${workspace.taskTitle}`,
                `  Task definition: ${(0, paths_1.toRepositoryRelativePath)(repositoryRoot, workspace.taskDefinitionPath)} (${workspace.taskDefinitionAction})`,
                `  Implementation summary: ${(0, paths_1.toRepositoryRelativePath)(repositoryRoot, workspace.implementationSummaryPath)} (${workspace.implementationSummaryAction})`
            ].join("\n");
        }),
        `Scaffolded via: ${workflowCliCommand}`
    ].join("\n");
}
