/**
 * Workflow YAML parsing and normalization.
 */
import { WorkflowConfigRawSchema } from '../../../core/models/index.js';
import { resolveLoopMonitorJudgeProviderModel, resolveStepProviderModel } from '../../../core/workflow/provider-resolution.js';
import { validateProviderModelCompatibility } from '../../../core/workflow/provider-model-compatibility.js';
import { normalizeRateLimitFallback, normalizeRuntime } from '../configNormalizers.js';
import { resolveSectionMapWithSource, unwrapResolvedSectionMap, } from './resource-resolver.js';
import { validateWorkflowRuntimePrepare, validateWorkflowCommandGates, } from './workflowNormalizationPolicies.js';
import { normalizeLoopMonitors } from './workflowLoopMonitorNormalizer.js';
import { normalizeProviderReference, normalizeStepFromRaw } from './workflowStepNormalizer.js';
import { expandCallableSubworkflowRaw, } from './workflowCallableArgResolver.js';
import { prepareCallableSubworkflowDiscoveryArgs } from './workflowCallableDiscoveryArgs.js';
function normalizeSubworkflowConfig(raw) {
    if (!raw) {
        return undefined;
    }
    return {
        callable: raw.callable,
        visibility: raw.visibility,
        returns: raw.returns,
        params: raw.params
            ? Object.fromEntries(Object.entries(raw.params).map(([name, param]) => [
                name,
                {
                    type: param.type,
                    facetKind: param.facet_kind,
                    default: param.default,
                },
            ]))
            : undefined,
    };
}
export function normalizeWorkflowConfig(raw, workflowDir, context, projectOverrides, globalOverrides, workflowRuntimePreparePolicy, workflowArpeggioPolicy, workflowMcpServersPolicy, callableArgs, callableArgPolicy, callableArgMode = 'runtime', workflowCommandGatesPolicy) {
    const parsedRaw = WorkflowConfigRawSchema.parse(raw);
    const callableDiscovery = callableArgMode === 'discovery'
        ? prepareCallableSubworkflowDiscoveryArgs(parsedRaw)
        : { raw: parsedRaw, callableArgs };
    const parsed = expandCallableSubworkflowRaw(callableDiscovery.raw, {
        args: callableDiscovery.callableArgs ?? callableArgs,
        argPolicy: callableArgPolicy,
        workflowDir,
        context,
    });
    const resolvedPoliciesWithSource = resolveSectionMapWithSource(parsed.policies, workflowDir, 'policies');
    const resolvedKnowledgeWithSource = resolveSectionMapWithSource(parsed.knowledge, workflowDir, 'knowledge');
    const resolvedInstructionsWithSource = resolveSectionMapWithSource(parsed.instructions, workflowDir, 'instructions');
    const resolvedReportFormatsWithSource = resolveSectionMapWithSource(parsed.report_formats, workflowDir, 'output-contracts');
    const sections = {
        personas: parsed.personas,
        resolvedPolicies: unwrapResolvedSectionMap(resolvedPoliciesWithSource),
        resolvedPoliciesWithSource,
        resolvedKnowledge: unwrapResolvedSectionMap(resolvedKnowledgeWithSource),
        resolvedKnowledgeWithSource,
        resolvedInstructions: unwrapResolvedSectionMap(resolvedInstructionsWithSource),
        resolvedInstructionsWithSource,
        resolvedReportFormats: unwrapResolvedSectionMap(resolvedReportFormatsWithSource),
        resolvedReportFormatsWithSource,
    };
    const workflowRuntime = normalizeRuntime(parsed.workflow_config?.runtime);
    validateWorkflowRuntimePrepare(workflowRuntime, workflowRuntimePreparePolicy);
    validateWorkflowCommandGates(parsed.steps, workflowCommandGatesPolicy);
    const normalizedWorkflowProvider = normalizeProviderReference(parsed.workflow_config?.provider, parsed.workflow_config?.model, parsed.workflow_config?.provider_options);
    const steps = parsed.steps.map((step) => normalizeStepFromRaw(step, workflowDir, sections, parsed.schemas, normalizedWorkflowProvider.provider, normalizedWorkflowProvider.model, normalizedWorkflowProvider.providerOptions, undefined, context, projectOverrides, globalOverrides, workflowArpeggioPolicy, workflowMcpServersPolicy));
    const loopMonitors = normalizeLoopMonitors(parsed.loop_monitors, workflowDir, sections, context);
    for (const monitor of loopMonitors ?? []) {
        const triggeringStep = steps.find((step) => step.name === monitor.cycle[monitor.cycle.length - 1]);
        if (!triggeringStep) {
            continue;
        }
        const triggeringProviderInfo = resolveStepProviderModel({
            step: triggeringStep,
            provider: normalizedWorkflowProvider.provider,
            model: normalizedWorkflowProvider.model,
        });
        const judgeProviderInfo = resolveLoopMonitorJudgeProviderModel({
            judge: monitor.judge,
            triggeringStep,
            provider: triggeringProviderInfo.provider,
            model: triggeringProviderInfo.model,
        });
        validateProviderModelCompatibility(judgeProviderInfo.provider, judgeProviderInfo.model, {
            modelFieldName: 'Configuration error: loop_monitors.judge.model',
        });
    }
    return {
        name: parsed.name,
        description: parsed.description,
        subworkflow: normalizeSubworkflowConfig(parsed.subworkflow),
        schemas: parsed.schemas,
        provider: normalizedWorkflowProvider.provider,
        model: normalizedWorkflowProvider.model,
        providerOptions: normalizedWorkflowProvider.providerOptions,
        rateLimitFallback: normalizeRateLimitFallback(parsed.rate_limit_fallback),
        runtime: workflowRuntime,
        personas: parsed.personas,
        policies: sections.resolvedPolicies,
        knowledge: sections.resolvedKnowledge,
        instructions: sections.resolvedInstructions,
        reportFormats: sections.resolvedReportFormats,
        steps,
        initialStep: parsed.initial_step ?? steps[0].name,
        maxSteps: parsed.max_steps,
        loopMonitors,
        interactiveMode: parsed.interactive_mode,
    };
}
//# sourceMappingURL=workflowParser.js.map