"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.runWorkflowTemplateMutationCommand = runWorkflowTemplateMutationCommand;
exports.runWorkflowTemplateMutation = runWorkflowTemplateMutation;
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 draft_file_support_1 = require("./draft-file-support");
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");
async function runWorkflowTemplateMutationCommand(input) {
    return runWorkflowTemplateMutation({
        cwd: input.cwd,
        locale: input.locale,
        command: input.command,
        saveDraft: input.args.mode !== "apply-draft" && input.args.saveDraft === true,
        validateInitialCatalog: input.validateInitialCatalog,
        ...(input.homeDirectory !== undefined
            ? { homeDirectory: input.homeDirectory }
            : {}),
        loadDraft: async (context) => {
            if (input.args.mode === "apply-draft") {
                return loadWorkflowTemplateMutationDraftFile({
                    command: input.command,
                    applyDraftPath: input.args.applyDraftPath,
                    locale: input.locale,
                });
            }
            return input.resolveDraft(context, input.args);
        },
    });
}
async function runWorkflowTemplateMutation(input) {
    const config = await (0, control_plane_config_1.loadConfig)(input.cwd).catch(() => null);
    const workflowTemplatesDirectory = (0, template_registry_1.getWorkflowTemplatesDirectoryPath)(input.cwd);
    const catalog = await (0, workflow_template_command_support_1.loadWorkflowTemplateCommandCatalog)(workflowTemplatesDirectory, input.locale);
    const maxNestedWorkflowDepth = config?.maxNestedWorkflowDepth ?? control_plane_config_1.DEFAULT_CONFIG.maxNestedWorkflowDepth;
    if (input.validateInitialCatalog) {
        (0, workflow_template_command_support_1.ensureWorkflowTemplateCatalogIsValid)(catalog, maxNestedWorkflowDepth, input.locale);
    }
    const draft = await input.loadDraft({
        config,
        catalog,
        maxNestedWorkflowDepth,
    });
    if (input.saveDraft) {
        const prepared = await prepareAndValidateWorkflowTemplateChangeSet({
            cwd: input.cwd,
            config,
            draft,
            workflowTemplatesDirectory,
            maxNestedWorkflowDepth,
            locale: input.locale,
            validateInitialCatalog: input.validateInitialCatalog,
        });
        const preparedAt = new Date().toISOString();
        const reusableDraft = (0, workflow_template_change_set_1.buildWorkflowTemplateChangeSetDraftFile)({
            preparedAt,
            prepared,
        });
        const applyDraftPath = await (0, draft_file_support_1.writeMachineLocalReusableDraft)({
            draftJson: (0, workflow_template_draft_file_1.stringifyWorkflowTemplateDraftFile)(reusableDraft),
            command: `workflow-${input.command}`,
            preparedAt,
            title: resolveWorkflowTemplateDraftTitle(prepared),
            cwd: input.cwd,
            ...(config !== null ? { trackedProject: config } : {}),
            ...(input.homeDirectory !== undefined
                ? { homeDirectory: input.homeDirectory }
                : {}),
        });
        console.log((0, workflow_template_change_set_1.renderWorkflowTemplateChangeSetDraftReviewSummary)({
            prepared,
            locale: input.locale,
            applyDraftPath,
        }));
        return 0;
    }
    return (0, workflow_template_command_support_1.withWorkflowTemplateWriteLock)(workflowTemplatesDirectory, input.locale, async () => {
        const currentCatalog = await (0, workflow_template_command_support_1.loadWorkflowTemplateCommandCatalog)(workflowTemplatesDirectory, input.locale);
        if (input.validateInitialCatalog) {
            (0, workflow_template_command_support_1.ensureWorkflowTemplateCatalogIsValid)(currentCatalog, maxNestedWorkflowDepth, input.locale);
        }
        const prepared = await prepareAndValidateWorkflowTemplateChangeSet({
            cwd: input.cwd,
            config,
            draft,
            workflowTemplatesDirectory,
            maxNestedWorkflowDepth,
            locale: input.locale,
            validateInitialCatalog: false,
            catalog: currentCatalog,
        });
        await (0, workflow_template_change_set_1.writePreparedWorkflowTemplateChangeSet)({
            workflowTemplatesDirectory,
            prepared,
            locale: input.locale,
        });
        console.log((0, workflow_template_change_set_1.renderWorkflowTemplateChangeSetSummary)({
            prepared,
            locale: input.locale,
        }));
        if (prepared.items.some((item) => item.action !== "reuse_existing")) {
            console.log((0, catalog_1.translate)(input.locale, "workflow.command.template.publishHint"));
        }
        return 0;
    });
}
async function prepareAndValidateWorkflowTemplateChangeSet(input) {
    const catalog = input.catalog ??
        (await (0, workflow_template_command_support_1.loadWorkflowTemplateCommandCatalog)(input.workflowTemplatesDirectory, input.locale));
    if (input.validateInitialCatalog) {
        (0, workflow_template_command_support_1.ensureWorkflowTemplateCatalogIsValid)(catalog, input.maxNestedWorkflowDepth, input.locale);
    }
    const prepared = await (0, workflow_template_change_set_1.prepareWorkflowTemplateChangeSet)({
        draft: input.draft,
        catalog,
        workflowTemplatesDirectory: input.workflowTemplatesDirectory,
        maxNestedWorkflowDepth: input.maxNestedWorkflowDepth,
        locale: input.locale,
    });
    const skillInventory = await (0, workflow_template_command_support_1.resolveWorkflowTemplateRequiredSkillInventory)({
        cwd: input.cwd,
        config: input.config,
    });
    await validatePreparedWorkflowTemplateChangeSetRequiredSkills({
        cwd: input.cwd,
        config: input.config,
        prepared,
        workflowTemplatesDirectory: input.workflowTemplatesDirectory,
        maxNestedWorkflowDepth: input.maxNestedWorkflowDepth,
        locale: input.locale,
        skillInventory,
    });
    await validatePreparedWorkflowTemplateChangeSetRequiredMcp({
        cwd: input.cwd,
        config: input.config,
        prepared,
        workflowTemplatesDirectory: input.workflowTemplatesDirectory,
        maxNestedWorkflowDepth: input.maxNestedWorkflowDepth,
        locale: input.locale,
        skillInventory,
    });
    await validatePreparedWorkflowTemplateDeletedReferencesRemoved({
        config: input.config,
        prepared,
        workflowTemplatesDirectory: input.workflowTemplatesDirectory,
        locale: input.locale,
    });
    return prepared;
}
async function validatePreparedWorkflowTemplateChangeSetRequiredSkills(input) {
    const candidates = (0, workflow_template_change_set_1.buildWorkflowTemplateCandidateSources)(input.prepared.items);
    if (candidates.length === 0) {
        return;
    }
    await (0, workflow_template_command_support_1.validateWorkflowTemplateCandidateRequiredSkills)({
        workflowTemplatesDirectory: input.workflowTemplatesDirectory,
        candidates,
        maxNestedWorkflowDepth: input.maxNestedWorkflowDepth,
        locale: input.locale,
        skillInventory: input.skillInventory,
    });
}
async function validatePreparedWorkflowTemplateChangeSetRequiredMcp(input) {
    const candidates = (0, workflow_template_change_set_1.buildWorkflowTemplateCandidateSources)(input.prepared.items);
    if (candidates.length === 0) {
        return;
    }
    await (0, workflow_template_command_support_1.validateWorkflowTemplateCandidateRequiredMcp)({
        repoRoot: input.cwd,
        workers: input.config === null ? [] : (0, control_plane_config_1.getConfiguredWorkerProviders)(input.config),
        workflowTemplatesDirectory: input.workflowTemplatesDirectory,
        candidates,
        maxNestedWorkflowDepth: input.maxNestedWorkflowDepth,
        locale: input.locale,
        skillInventory: input.skillInventory,
    });
}
async function validatePreparedWorkflowTemplateDeletedReferencesRemoved(input) {
    const deletedTemplatePaths = input.prepared.items.flatMap((item) => item.action === "delete_existing" ? [item.templatePath] : []);
    if (deletedTemplatePaths.length === 0) {
        return;
    }
    await (0, workflow_template_command_support_1.validateDeletedWorkflowTemplateReferencesRemoved)({
        workflowTemplatesDirectory: input.workflowTemplatesDirectory,
        candidates: (0, workflow_template_change_set_1.buildWorkflowTemplateCandidateSources)(input.prepared.items),
        deletedTemplatePaths,
        config: input.config,
        locale: input.locale,
    });
}
async function loadWorkflowTemplateMutationDraftFile(input) {
    return (0, workflow_template_change_set_1.workflowTemplateChangeSetFromDraftFile)({
        command: input.command,
        draftFile: await (0, workflow_template_draft_file_1.readWorkflowTemplateDraftFile)(input.applyDraftPath, input.locale),
        locale: input.locale,
    });
}
function resolveWorkflowTemplateDraftTitle(prepared) {
    if (prepared.items.length === 1) {
        return prepared.items[0]?.templatePath ?? "workflow-template";
    }
    return prepared.anchorPath ?? "template-set";
}
