import fs from 'fs';
import path from 'path';
import os from 'os';

const CONFIG_DIR = path.join(os.homedir(), '.thrust');
const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');

const DEFAULT_CONFIG = {
    auth: {
        token: null,
        user: null
    },
    activeLeadId: null,
    leads: {},
    mcpServers: [] // NEW: Stores external MCP servers we poll (Feed-In Client)
};

export function initConfig() {
    try {
        if (!fs.existsSync(CONFIG_DIR)) {
            fs.mkdirSync(CONFIG_DIR, { recursive: true });
        }
        if (!fs.existsSync(CONFIG_FILE)) {
            fs.writeFileSync(CONFIG_FILE, JSON.stringify(DEFAULT_CONFIG, null, 2), 'utf8');
        }
    } catch (error) {
        console.error(`❌ [Config Error] Failed to initialize config directory at ${CONFIG_DIR}:`, error.message);
    }
}

export function getConfig() {
    initConfig();
    try {
        const data = fs.readFileSync(CONFIG_FILE, 'utf8');
        const parsed = JSON.parse(data);
        
        // Ensure legacy configs get the new objects injected safely
        if (!parsed.auth) parsed.auth = { token: null, user: null };
        if (!parsed.mcpServers) parsed.mcpServers = []; 
        
        return parsed;
    } catch (error) {
        console.error('⚠️ [Config Error] Corrupted config file. Returning defaults.', error.message);
        return { ...DEFAULT_CONFIG };
    }
}

export function saveConfig(newConfig) {
    initConfig();
    try {
        fs.writeFileSync(CONFIG_FILE, JSON.stringify(newConfig, null, 2), 'utf8');
    } catch (error) {
        console.error('❌ [Config Error] Failed to save configuration:', error.message);
    }
}

export function getActiveProject() {
    const config = getConfig();
    if (!config.activeLeadId || !config.leads[config.activeLeadId]) return null;

    return {
        id: config.activeLeadId,
        ...config.leads[config.activeLeadId]
    };
}
