/**
 * CI/CD Monitor Configuration Loader
 *
 * Loads configuration from environment variables, .env files, and
 * .specweave/config.json with validation and defaults.
 */
import * as fs from '../../utils/fs-native.js';
import * as path from 'path';
/**
 * Load configuration from environment variables
 */
function loadFromEnv() {
    const token = process.env.GITHUB_TOKEN;
    const owner = process.env.GITHUB_OWNER;
    const repo = process.env.GITHUB_REPO;
    const pollIntervalStr = process.env.CICD_POLL_INTERVAL;
    const channelsStr = process.env.CICD_NOTIFICATION_CHANNELS;
    const webhookUrl = process.env.CICD_WEBHOOK_URL;
    const config = {};
    // Build monitor config if any GitHub-related env vars are set
    if (token || owner || repo || pollIntervalStr) {
        config.monitor = {
            token: token || '',
            owner: owner || '',
            repo: repo || '',
            pollInterval: pollIntervalStr ? parseInt(pollIntervalStr, 10) : 60000
        };
    }
    // Build notifier config if notification env vars are set
    if (channelsStr || webhookUrl) {
        const channels = channelsStr?.split(',').map((c) => c.trim());
        config.notifier = {
            channels: channels || ['console'],
            webhookUrl,
            logFile: undefined
        };
    }
    // Auto-notify defaults to false unless explicitly set to 'true'
    if (process.env.CICD_AUTO_NOTIFY !== undefined) {
        config.autoNotify = process.env.CICD_AUTO_NOTIFY === 'true';
    }
    return config;
}
/**
 * Load configuration from .specweave/config.json
 */
async function loadFromConfigFile(rootDir) {
    const configPath = path.join(rootDir, '.specweave/config.json');
    if (!(await fs.pathExists(configPath))) {
        return {};
    }
    try {
        const content = await fs.readFile(configPath, 'utf-8');
        const rawConfig = JSON.parse(content);
        const config = {};
        if (rawConfig.cicd?.github) {
            config.monitor = {
                token: rawConfig.cicd.github.token || '',
                owner: rawConfig.cicd.github.owner || '',
                repo: rawConfig.cicd.github.repo || '',
                pollInterval: rawConfig.cicd.monitoring?.pollInterval || 60000
            };
        }
        else if (rawConfig.cicd?.monitoring) {
            // Unified config format: cicd.monitoring at top level (no github sub-key)
            config.monitor = {
                token: '',
                owner: '',
                repo: '',
                pollInterval: rawConfig.cicd.monitoring.pollInterval || 60000
            };
        }
        if (rawConfig.cicd?.notifications) {
            config.notifier = {
                channels: (rawConfig.cicd.notifications.channels || ['console']),
                webhookUrl: rawConfig.cicd.notifications.webhookUrl,
                logFile: rawConfig.cicd.notifications.logFile
            };
        }
        if (rawConfig.cicd?.monitoring?.autoNotify !== undefined) {
            config.autoNotify = rawConfig.cicd.monitoring.autoNotify;
        }
        // Unified config fields (v1.0.231+)
        if (rawConfig.cicd?.pushStrategy) {
            config.pushStrategy = rawConfig.cicd.pushStrategy;
        }
        if (rawConfig.cicd?.git) {
            config.git = rawConfig.cicd.git;
        }
        if (rawConfig.cicd?.autoFix) {
            config.autoFix = rawConfig.cicd.autoFix;
        }
        if (rawConfig.cicd?.release) {
            config.release = rawConfig.cicd.release;
        }
        return config;
    }
    catch (error) {
        console.warn('Failed to load .specweave/config.json:', error);
        return {};
    }
}
/**
 * Get default configuration
 */
function getDefaults() {
    return {
        monitor: {
            token: '',
            owner: '',
            repo: '',
            pollInterval: 60000,
            debug: false
        },
        notifier: {
            channels: ['console', 'file'],
            logFile: '.specweave/logs/cicd-notifications.log',
            webhookUrl: undefined,
            debug: false
        },
        rootDir: process.cwd(),
        autoNotify: true,
        pushStrategy: 'direct',
        git: {
            branchPrefix: 'sw/',
            targetBranch: 'main',
            deleteOnMerge: true,
        },
        autoFix: {
            enabled: true,
            maxRetries: 1,
            allowedBranches: ['develop', 'main'],
        },
    };
}
/**
 * Merge configurations with priority:
 * env > configFile > defaults
 */
function mergeConfigs(defaults, configFile, env) {
    return {
        monitor: {
            ...defaults.monitor,
            ...(configFile.monitor || {}),
            ...(env.monitor || {})
        },
        notifier: {
            ...defaults.notifier,
            ...(configFile.notifier || {}),
            ...(env.notifier || {})
        },
        rootDir: env.rootDir || configFile.rootDir || defaults.rootDir,
        autoNotify: env.autoNotify ?? configFile.autoNotify ?? defaults.autoNotify,
        pushStrategy: configFile.pushStrategy ?? defaults.pushStrategy,
        git: { ...defaults.git, ...(configFile.git || {}) },
        autoFix: configFile.autoFix ?? defaults.autoFix,
        release: configFile.release ?? defaults.release
    };
}
/**
 * Validate configuration
 */
function validateConfig(config) {
    if (!config.monitor.token) {
        throw new Error('GitHub token is required (set GITHUB_TOKEN or add to .specweave/config.json)');
    }
    if (!config.monitor.owner || !config.monitor.repo) {
        throw new Error('GitHub owner and repo are required (set GITHUB_OWNER/GITHUB_REPO or add to .specweave/config.json)');
    }
    if (config.monitor.pollInterval && config.monitor.pollInterval < 10000) {
        throw new Error('Poll interval must be at least 10 seconds (10000ms) to avoid rate limiting');
    }
    if (config.notifier.channels.length === 0) {
        throw new Error('At least one notification channel must be configured');
    }
}
/**
 * Load and validate configuration from all sources
 *
 * Priority: env > .specweave/config.json > defaults
 *
 * @param rootDir - Project root directory (optional)
 * @returns Validated configuration
 */
export async function loadConfig(rootDir = process.cwd()) {
    // Load from all sources
    const defaults = getDefaults();
    const configFile = await loadFromConfigFile(rootDir);
    const env = loadFromEnv();
    // Merge with priority
    const config = mergeConfigs(defaults, configFile, env);
    // Update rootDir
    config.rootDir = rootDir;
    // Validate
    validateConfig(config);
    return config;
}
/**
 * Create example configuration file
 */
export async function createExampleConfig(rootDir = process.cwd()) {
    const configPath = path.join(rootDir, '.specweave/config.json');
    const exampleConfig = {
        cicd: {
            github: {
                token: '${GITHUB_TOKEN}',
                owner: 'your-github-username',
                repo: 'your-repo-name'
            },
            monitoring: {
                pollInterval: 60000,
                autoNotify: true
            },
            notifications: {
                channels: ['console', 'file'],
                webhookUrl: 'https://your-webhook-url.com/cicd-alerts',
                logFile: '.specweave/logs/cicd-notifications.log'
            }
        }
    };
    await fs.ensureDir(path.dirname(configPath));
    await fs.writeFile(configPath, JSON.stringify(exampleConfig, null, 2), 'utf-8');
    console.log(`✅ Created example config at ${configPath}`);
    console.log('   Edit this file and set your GitHub token, owner, and repo');
}
//# sourceMappingURL=config-loader.js.map