import { readFileSync, existsSync } from 'node:fs';
import { join } from 'node:path';
import { parse as parseToml } from 'smol-toml';
import { WardenConfigSchema, } from './schema.js';
export class ConfigLoadError extends Error {
    constructor(message, options) {
        super(message, options);
        this.name = 'ConfigLoadError';
    }
}
export function loadWardenConfig(repoPath) {
    const configPath = join(repoPath, 'warden.toml');
    if (!existsSync(configPath)) {
        throw new ConfigLoadError(`Configuration file not found: ${configPath}`);
    }
    let content;
    try {
        content = readFileSync(configPath, 'utf-8');
    }
    catch (error) {
        throw new ConfigLoadError(`Failed to read configuration file: ${configPath}`, { cause: error });
    }
    let rawConfig;
    try {
        rawConfig = parseToml(content);
    }
    catch (error) {
        throw new ConfigLoadError('Failed to parse TOML configuration', { cause: error });
    }
    const result = WardenConfigSchema.safeParse(rawConfig);
    if (!result.success) {
        const issues = result.error.issues.map(i => `  - ${i.path.join('.')}: ${i.message}`).join('\n');
        throw new ConfigLoadError(`Invalid configuration:\n${issues}`);
    }
    return result.data;
}
/**
 * Convert empty strings to undefined.
 * GitHub Actions substitutes unconfigured secrets with empty strings,
 * so we need to treat '' as "not set" for optional config values.
 */
function emptyToUndefined(value) {
    return value === '' ? undefined : value;
}
/**
 * Resolve a trigger's configuration by merging with defaults.
 * Trigger-specific values override defaults.
 *
 * Model precedence (highest to lowest):
 * 1. trigger.model (warden.toml trigger-level)
 * 2. defaults.model (warden.toml [defaults])
 * 3. cliModel (--model flag)
 * 4. WARDEN_MODEL env var
 * 5. SDK default (not set here)
 */
export function resolveTrigger(trigger, config, cliModel) {
    const defaults = config.defaults;
    const envModel = emptyToUndefined(process.env['WARDEN_MODEL']);
    return {
        ...trigger,
        filters: {
            paths: trigger.filters?.paths ?? defaults?.filters?.paths,
            ignorePaths: trigger.filters?.ignorePaths ?? defaults?.filters?.ignorePaths,
        },
        output: {
            failOn: trigger.output?.failOn ?? defaults?.output?.failOn,
            commentOn: trigger.output?.commentOn ?? defaults?.output?.commentOn,
            maxFindings: trigger.output?.maxFindings ?? defaults?.output?.maxFindings,
            commentOnSuccess: trigger.output?.commentOnSuccess ?? defaults?.output?.commentOnSuccess,
        },
        model: emptyToUndefined(trigger.model) ??
            emptyToUndefined(defaults?.model) ??
            emptyToUndefined(cliModel) ??
            envModel,
    };
}
//# sourceMappingURL=loader.js.map