"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.runWorkflowDeleteCommand = runWorkflowDeleteCommand;
const control_plane_config_1 = require("../config/control-plane-config");
const catalog_1 = require("../i18n/catalog");
const template_registry_1 = require("../workflows/template-registry");
const template_reference_usages_1 = require("../workflows/template-reference-usages");
const workflow_template_authoring_1 = require("./workflow-template-authoring");
const workflow_template_command_support_1 = require("./workflow-template-command-support");
const workflow_template_change_set_1 = require("./workflow-template-change-set");
const workflow_template_draft_file_1 = require("./workflow-template-draft-file");
const workflow_template_mutation_1 = require("./workflow-template-mutation");
async function runWorkflowDeleteCommand(cwd, args, locale, deps = {}) {
    if (args.mode === "apply-draft") {
        return (0, workflow_template_mutation_1.runWorkflowTemplateMutation)({
            cwd,
            locale,
            command: "delete",
            saveDraft: false,
            validateInitialCatalog: true,
            loadDraft: async (context) => {
                const draft = (0, workflow_template_change_set_1.workflowTemplateChangeSetFromDraftFile)({
                    command: "delete",
                    draftFile: await (0, workflow_template_draft_file_1.readWorkflowTemplateDraftFile)(args.applyDraftPath, locale),
                    locale,
                });
                ensureWorkflowTemplateDeleteDraftShape({
                    draft,
                    catalog: context.catalog,
                    config: context.config,
                    locale,
                });
                return draft;
            },
        });
    }
    const targetPath = (0, template_reference_usages_1.normalizeWorkflowTemplateReferenceTargetPath)(args.workflowTemplatePath);
    if (targetPath === null) {
        console.log((0, catalog_1.translate)(locale, "workflow.command.template.invalidPath", {
            value: args.workflowTemplatePath,
        }));
        return 1;
    }
    const workflowTemplatesDirectory = (0, template_registry_1.getWorkflowTemplatesDirectoryPath)(cwd);
    const catalog = await (0, workflow_template_command_support_1.loadWorkflowTemplateCommandCatalog)(workflowTemplatesDirectory, locale);
    const targetTemplate = catalog.templateByPath.get(targetPath);
    if (targetTemplate === undefined) {
        console.log((0, catalog_1.translate)(locale, "workflow.command.update.missingPath", {
            templatePath: targetPath,
        }));
        return 1;
    }
    if (targetTemplate.source !== "repository" ||
        (0, template_registry_1.isSystemWorkflowTemplatePath)(targetTemplate.templatePath)) {
        console.log((0, catalog_1.translate)(locale, "workflow.command.delete.systemBlocked", {
            templatePath: targetTemplate.templatePath,
        }));
        return 1;
    }
    const config = await (0, control_plane_config_1.loadConfig)(cwd).catch(() => null);
    const usages = (0, template_reference_usages_1.collectWorkflowTemplateReferenceUsages)({
        catalog,
        targetPath,
        includeSystemSources: true,
        config,
    });
    if (usages.length > 0 && !args.cleanupReferences) {
        console.log(formatDeleteBlockedByReferences(locale, targetPath, usages));
        return 1;
    }
    if (args.cleanupReferences) {
        const nonEditableUsages = usages.filter((usage) => !usage.editable);
        if (nonEditableUsages.length > 0) {
            console.log(formatDeleteBlockedByReferences(locale, targetPath, nonEditableUsages));
            return 1;
        }
    }
    if (args.dryRun) {
        console.log((0, catalog_1.translate)(locale, "workflow.command.delete.dryRun", {
            templatePath: targetPath,
        }));
        return 0;
    }
    return (0, workflow_template_mutation_1.runWorkflowTemplateMutation)({
        cwd,
        locale,
        command: "delete",
        saveDraft: args.saveDraft,
        validateInitialCatalog: true,
        ...(deps.homeDirectory !== undefined
            ? { homeDirectory: deps.homeDirectory }
            : {}),
        loadDraft: async (context) => {
            const currentTarget = context.catalog.templateByPath.get(targetPath);
            if (currentTarget === undefined) {
                throw new Error((0, catalog_1.translate)(locale, "workflow.command.update.missingPath", {
                    templatePath: targetPath,
                }));
            }
            if (!args.cleanupReferences || usages.length === 0) {
                return buildWorkflowTemplateDeleteDraft({
                    targetTemplate: currentTarget,
                    items: [],
                });
            }
            return buildWorkflowTemplateCleanupDeleteDraft({
                cwd,
                config: context.config,
                catalog: context.catalog,
                maxNestedWorkflowDepth: context.maxNestedWorkflowDepth,
                targetTemplate: currentTarget,
                usages,
                locale,
            });
        },
    });
}
function buildWorkflowTemplateDeleteDraft(input) {
    return {
        command: "delete",
        templateSet: true,
        sourcePrompt: `Delete workflow template ${input.targetTemplate.templatePath}.`,
        items: [
            ...input.items,
            {
                action: "delete_existing",
                workflowTemplatePath: input.targetTemplate.templatePath,
                baseDigest: input.targetTemplate.digest,
                reason: "Template was explicitly selected for deletion.",
            },
        ],
    };
}
async function buildWorkflowTemplateCleanupDeleteDraft(input) {
    const updateItems = [];
    const referrerPaths = [
        ...new Set(input.usages.flatMap((usage) => usage.sourceType === "template" &&
            usage.sourceTemplatePath !== undefined
            ? [usage.sourceTemplatePath]
            : [])),
    ].sort();
    for (const referrerPath of referrerPaths) {
        const updateDraft = await (0, workflow_template_authoring_1.resolveWorkflowTemplateUpdateDraft)({
            cwd: input.cwd,
            config: input.config,
            catalog: input.catalog,
            args: {
                action: "update",
                mode: "prompt",
                workflowTemplatePath: referrerPath,
                prompt: buildCleanupReferencePrompt({
                    targetPath: input.targetTemplate.templatePath,
                    usages: input.usages.filter((usage) => usage.sourceTemplatePath === referrerPath),
                }),
            },
            locale: input.locale,
            maxNestedWorkflowDepth: input.maxNestedWorkflowDepth,
        });
        updateItems.push(...updateDraft.items.filter((item) => item.action === "update_existing"));
    }
    return buildWorkflowTemplateDeleteDraft({
        targetTemplate: input.targetTemplate,
        items: updateItems,
    });
}
function buildCleanupReferencePrompt(input) {
    return [
        `Remove references to workflow template ${input.targetPath}.`,
        "Keep the template's reusable responsibility intact, remove only obsolete nested workflow calls or reference guidance, and adjust surrounding prose so the result remains coherent.",
        "Do not create new workflow modules or reference the deleted template.",
        "",
        "References to remove:",
        ...input.usages.map((usage) => `- ${usage.usageKind} line ${usage.lineNumber ?? "?"}: ${usage.sourceLine}`),
    ].join("\n");
}
function formatDeleteBlockedByReferences(locale, targetPath, usages) {
    return [
        (0, catalog_1.translate)(locale, "workflow.command.delete.referencesBlocked", {
            templatePath: targetPath,
        }),
        formatReferenceUsageLines(usages),
    ].join("\n");
}
function ensureWorkflowTemplateDeleteDraftShape(input) {
    const deleteItems = input.draft.items.filter((item) => item.action === "delete_existing");
    const unsupportedItem = input.draft.items.find((item) => item.action !== "update_existing" && item.action !== "delete_existing");
    if (deleteItems.length !== 1 || unsupportedItem !== undefined) {
        throwInvalidDeleteDraft(input.locale);
    }
    const [deleteItem] = deleteItems;
    const targetPath = deleteItem?.workflowTemplatePath;
    if (targetPath === undefined) {
        throwInvalidDeleteDraft(input.locale);
    }
    const editableReferrerPaths = new Set((0, template_reference_usages_1.collectWorkflowTemplateReferenceUsages)({
        catalog: input.catalog,
        targetPath,
        includeSystemSources: true,
        config: input.config,
    })
        .filter((usage) => usage.sourceType === "template" &&
        usage.editable &&
        usage.sourceTemplatePath !== undefined)
        .flatMap((usage) => usage.sourceTemplatePath === undefined
        ? []
        : [usage.sourceTemplatePath]));
    for (const item of input.draft.items) {
        if (item.action !== "update_existing") {
            continue;
        }
        if (item.targetWorkflowTemplatePath !== item.workflowTemplatePath ||
            !editableReferrerPaths.has(item.targetWorkflowTemplatePath)) {
            throwInvalidDeleteDraft(input.locale);
        }
    }
}
function throwInvalidDeleteDraft(locale) {
    throw new Error((0, catalog_1.translate)(locale, "workflow.command.template.invalidDraftFile"));
}
function formatReferenceUsageLines(usages) {
    return (0, template_reference_usages_1.formatWorkflowTemplateReferenceUsageTable)(usages);
}
