"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
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");
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/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.")
        .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.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,
                    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
            });
            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),
                data: {
                    repositoryRoot: repositoryContext.root,
                    detectionSource: repositoryContext.detectionSource,
                    mode: "full-set",
                    milestoneOverviewPath: result.milestoneOverviewPath,
                    declaredTaskSlugs: result.declaredTaskSlugs,
                    createdCount: result.createdCount,
                    keptCount: result.keptCount,
                    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
                    })),
                    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
        });
        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),
            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,
                workflowProvenance: {
                    method: workflowProvenance.workflowProvenance,
                    cliCommand: workflowProvenance.workflowCliCommand
                },
                commandWriteSummary: persistedArtifactLicenseReminder.commandWriteSummary,
                persistedArtifactLicenseReminder
            }
        });
    });
    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(", ")}`,
        `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(", ")}`,
        `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}`,
        "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");
}
