import dotenv from 'dotenv';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
dotenv.config();

const DEV_SECRET = 'agora-secret-key-12345';
const isProd = process.env.NODE_ENV === 'production';

if (isProd && (!process.env.SECRET || process.env.SECRET === DEV_SECRET)) {
    throw new Error('[CONFIG] SECRET requis et différent du fallback dev en production.');
}

const CONFIG_PATH = path.resolve(process.cwd(), 'database', 'config.json');
const OLD_CONFIG_PATH = path.resolve(process.cwd(), 'config.json');

export class ConfigurationManager {
    private dynamicConfig: Record<string, any> = {};

    constructor() {
        this.load();
    }

    public load() {
        // Migration: si un fichier de config existe à la racine, on le déplace dans database/ pour plus de sécurité
        if (fs.existsSync(OLD_CONFIG_PATH) && !fs.existsSync(CONFIG_PATH)) {
            try {
                const dbDir = path.resolve(process.cwd(), 'database');
                if (!fs.existsSync(dbDir)) fs.mkdirSync(dbDir, { recursive: true });
                fs.copyFileSync(OLD_CONFIG_PATH, CONFIG_PATH);
                fs.unlinkSync(OLD_CONFIG_PATH);
                console.log('[CONFIG] Migration de config.json vers database/ réussie.');
            } catch (e) {
                console.error('[CONFIG] Erreur de migration de config.json', e);
            }
        }

        if (fs.existsSync(CONFIG_PATH)) {
            try {
                const data = fs.readFileSync(CONFIG_PATH, 'utf-8');
                this.dynamicConfig = JSON.parse(data);
            } catch (e) {
                console.error('[CONFIG] Erreur de lecture de database/config.json', e);
            }
        }
    }

    public save() {
        try {
            const dbDir = path.dirname(CONFIG_PATH);
            if (!fs.existsSync(dbDir)) fs.mkdirSync(dbDir, { recursive: true });
            fs.writeFileSync(CONFIG_PATH, JSON.stringify(this.dynamicConfig, null, 2), 'utf-8');
        } catch (e) {
            console.error('[CONFIG] Erreur d\'écriture de database/config.json', e);
        }
    }

    public get(key: string, fallback?: any): any {
        if (this.dynamicConfig[key] !== undefined && this.dynamicConfig[key] !== '') {
            return this.dynamicConfig[key];
        }
        if (process.env[key] !== undefined && process.env[key] !== '') {
            return process.env[key];
        }
        return fallback;
    }

    public set(key: string, value: any) {
        this.dynamicConfig[key] = value;
    }

    public delete(key: string) {
        delete this.dynamicConfig[key];
    }

    public getAllPluginsConfig(): Record<string, any> {
        // Renvoie tout sauf les variables systèmes pour l'UI
        const exclude = ['PORT', 'SECRET', 'ADMIN_USERNAME', 'ADMIN_PASSWORD'];
        const result: Record<string, any> = {};
        for (const [k, v] of Object.entries(this.dynamicConfig)) {
            if (!exclude.includes(k)) {
                result[k] = v;
            }
        }
        return result;
    }
}

export const configManager = new ConfigurationManager();

export const CONFIG = new Proxy({}, {
    get: (target, prop) => {
        if (typeof prop !== 'string') return undefined;

        switch(prop) {
            case 'HYDRACKER_URL': return configManager.get('HYDRACKER_URL', process.env.BASE_URL || '');
            case 'HYDRACKER_API_KEY': return configManager.get('HYDRACKER_API_KEY', process.env.API_KEY || '');
            case 'HYDRACKER_TIMEOUT': return parseInt(configManager.get('HYDRACKER_TIMEOUT', '30000'), 10);
            case 'TMDB_ENABLED': return String(configManager.get('TMDB_ENABLED', 'false')) === 'true';
            case 'TMDB_API_KEY': return configManager.get('TMDB_API_KEY', '');
            
            case 'ZT_URL': return configManager.get('ZT_URL', '');
            case 'ZTTEAM_URL': return configManager.get('ZTTEAM_URL', '');
            case 'FT_URL': return configManager.get('FT_URL', '');
            
            case 'FS24_URL': return configManager.get('FS24_URL', '');
            case 'FS24_USERNAME': return configManager.get('FS24_USERNAME', '');
            case 'FS24_PASSWORD': return configManager.get('FS24_PASSWORD', '');
            
            case 'MOVIX_URL': return configManager.get('MOVIX_URL', '');
            
            case 'FLIXART_URL': return configManager.get('FLIXART_URL', '');
            case 'FLIXART_USERNAME': return configManager.get('FLIXART_USERNAME', '');
            case 'FLIXART_PASSWORD': return configManager.get('FLIXART_PASSWORD', '');
            
            case 'LOADIX_URL': return configManager.get('LOADIX_URL', '');
            
            case 'DB_PATH': return configManager.get('DB_PATH', './database/darkiworld.db');
            
            case 'JD_HOST': return configManager.get('JD_HOST')?.trim();
            case 'JD_API_PORT': return String(configManager.get('JD_API_PORT') || '').trim() || undefined;
            case 'JD_CREATE_SUBFOLDER': return String(configManager.get('JD_CREATE_SUBFOLDER')) === 'true';
            case 'JD_AUTOSTART': return String(configManager.get('JD_AUTOSTART')) === 'true';
            
            case 'SECRET': return configManager.get('SECRET', DEV_SECRET);
            case 'MIN_MINUTES': return parseInt(configManager.get('MIN_MINUTES', '15'), 10);
            case 'MAX_MINUTES': return parseInt(configManager.get('MAX_MINUTES', '30'), 10);
            case 'PORT': return parseInt(configManager.get('PORT', '3067'), 10);
            
            case 'PREFERRED_HOSTERS': {
                const val = configManager.get('PREFERRED_HOSTERS');
                if (Array.isArray(val)) return val;
                if (typeof val === 'string') return val.split(',').map(s => s.trim());
                return ['1fichier', 'uptobox', 'turbobit', 'rapidgator', 'nitroflare', 'ddownload', 'mega', 'gofile', 'pixeldrain'];
            }
            case 'MAX_RESULTS_PER_SOURCE': return parseInt(configManager.get('MAX_RESULTS_PER_SOURCE', '20'), 10);
            default: return configManager.get(prop);
        }
    }
}) as any;

export function getPluginsToConfigure() {
    const __filename = fileURLToPath(import.meta.url);
    const __dirname = path.dirname(__filename);
    const pluginsDir = path.join(__dirname, '../../plugins');
    let detected: string[] = [];
    if (fs.existsSync(pluginsDir)) {
        detected = fs.readdirSync(pluginsDir, { withFileTypes: true })
            .filter(d => d.isDirectory())
            .map(d => d.name);
    }

    const pluginConfigMap: Record<string, { key: string; label: string; placeholder: string; default?: string }[]> = {
        'ZT': [{ key: 'ZT_URL', label: 'Zone-Téléchargement URL', placeholder: 'https://...', default: CONFIG.ZT_URL }],
        'ztnews': [{ key: 'ZTTEAM_URL', label: 'ZT (Team) URL', placeholder: 'https://...', default: CONFIG.ZTTEAM_URL }],
        'freetelecharger': [{ key: 'FT_URL', label: 'Free-Télécharger URL', placeholder: 'https://...', default: CONFIG.FT_URL }],
        'hydracker': [
            { key: 'HYDRACKER_URL', label: 'Hydracker API URL', placeholder: 'https://...', default: CONFIG.HYDRACKER_URL },
            { key: 'HYDRACKER_API_KEY', label: 'Hydracker API Key', placeholder: 'Token...', default: CONFIG.HYDRACKER_API_KEY }
        ],
        'fs24': [
            { key: 'FS24_URL', label: 'FS24 URL', placeholder: 'https://...', default: CONFIG.FS24_URL },
            { key: 'FS24_USERNAME', label: 'FS24 Identifiant', placeholder: 'Nom d\'utilisateur...', default: CONFIG.FS24_USERNAME },
            { key: 'FS24_PASSWORD', label: 'FS24 Mot de passe', placeholder: 'Mot de passe...', default: CONFIG.FS24_PASSWORD }
        ],
        'movix': [
            { key: 'MOVIX_URL', label: 'Movix URL', placeholder: 'https://...', default: CONFIG.MOVIX_URL }
        ],
        'flixart': [
            { key: 'FLIXART_URL', label: 'FlixArt URL', placeholder: 'https://...', default: CONFIG.FLIXART_URL },
            { key: 'FLIXART_USERNAME', label: 'FlixArt Identifiant', placeholder: 'Nom d\'utilisateur...', default: CONFIG.FLIXART_USERNAME },
            { key: 'FLIXART_PASSWORD', label: 'FlixArt Mot de passe', placeholder: 'Mot de passe...', default: CONFIG.FLIXART_PASSWORD }
        ],
        'loadix': [
            { key: 'LOADIX_URL', label: 'Loadix API URL', placeholder: 'https://...', default: CONFIG.LOADIX_URL }
        ]
    };

    const configs = detected.filter(p => pluginConfigMap[p]).map(p => ({
        name: p,
        fields: pluginConfigMap[p]
    }));

    configs.push({
        name: 'Paramètres Généraux',
        fields: [
            { key: 'MAX_RESULTS_PER_SOURCE', label: 'Limite de résultats par source (Tendances/Récents)', placeholder: 'ex: 20', default: String(CONFIG.MAX_RESULTS_PER_SOURCE) }
        ]
    });

    configs.push({
        name: 'TMDB (Enrichissement Auto)',
        fields: [
            { key: 'TMDB_ENABLED', label: 'Activer TMDB', placeholder: 'true ou false', default: String(CONFIG.TMDB_ENABLED === true) },
            { key: 'TMDB_API_KEY', label: 'Clé API TMDB (v3 auth)', placeholder: 'Clé API...', default: CONFIG.TMDB_API_KEY }
        ]
    });

    return configs;
}
