"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveWorkflowTemplateCreateDraft = resolveWorkflowTemplateCreateDraft;
exports.resolveWorkflowTemplateUpdateDraft = resolveWorkflowTemplateUpdateDraft;
const node_path_1 = require("node:path");
const control_plane_config_1 = require("../config/control-plane-config");
const catalog_1 = require("../i18n/catalog");
const runtime_1 = require("../worker/runtime");
const template_registry_1 = require("../workflows/template-registry");
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_worker_context_1 = require("./workflow-template-worker-context");
async function resolveWorkflowTemplateCreateDraft(input) {
    if (input.args.mode === "manual") {
        return {
            command: "create",
            templateSet: false,
            items: [
                {
                    action: "create_new",
                    workflowTemplatePath: input.args.workflowTemplatePath,
                    description: (0, workflow_template_command_support_1.normalizeWorkflowTemplateDescription)(input.args.description),
                    requiredSkills: (0, workflow_template_command_support_1.normalizeWorkflowTemplateRequiredSkills)(input.args.requiredSkills ?? [], input.locale),
                    requiredMcp: (0, workflow_template_command_support_1.normalizeWorkflowTemplateRequiredMcp)(input.args.requiredMcp ?? [], input.locale),
                    targets: (0, workflow_template_command_support_1.normalizeWorkflowTemplateTargets)(input.args.targets, input.locale),
                    autoSelect: (0, workflow_template_command_support_1.normalizeWorkflowTemplateAutoSelect)(input.args.autoSelect),
                    body: input.args.body === undefined
                        ? buildWorkflowCreateScaffold(input.args.workflowTemplatePath, input.locale)
                        : await (0, workflow_template_command_support_1.loadWorkflowTemplateBody)(input.args.body),
                },
            ],
        };
    }
    const explicitOverrides = resolveWorkflowCreateExplicitOverrides(input.args, input.locale);
    if (explicitOverrides.workflowTemplatePath !== undefined) {
        (0, workflow_template_command_support_1.ensureWorkflowTemplateCreateTargetIsAvailable)(input.catalog, explicitOverrides.workflowTemplatePath, input.locale);
    }
    if (input.config === null ||
        (0, control_plane_config_1.resolveWorkersForPurpose)(input.config, "thinking").length === 0) {
        throw new Error((0, catalog_1.translate)(input.locale, "workflow.command.create.noWorker"));
    }
    if (explicitOverrides.requiredSkills !== undefined) {
        (0, workflow_template_command_support_1.ensureWorkflowTemplateRequiredSkillsAreUsable)(explicitOverrides.requiredSkills, await (0, workflow_template_command_support_1.resolveWorkflowTemplateRequiredSkillInventory)({
            cwd: input.cwd,
            config: input.config,
        }), input.locale);
    }
    const workerRuntime = await (0, runtime_1.createConfiguredWorkerRuntime)(input.config);
    const structuredOverrides = buildWorkerTemplateDraftStructuredOverrides(explicitOverrides);
    const templateSet = input.args.templateSet === true;
    const workerCatalog = filterWorkerVisibleWorkflowTemplateCatalog(input.catalog);
    const draftInput = {
        prompt: input.args.prompt,
        outputLanguage: input.config.i18n.defaultLanguage,
        ...(templateSet ? { templateSet: true } : {}),
        existingWorkflowTemplatePaths: workerCatalog.templates.map((template) => template.templatePath),
        existingWorkflowTemplates: (0, workflow_template_worker_context_1.buildWorkerTemplateCatalogEntries)(workerCatalog),
        maxNestedWorkflowDepth: input.config.maxNestedWorkflowDepth ??
            control_plane_config_1.DEFAULT_CONFIG.maxNestedWorkflowDepth,
        explicitTemplateOverridesSummary: buildWorkerTemplateDraftExplicitOverridesSummary(explicitOverrides),
        ...(Object.keys(structuredOverrides).length > 0
            ? { explicitTemplateOverrides: structuredOverrides }
            : {}),
        workspacePath: input.cwd,
        repositoryRoot: input.cwd,
    };
    const draftResult = await workerRuntime.runTemplateDraft(draftInput);
    if (draftResult.kind === "deferred") {
        throw new Error((0, catalog_1.translate)(input.locale, "workflow.command.create.workerDeferred", {
            cooldownUntil: draftResult.cooldownUntil ?? "-",
        }));
    }
    const draftSet = templateSet
        ? (0, workflow_template_change_set_1.workflowTemplateChangeSetFromWorkerDraft)({
            command: "create",
            templateSet: true,
            sourcePrompt: input.args.prompt,
            draft: draftResult.launchResult.draft,
        })
        : {
            command: "create",
            templateSet: false,
            sourcePrompt: input.args.prompt,
            items: [
                mergeWorkflowCreateDraftWithExplicitOverrides(expectSingleWorkerTemplateDraft(draftResult.launchResult.draft), explicitOverrides, input.locale),
            ],
        };
    const attachedDraftSet = (0, workflow_template_change_set_1.attachWorkflowTemplateUpdateBaseDigests)(draftSet, input.catalog);
    return attachedDraftSet;
}
async function resolveWorkflowTemplateUpdateDraft(input) {
    if (input.config === null ||
        (0, control_plane_config_1.resolveWorkersForPurpose)(input.config, "thinking").length === 0) {
        throw new Error((0, catalog_1.translate)(input.locale, "workflow.command.update.noWorker"));
    }
    const templatePath = (0, workflow_template_command_support_1.normalizeWorkflowTemplateCommandPath)(input.args.workflowTemplatePath, input.locale);
    const targetTemplate = input.catalog.templateByPath.get(templatePath);
    if (targetTemplate === undefined) {
        throw new Error((0, catalog_1.translate)(input.locale, "workflow.command.update.missingPath", {
            templatePath,
        }));
    }
    const targetUpdateMode = targetTemplate.updateMode ?? template_registry_1.DEFAULT_WORKFLOW_TEMPLATE_UPDATE_MODE;
    if (input.args.templateSet === true) {
        if (targetUpdateMode !== "flexible") {
            throw new Error((0, catalog_1.translate)(input.locale, "workflow.command.template.updateModeBlocked", {
                templatePath,
                updateMode: targetUpdateMode,
            }));
        }
        return resolveWorkflowUpdateTemplateSetDraft({
            ...input,
            config: input.config,
            templatePath,
            targetTemplate,
        });
    }
    if (targetUpdateMode === "disabled") {
        throw new Error((0, catalog_1.translate)(input.locale, "workflow.command.template.updateModeBlocked", {
            templatePath,
            updateMode: targetUpdateMode,
        }));
    }
    const workerCatalog = filterWorkerVisibleWorkflowTemplateCatalog(input.catalog);
    const updateInput = {
        prompt: input.args.prompt,
        outputLanguage: input.config.i18n.defaultLanguage,
        currentTemplate: {
            path: targetTemplate.templatePath,
            description: targetTemplate.metadata?.description ?? null,
            requiredSkills: targetTemplate.metadata?.requiredSkills ?? [],
            requiredMcp: targetTemplate.metadata?.requiredMcp ?? [],
            targets: (0, template_registry_1.resolveWorkflowTemplateRecordTargets)(targetTemplate),
            autoSelect: targetTemplate.metadata?.autoSelect ??
                targetTemplate.autoSelect ??
                true,
            body: targetTemplate.body,
            digest: targetTemplate.digest,
        },
        existingWorkflowTemplatePaths: workerCatalog.templates.map((template) => template.templatePath),
        existingWorkflowTemplates: (0, workflow_template_worker_context_1.buildWorkerTemplateCatalogEntries)(workerCatalog),
        workflowTemplateContext: (0, workflow_template_worker_context_1.buildWorkerTemplateImpactContext)(input.catalog, targetTemplate.templatePath),
        maxNestedWorkflowDepth: input.maxNestedWorkflowDepth,
        workspacePath: input.cwd,
        repositoryRoot: input.cwd,
    };
    const workerRuntime = await (0, runtime_1.createConfiguredWorkerRuntime)(input.config);
    const updateResult = await workerRuntime.runTemplateUpdate(updateInput);
    if (updateResult.kind === "deferred") {
        throw new Error((0, catalog_1.translate)(input.locale, "workflow.command.update.workerDeferred", {
            cooldownUntil: updateResult.cooldownUntil ?? "-",
        }));
    }
    const updateContent = updateResult.launchResult.update;
    const normalizedUpdateContent = (0, workflow_template_command_support_1.normalizeWorkflowTemplateContentSource)({
        description: updateContent.description,
        requiredSkills: updateContent.requiredSkills,
        requiredMcp: updateContent.requiredMcp,
        targets: updateContent.targets,
        autoSelect: updateContent.autoSelect,
        body: updateContent.body,
    }, input.locale, { bodyValidationOrder: "before-fields" });
    const draftSet = {
        command: "update",
        templateSet: false,
        sourcePrompt: input.args.prompt,
        items: [
            {
                action: "update_existing",
                targetWorkflowTemplatePath: templatePath,
                workflowTemplatePath: templatePath,
                ...normalizedUpdateContent,
                baseDigest: targetTemplate.digest,
            },
        ],
    };
    return draftSet;
}
async function resolveWorkflowUpdateTemplateSetDraft(input) {
    const workerCatalog = filterWorkerVisibleWorkflowTemplateCatalog(input.catalog);
    const draftInput = {
        prompt: input.args.prompt,
        outputLanguage: input.config.i18n.defaultLanguage,
        templateSet: true,
        anchorTemplate: {
            path: input.targetTemplate.templatePath,
            description: input.targetTemplate.metadata?.description ?? null,
            requiredSkills: input.targetTemplate.metadata?.requiredSkills ?? [],
            requiredMcp: input.targetTemplate.metadata?.requiredMcp ?? [],
            targets: (0, template_registry_1.resolveWorkflowTemplateRecordTargets)(input.targetTemplate),
            autoSelect: input.targetTemplate.metadata?.autoSelect ??
                input.targetTemplate.autoSelect ??
                true,
            body: input.targetTemplate.body,
            digest: input.targetTemplate.digest,
        },
        existingWorkflowTemplatePaths: workerCatalog.templates.map((template) => template.templatePath),
        existingWorkflowTemplates: (0, workflow_template_worker_context_1.buildWorkerTemplateCatalogEntries)(workerCatalog),
        maxNestedWorkflowDepth: input.maxNestedWorkflowDepth,
        explicitTemplateOverridesSummary: "(none)",
        workspacePath: input.cwd,
        repositoryRoot: input.cwd,
    };
    const workerRuntime = await (0, runtime_1.createConfiguredWorkerRuntime)(input.config);
    const draftResult = await workerRuntime.runTemplateDraft(draftInput);
    if (draftResult.kind === "deferred") {
        throw new Error((0, catalog_1.translate)(input.locale, "workflow.command.update.workerDeferred", {
            cooldownUntil: draftResult.cooldownUntil ?? "-",
        }));
    }
    const draftSet = (0, workflow_template_change_set_1.attachWorkflowTemplateUpdateBaseDigests)((0, workflow_template_change_set_1.workflowTemplateChangeSetFromWorkerDraft)({
        command: "update",
        templateSet: true,
        sourcePrompt: input.args.prompt,
        anchorPath: input.templatePath,
        draft: draftResult.launchResult.draft,
    }), input.catalog);
    return draftSet;
}
function filterWorkerVisibleWorkflowTemplateCatalog(catalog) {
    const templates = catalog.templates.filter((template) => (template.updateMode ?? template_registry_1.DEFAULT_WORKFLOW_TEMPLATE_UPDATE_MODE) ===
        "flexible");
    return {
        templates,
        templateByPath: new Map(templates.map((template) => [template.templatePath, template])),
    };
}
function buildWorkflowCreateScaffold(workflowTemplatePath, locale) {
    switch (locale) {
        case "ja":
            return [
                "# ワークフローテンプレート",
                "",
                "## 目的",
                "",
                "再利用可能な issue 作業を、明確な手順、人への引き継ぎ条件、観測可能な成功条件に沿って進める。",
                "",
                "## ルール",
                "",
                "### やること",
                "",
                "- すべてのワークフローステップでテンプレートのルールに従う。",
                "- リポジトリ文脈と依頼された範囲に沿って進める。",
                "",
                "### やらないこと",
                "",
                "- リポジトリの事実を推測したり、対象作業の種類を超えて範囲を広げたりしない。",
                "- 人の判断や利用できない認証情報が必要な場合に続行しない。",
                "",
                "## 必須プロセス",
                "",
                "### 1. 依頼を理解する",
                "",
                "- issue、現在のワークフロー状態、関連するリポジトリ指示を読む。",
                "- 期待される結果、制約、検証要件を特定する。",
                "",
                "### 2. ワークフローを完了する",
                "",
                "- ワークフローの目的を満たす最小のプロセスを実行する。",
                "- 結果を検証し、残リスクやブロッカーを記録する。",
                "",
                "## 人へ引き継ぐ条件",
                "",
                "- 利用可能な文脈を確認しても依頼が曖昧な場合。",
                "- 完了に認証情報、承認、またはプロダクト判断が必要な場合。",
                "",
                "## 成功条件",
                "",
                "- ワークフローの目的が満たされるか、具体的なブロッカーが報告されている。",
                "- 最終結果に実施した検証と残リスクが含まれている。",
            ].join("\n");
        case "zh":
            return [
                "# 工作流模板",
                "",
                "## 目标",
                "",
                "通过清晰步骤、人工介入条件和可观察的成功标准指导可复用的 issue 工作。",
                "",
                "## 规则",
                "",
                "### 要做",
                "",
                "- 在每个工作流步骤中遵循模板规则。",
                "- 保持工作符合仓库上下文和请求范围。",
                "",
                "### 不要做",
                "",
                "- 不要编造仓库事实，也不要把工作扩展到请求的工作类型之外。",
                "- 当需要人工判断或不可用凭据时不要继续。",
                "",
                "## 必要流程",
                "",
                "### 1. 理解请求",
                "",
                "- 阅读 issue、当前工作流状态和相关仓库说明。",
                "- 确定预期结果、约束和验证需求。",
                "",
                "### 2. 完成工作流",
                "",
                "- 执行满足工作流目标的最小流程。",
                "- 验证结果并记录剩余风险或阻塞项。",
                "",
                "## 需要人工介入时",
                "",
                "- 查看可用上下文后请求仍然不明确。",
                "- 完成工作需要凭据、批准或产品判断。",
                "",
                "## 成功标准",
                "",
                "- 工作流目标已满足，或报告了具体阻塞项。",
                "- 最终结果包含已执行的验证和剩余风险。",
            ].join("\n");
        case "en":
            return buildEnglishWorkflowCreateScaffold(workflowTemplatePath);
    }
}
function buildEnglishWorkflowCreateScaffold(workflowTemplatePath) {
    const title = buildWorkflowCreateTitle(workflowTemplatePath);
    return [
        `# ${title}`,
        "",
        "## Goal",
        "",
        "Guide reusable issue work through clear steps, human handoff conditions, and observable success criteria.",
        "",
        "## Rules",
        "",
        "### Do",
        "",
        "- Follow the template rules throughout every workflow step.",
        "- Keep the workflow aligned with the repository context and requested scope.",
        "",
        "### Do Not",
        "",
        "- Do not invent repository facts or expand the workflow beyond the requested class of work.",
        "- Do not continue when human judgment or unavailable credentials are required.",
        "",
        "## Required Process",
        "",
        "### 1. Understand The Request",
        "",
        "- Read the issue, current workflow state, and relevant repository instructions.",
        "- Identify the intended outcome, constraints, and verification needs.",
        "",
        "### 2. Complete The Workflow",
        "",
        "- Carry out the smallest process that satisfies the workflow goal.",
        "- Verify the result and record any remaining risks or blockers.",
        "",
        "## Handoff To Human When",
        "",
        "- The request remains ambiguous after reviewing available context.",
        "- Completing the workflow requires credentials, approvals, or product judgment.",
        "",
        "## Success Criteria",
        "",
        "- The workflow goal is satisfied or a concrete blocker is reported.",
        "- The final result includes verification performed and remaining risk.",
    ].join("\n");
}
function buildWorkflowCreateTitle(workflowTemplatePath) {
    const fileName = (0, node_path_1.basename)(workflowTemplatePath, ".md");
    const words = fileName
        .replace(/[._-]+/gu, " ")
        .trim()
        .split(/\s+/u)
        .filter((value) => value.length > 0);
    if (words.length === 0) {
        return "Workflow Template";
    }
    return words.map((word) => word[0]?.toUpperCase() + word.slice(1)).join(" ");
}
function resolveWorkflowCreateExplicitOverrides(args, locale) {
    const overrides = {};
    if (args.workflowTemplatePath !== undefined) {
        overrides.workflowTemplatePath = (0, workflow_template_command_support_1.normalizeWorkflowTemplateCommandPath)(args.workflowTemplatePath, locale);
    }
    if (args.description !== undefined) {
        overrides.description = (0, workflow_template_command_support_1.normalizeWorkflowTemplateDescription)(args.description);
    }
    if (args.requiredSkills !== undefined) {
        overrides.requiredSkills = (0, workflow_template_command_support_1.normalizeWorkflowTemplateRequiredSkills)(args.requiredSkills, locale);
    }
    if (args.requiredMcp !== undefined) {
        overrides.requiredMcp = (0, workflow_template_command_support_1.normalizeWorkflowTemplateRequiredMcp)(args.requiredMcp, locale);
    }
    if (args.targets !== undefined) {
        overrides.targets = (0, workflow_template_command_support_1.normalizeWorkflowTemplateTargets)(args.targets, locale);
    }
    if (args.autoSelect !== undefined) {
        overrides.autoSelect = (0, workflow_template_command_support_1.normalizeWorkflowTemplateAutoSelect)(args.autoSelect);
    }
    return overrides;
}
function buildWorkerTemplateDraftExplicitOverridesSummary(overrides) {
    const summary = {};
    if (overrides.workflowTemplatePath !== undefined) {
        summary.workflowTemplatePath = overrides.workflowTemplatePath;
    }
    if (Object.hasOwn(overrides, "description")) {
        summary.description = overrides.description ?? null;
    }
    if (overrides.requiredSkills !== undefined) {
        summary.requiredSkills = overrides.requiredSkills;
    }
    if (overrides.requiredMcp !== undefined) {
        summary.requiredMcp = overrides.requiredMcp;
    }
    if (overrides.targets !== undefined) {
        summary.targets = overrides.targets;
    }
    if (overrides.autoSelect !== undefined) {
        summary.autoSelect = overrides.autoSelect;
    }
    return Object.keys(summary).length === 0
        ? "(none)"
        : JSON.stringify(summary, null, 2);
}
function buildWorkerTemplateDraftStructuredOverrides(overrides) {
    return {
        ...(overrides.workflowTemplatePath !== undefined
            ? { path: overrides.workflowTemplatePath }
            : {}),
        ...(Object.hasOwn(overrides, "description")
            ? { description: overrides.description ?? null }
            : {}),
        ...(overrides.requiredSkills !== undefined
            ? { requiredSkills: overrides.requiredSkills }
            : {}),
        ...(overrides.requiredMcp !== undefined
            ? { requiredMcp: overrides.requiredMcp }
            : {}),
        ...(overrides.targets !== undefined ? { targets: overrides.targets } : {}),
        ...(overrides.autoSelect !== undefined
            ? { autoSelect: overrides.autoSelect }
            : {}),
    };
}
function mergeWorkflowCreateDraftWithExplicitOverrides(draft, overrides, locale) {
    const changeDraft = (0, workflow_template_change_set_1.workflowTemplateChangeDraftFromWorkerDraft)(draft);
    if (changeDraft.action === "reuse_existing") {
        return changeDraft;
    }
    if (changeDraft.action === "update_existing") {
        return {
            ...changeDraft,
            description: Object.hasOwn(overrides, "description")
                ? (overrides.description ?? null)
                : (0, workflow_template_command_support_1.normalizeWorkflowTemplateDescription)(changeDraft.description ?? undefined),
            requiredSkills: overrides.requiredSkills ??
                (0, workflow_template_command_support_1.normalizeWorkflowTemplateRequiredSkills)(changeDraft.requiredSkills, locale),
            requiredMcp: overrides.requiredMcp ??
                (0, workflow_template_command_support_1.normalizeWorkflowTemplateRequiredMcp)(changeDraft.requiredMcp, locale),
            targets: overrides.targets ??
                (0, workflow_template_command_support_1.normalizeWorkflowTemplateTargets)(changeDraft.targets, locale),
            autoSelect: overrides.autoSelect ??
                (0, workflow_template_command_support_1.normalizeWorkflowTemplateAutoSelect)(changeDraft.autoSelect),
        };
    }
    if (changeDraft.action === "delete_existing") {
        throw new Error("Unexpected workflow template delete draft.");
    }
    return {
        ...changeDraft,
        workflowTemplatePath: overrides.workflowTemplatePath ?? changeDraft.workflowTemplatePath,
        description: Object.hasOwn(overrides, "description")
            ? (overrides.description ?? null)
            : (0, workflow_template_command_support_1.normalizeWorkflowTemplateDescription)(changeDraft.description ?? undefined),
        requiredSkills: overrides.requiredSkills ??
            (0, workflow_template_command_support_1.normalizeWorkflowTemplateRequiredSkills)(changeDraft.requiredSkills, locale),
        requiredMcp: overrides.requiredMcp ??
            (0, workflow_template_command_support_1.normalizeWorkflowTemplateRequiredMcp)(changeDraft.requiredMcp, locale),
        targets: overrides.targets ??
            (0, workflow_template_command_support_1.normalizeWorkflowTemplateTargets)(changeDraft.targets, locale),
        autoSelect: overrides.autoSelect ??
            (0, workflow_template_command_support_1.normalizeWorkflowTemplateAutoSelect)(changeDraft.autoSelect),
    };
}
function expectSingleWorkerTemplateDraft(draft) {
    if (typeof draft === "object" && draft !== null && "items" in draft) {
        throw new Error("Unexpected workflow template set draft.");
    }
    return draft;
}
