"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.loadWorkflowTemplateCatalogOrHandoff = loadWorkflowTemplateCatalogOrHandoff;
exports.resolveWorkflowPlanningTemplateOrHandoff = resolveWorkflowPlanningTemplateOrHandoff;
exports.buildMissingWorkflowTemplateHandoff = buildMissingWorkflowTemplateHandoff;
exports.resolveNestedWorkflowChildTemplateOrHandoff = resolveNestedWorkflowChildTemplateOrHandoff;
exports.resolveWorkflowPlanningArtifacts = resolveWorkflowPlanningArtifacts;
exports.resolveNestedWorkflowPlanningArtifacts = resolveNestedWorkflowPlanningArtifacts;
const nested_workflows_1 = require("./nested-workflows");
const run_context_summaries_1 = require("./run-context-summaries");
const template_links_1 = require("./template-links");
const template_registry_1 = require("./template-registry");
const workflow_template_targets_1 = require("./workflow-template-targets");
const template_bindings_1 = require("./template-bindings");
const required_skills_1 = require("./required-skills");
const required_mcp_1 = require("./required-mcp");
async function loadWorkflowTemplateCatalogOrHandoff(input) {
    try {
        return await (0, template_registry_1.loadWorkflowTemplates)((0, template_registry_1.getWorkflowTemplatesDirectoryPath)(input.repoRoot), input.locale);
    }
    catch (error) {
        return {
            kind: "handoff",
            summary: (0, run_context_summaries_1.buildWorkflowCatalogErrorSummary)(error, input.locale),
            workflowTemplateName: getActiveTemplateName(input.workflowState),
            workflowState: input.workflowState,
        };
    }
}
function resolveWorkflowPlanningTemplateOrHandoff(input) {
    const workflowSurface = input.workflowSurface;
    const workflowSurfaceTargetsTemplates = (0, template_bindings_1.isWorkflowTemplateBindingSurface)(workflowSurface);
    const template = input.catalog.templateByPath.get(input.templateName);
    if (template !== undefined &&
        workflowSurfaceTargetsTemplates &&
        (0, template_registry_1.workflowTemplateTargetsSurface)(template, workflowSurface)) {
        return template;
    }
    return buildMissingWorkflowTemplateHandoff({
        catalog: input.catalog,
        templateName: input.templateName,
        workflowSurface,
        locale: input.locale,
        workflowState: input.workflowState,
        selection: { mode: "template", templatePath: input.templateName },
    });
}
function buildMissingWorkflowTemplateHandoff(input) {
    const workflowSurface = (0, template_bindings_1.isWorkflowTemplateBindingSurface)(input.workflowSurface)
        ? input.workflowSurface
        : null;
    return {
        kind: "handoff",
        summary: (0, run_context_summaries_1.buildMissingWorkflowTemplateSummary)({
            kind: "missing-template",
            source: "sticky",
            selection: input.selection ??
                { mode: "template", templatePath: input.templateName },
            missingTemplatePath: input.templateName,
            availableTemplatePaths: workflowSurface !== null
                ? input.catalog.templates
                    .filter((candidate) => (0, template_registry_1.workflowTemplateTargetsSurface)(candidate, workflowSurface))
                    .map((candidate) => candidate.templatePath)
                : [],
            suggestions: [],
        }, input.locale),
        workflowTemplateName: input.workflowTemplateName ?? input.templateName,
        workflowState: input.workflowState,
    };
}
function resolveNestedWorkflowChildTemplateOrHandoff(input) {
    const targetTemplate = input.catalog.templateByPath.get(input.targetTemplateName);
    if (targetTemplate === undefined) {
        return {
            kind: "handoff",
            summary: (0, run_context_summaries_1.buildNestedWorkflowChildHandoffSummary)(`Missing child workflow template \`${input.targetTemplateName}\`.`, input.parentStepTitle, input.targetTemplateName, input.locale),
            workflowTemplateName: getActiveTemplateName(input.workflowState),
            workflowState: input.workflowState,
        };
    }
    const sourceTemplate = input.catalog.templateByPath.get(input.sourceTemplateName);
    if (sourceTemplate !== undefined &&
        !workflowTemplateTargetsOverlap(targetTemplate, sourceTemplate)) {
        return {
            kind: "handoff",
            summary: (0, run_context_summaries_1.buildNestedWorkflowChildHandoffSummary)(`Nested workflow template \`${input.targetTemplateName}\` is on a different workflow surface than \`${input.sourceTemplateName}\`.`, input.parentStepTitle, input.targetTemplateName, input.locale),
            workflowTemplateName: getActiveTemplateName(input.workflowState),
            workflowState: input.workflowState,
        };
    }
    return targetTemplate;
}
function workflowTemplateTargetsOverlap(left, right) {
    const rightTargets = (0, workflow_template_targets_1.resolveWorkflowTemplateRecordTargets)(right);
    return (0, workflow_template_targets_1.resolveWorkflowTemplateRecordTargets)(left).some((target) => rightTargets.includes(target));
}
function getActiveTemplateName(workflowState) {
    return (0, template_bindings_1.getWorkflowTemplateName)((0, template_bindings_1.getActiveWorkflowTemplateBinding)(workflowState));
}
async function resolveWorkflowPlanningArtifacts(input) {
    const nestedExpansion = (0, nested_workflows_1.resolveNestedWorkflowExpansion)({
        catalog: input.catalog,
        rootTemplate: input.template,
        maxNestedWorkflowDepth: input.maxNestedWorkflowDepth,
    });
    if (nestedExpansion.kind !== "ok") {
        return {
            kind: "handoff",
            summary: (0, run_context_summaries_1.buildNestedWorkflowExpansionSummary)(nestedExpansion, input.templateName, input.locale),
            workflowTemplateName: input.templateName,
            workflowState: input.workflowState,
        };
    }
    try {
        return await buildWorkflowPlanningArtifacts({
            repoRoot: input.repoRoot,
            catalog: input.catalog,
            template: input.template,
            nestedExpansion,
            maxNestedWorkflowDepth: input.maxNestedWorkflowDepth,
        });
    }
    catch (error) {
        return {
            kind: "handoff",
            summary: (0, run_context_summaries_1.buildWorkflowLinkResolutionSummary)(error, input.locale),
            workflowTemplateName: input.templateName,
            workflowState: input.workflowState,
        };
    }
}
async function resolveNestedWorkflowPlanningArtifacts(input) {
    const nestedExpansion = (0, nested_workflows_1.resolveNestedWorkflowExpansion)({
        catalog: input.catalog,
        rootTemplate: input.targetTemplate,
        maxNestedWorkflowDepth: input.maxNestedWorkflowDepth,
        activeStack: input.activeStack,
        currentDepth: input.currentDepth,
    });
    if (nestedExpansion.kind !== "ok") {
        return {
            kind: "handoff",
            summary: (0, run_context_summaries_1.buildNestedWorkflowChildHandoffSummary)((0, run_context_summaries_1.buildNestedWorkflowExpansionSummary)(nestedExpansion, input.targetTemplateName, input.locale), input.parentStepTitle, input.targetTemplateName, input.locale),
            workflowTemplateName: input.activeTemplateName,
            workflowState: input.workflowState,
        };
    }
    try {
        return await buildWorkflowPlanningArtifacts({
            repoRoot: input.repoRoot,
            catalog: input.catalog,
            template: input.targetTemplate,
            nestedExpansion,
            maxNestedWorkflowDepth: input.maxNestedWorkflowDepth,
        });
    }
    catch (error) {
        return {
            kind: "handoff",
            summary: (0, run_context_summaries_1.buildNestedWorkflowChildHandoffSummary)((0, run_context_summaries_1.buildWorkflowLinkResolutionSummary)(error, input.locale), input.parentStepTitle, input.targetTemplateName, input.locale),
            workflowTemplateName: input.activeTemplateName,
            workflowState: input.workflowState,
        };
    }
}
async function buildWorkflowPlanningArtifacts(input) {
    const templateReferences = await (0, template_links_1.resolveWorkflowTemplateReferencesForTemplates)({
        repoRoot: input.repoRoot,
        templates: [
            {
                templatePath: input.template.filePath,
                templateBody: input.template.body,
            },
        ],
    });
    return {
        templateBody: input.template.body,
        requiredSkills: (0, required_skills_1.collectRequiredSkillsForWorkflowTree)({
            catalog: input.catalog,
            rootTemplate: input.template,
            maxNestedWorkflowDepth: input.maxNestedWorkflowDepth,
        }),
        requiredMcp: (0, required_mcp_1.collectRequiredMcpForWorkflowTree)({
            catalog: input.catalog,
            rootTemplate: input.template,
            maxNestedWorkflowDepth: input.maxNestedWorkflowDepth,
        }),
        directChildWorkflows: input.nestedExpansion.directChildWorkflows,
        templateReferences,
    };
}
