import { dirname } from 'node:path';
import { existsSync, readFileSync } from 'node:fs';
import { parse as parseYaml } from 'yaml';
import { getRepertoireDir } from '../paths.js';
import { resolveWorkflowConfigValue } from '../resolveWorkflowConfigValue.js';
import { loadGlobalConfig } from '../global/globalConfig.js';
import { loadProjectConfig } from '../project/projectConfig.js';
import { normalizeWorkflowConfig } from './workflowParser.js';
import { resolveWorkflowArpeggioPolicy, resolveWorkflowCommandGatesPolicy, resolveWorkflowMcpServersPolicy, resolveWorkflowRuntimePreparePolicy, } from './workflowNormalizationPolicies.js';
import { attachWorkflowSourcePath, attachWorkflowTrustInfo, attachWorkflowOpaqueRef, buildOpaqueWorkflowRef, } from './workflowSourceMetadata.js';
import { resolveWorkflowTrustInfo } from './workflowTrustSource.js';
function loadWorkflowFromFileInternal(filePath, projectDir, options, loadMode) {
    if (!existsSync(filePath)) {
        throw new Error(`Workflow file not found: ${filePath}`);
    }
    const raw = parseYaml(readFileSync(filePath, 'utf-8'));
    const workflowDir = dirname(filePath);
    const context = {
        lang: resolveWorkflowConfigValue(projectDir, 'language'),
        projectDir,
        workflowDir,
        repertoireDir: getRepertoireDir(),
    };
    const projectConfig = loadProjectConfig(projectDir);
    const globalConfig = loadGlobalConfig();
    const trustInfo = options?.trustInfo ?? resolveWorkflowTrustInfo({
        filePath,
        projectCwd: projectDir,
    });
    const config = normalizeWorkflowConfig(raw, workflowDir, context, projectConfig.workflowOverrides, globalConfig.workflowOverrides, resolveWorkflowRuntimePreparePolicy(globalConfig.workflowRuntimePrepare, projectConfig.workflowRuntimePrepare), resolveWorkflowArpeggioPolicy(globalConfig.workflowArpeggio, projectConfig.workflowArpeggio), resolveWorkflowMcpServersPolicy(globalConfig.workflowMcpServers, projectConfig.workflowMcpServers), options?.callableArgs, options?.callableArgPolicy, loadMode, resolveWorkflowCommandGatesPolicy(globalConfig.workflowCommandGates, projectConfig.workflowCommandGates));
    attachWorkflowOpaqueRef(config, buildOpaqueWorkflowRef(filePath, trustInfo));
    attachWorkflowSourcePath(config, filePath);
    attachWorkflowTrustInfo(config, trustInfo);
    return config;
}
export function loadWorkflowFromFile(filePath, projectDir, options) {
    return loadWorkflowFromFileInternal(filePath, projectDir, options, 'runtime');
}
export function loadWorkflowFromFileForDiscovery(filePath, projectDir, options) {
    return loadWorkflowFromFileInternal(filePath, projectDir, options, 'discovery');
}
//# sourceMappingURL=workflowFileLoader.js.map