"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveSelectedWorkflowTemplatePath = resolveSelectedWorkflowTemplatePath;
exports.validateWorkflowTemplateSelection = validateWorkflowTemplateSelection;
const default_system_workflows_1 = require("./default-system-workflows");
const template_bindings_1 = require("./template-bindings");
const template_registry_1 = require("./template-registry");
const validation_1 = require("./validation");
function resolveSelectedWorkflowTemplatePath(selector, workflowSurface) {
    if (selector === undefined) {
        return undefined;
    }
    if (selector === null) {
        return null;
    }
    if (selector.mode === "no_template") {
        return workflowSurface === undefined
            ? null
            : (0, default_system_workflows_1.resolveDefaultSystemWorkflowTemplatePath)(workflowSurface);
    }
    return selector.mode === "template" ? selector.templatePath : undefined;
}
function validateWorkflowTemplateSelection(input) {
    const workflowSurface = input.workflowSurface;
    const workflowSurfaceTargetsTemplates = (0, template_bindings_1.isWorkflowTemplateBindingSurface)(workflowSurface);
    if (input.templatePath === undefined || input.templatePath === null) {
        return { kind: "ok", template: null };
    }
    const template = input.catalog.templateByPath.get(input.templatePath);
    if (template === undefined) {
        return {
            kind: "missing-template",
            templatePath: input.templatePath,
            availableTemplatePaths: workflowSurfaceTargetsTemplates
                ? input.catalog.templates
                    .filter((candidate) => (0, template_registry_1.workflowTemplateTargetsSurface)(candidate, workflowSurface))
                    .map((candidate) => candidate.templatePath)
                : [],
        };
    }
    if (!workflowSurfaceTargetsTemplates ||
        !(0, template_registry_1.workflowTemplateTargetsSurface)(template, workflowSurface)) {
        return { kind: "invalid-surface", template };
    }
    const validation = (0, validation_1.validateWorkflowTemplateTree)({
        catalog: input.catalog,
        rootTemplate: template,
        maxNestedWorkflowDepth: input.maxNestedWorkflowDepth,
    });
    if (validation.diagnostics.length !== 0) {
        return {
            kind: "invalid-tree",
            template,
            diagnostics: validation.diagnostics,
        };
    }
    return { kind: "ok", template };
}
