
const express = require('express');
const cors = require('cors');
const fs = require('fs');
const path = require('path');
const { validateLocale, validateConfigKey } = require('./middleware/validate');
const logger = require('./utils/logger');

const app = express();

const BASE_PATH = process.env.BASE_PATH || '/translations';
const router = express.Router();
const corsOptions = {
    origin: process.env.CORS_ORIGIN || '*',
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
    allowedHeaders: ['Content-Type', 'Authorization'],
    credentials: true
};
app.use(cors(corsOptions));

app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

app.use((req, res, next) => {
    console.log(`${req.method} ${req.path} - IP: ${req.ip || req.connection.remoteAddress}`);
    next();
});

const TRANSLATIONS_DIR = path.join(__dirname, 'data');
const CONFIGS_FILE = path.join(TRANSLATIONS_DIR, 'configs.json');

let translationsCache = {};
let configsCache = null;
// Track file modification times to detect changes
let fileTimestamps = {}; // { locale: mtime }
let configsTimestamp = null;

function loadTranslations(locale) {
    const filePath = path.join(TRANSLATIONS_DIR, `translations.${locale}.json`);
    
    console.log(`[LOAD] Attempting to load translations for locale: ${locale}`);
    console.log(`[LOAD] File path: ${filePath}`);
    
    if (!fs.existsSync(filePath)) {
        logger.warn(`[LOAD] File not found: ${filePath}`);
        return null;
    }
    
    try {
        const stats = fs.statSync(filePath);
        console.log(`[LOAD] File exists. Size: ${stats.size} bytes, Modified: ${stats.mtime.toISOString()}`);
        
        const content = fs.readFileSync(filePath, 'utf8');
        console.log(`[LOAD] File read successfully. Content length: ${content.length} characters`);
        
        const translations = JSON.parse(content);
        const keyCount = Object.keys(translations).length;
        
        // Store file modification time
        fileTimestamps[locale] = stats.mtime.getTime();
        console.log(`[LOAD] Stored file timestamp for '${locale}': ${fileTimestamps[locale]} (${stats.mtime.toISOString()})`);
        
        logger.success(`[LOAD] ✓ Successfully loaded translations for locale '${locale}'. Keys: ${keyCount}`);
        
        return translations;
    } catch (error) {
        logger.error(`[LOAD] ✗ Error loading translations for locale ${locale}:`, error.message);
        if (error instanceof SyntaxError) {
            logger.error(`[LOAD] JSON parse error. File may be corrupted or invalid JSON.`);
        }
        return null;
    }
}

/**
 * Check if file has been modified since last cache
 * Returns true if file is newer than cache, false otherwise
 */
function isFileModified(locale) {
    const filePath = path.join(TRANSLATIONS_DIR, `translations.${locale}.json`);
    
    if (!fs.existsSync(filePath)) {
        console.log(`[CHECK] File not found: ${filePath}`);
        return false;
    }
    
    try {
        const stats = fs.statSync(filePath);
        const currentMtime = stats.mtime.getTime();
        const cachedMtime = fileTimestamps[locale];
        
        if (!cachedMtime) {
            console.log(`[CHECK] No cached timestamp for '${locale}', file is considered new`);
            return true; // No cache, consider it new
        }
        
        const isNewer = currentMtime > cachedMtime;
        
        if (isNewer) {
            logger.info(`[CHECK] ⚠ File '${locale}' has been modified!`);
            console.log(`[CHECK] Cached: ${new Date(cachedMtime).toISOString()}, Current: ${stats.mtime.toISOString()}`);
        } else {
            console.log(`[CHECK] File '${locale}' unchanged (cached: ${new Date(cachedMtime).toISOString()}, current: ${stats.mtime.toISOString()})`);
        }
        
        return isNewer;
    } catch (error) {
        logger.error(`[CHECK] Error checking file modification for '${locale}':`, error.message);
        return false;
    }
}

function loadConfigs() {
    console.log(`[CONFIGS] Attempting to load configs from: ${CONFIGS_FILE}`);
    
    if (!fs.existsSync(CONFIGS_FILE)) {
        logger.warn(`[CONFIGS] Configs file not found: ${CONFIGS_FILE}`);
        return {};
    }
    
    try {
        const stats = fs.statSync(CONFIGS_FILE);
        console.log(`[CONFIGS] File exists. Size: ${stats.size} bytes, Modified: ${stats.mtime.toISOString()}`);
        
        const content = fs.readFileSync(CONFIGS_FILE, 'utf8');
        const configs = JSON.parse(content);
        const keyCount = Object.keys(configs).length;
        
        // Store file modification time
        configsTimestamp = stats.mtime.getTime();
        console.log(`[CONFIGS] Stored file timestamp: ${configsTimestamp} (${stats.mtime.toISOString()})`);
        
        logger.success(`[CONFIGS] ✓ Successfully loaded configs. Keys: ${keyCount}`);
        
        return configs;
    } catch (error) {
        logger.error(`[CONFIGS] ✗ Error loading configs:`, error.message);
        if (error instanceof SyntaxError) {
            logger.error(`[CONFIGS] JSON parse error. File may be corrupted or invalid JSON.`);
        }
        return {};
    }
}

/**
 * Check if configs file has been modified since last cache
 */
function isConfigsModified() {
    if (!fs.existsSync(CONFIGS_FILE)) {
        console.log(`[CHECK] Configs file not found: ${CONFIGS_FILE}`);
        return false;
    }
    
    try {
        const stats = fs.statSync(CONFIGS_FILE);
        const currentMtime = stats.mtime.getTime();
        const cachedMtime = configsTimestamp;
        
        if (!cachedMtime) {
            console.log(`[CHECK] No cached timestamp for configs, file is considered new`);
            return true;
        }
        
        const isNewer = currentMtime > cachedMtime;
        
        if (isNewer) {
            logger.info(`[CHECK] ⚠ Configs file has been modified!`);
            console.log(`[CHECK] Cached: ${new Date(cachedMtime).toISOString()}, Current: ${stats.mtime.toISOString()}`);
        } else {
            console.log(`[CHECK] Configs file unchanged (cached: ${new Date(cachedMtime).toISOString()}, current: ${stats.mtime.toISOString()})`);
        }
        
        return isNewer;
    } catch (error) {
        logger.error(`[CHECK] Error checking configs file modification:`, error.message);
        return false;
    }
}

function reloadTranslationsCache() {
    logger.info(`[RELOAD] Starting translations cache reload...`);
    console.log(`[RELOAD] Translations directory: ${TRANSLATIONS_DIR}`);
    
    const oldCacheSize = Object.keys(translationsCache).length;
    console.log(`[RELOAD] Current cache size: ${oldCacheSize} locales`);
    
    // Clear cache and timestamps
    translationsCache = {};
    fileTimestamps = {};
    
    try {
        if (!fs.existsSync(TRANSLATIONS_DIR)) {
            logger.error(`[RELOAD] ✗ Translations directory does not exist: ${TRANSLATIONS_DIR}`);
            return;
        }
        
        const files = fs.readdirSync(TRANSLATIONS_DIR);
        console.log(`[RELOAD] Found ${files.length} files in directory`);
        
        const translationFiles = files.filter(file => file.match(/^translations\.(.+)\.json$/));
        logger.info(`[RELOAD] Found ${translationFiles.length} translation file(s)`);
        
        let loadedCount = 0;
        let failedCount = 0;
        
        translationFiles.forEach(file => {
            const match = file.match(/^translations\.(.+)\.json$/);
            if (match) {
                const locale = match[1];
                console.log(`[RELOAD] Processing file: ${file} (locale: ${locale})`);
                
                const translations = loadTranslations(locale);
                if (translations) {
                    translationsCache[locale] = translations;
                    loadedCount++;
                    logger.success(`[RELOAD] ✓ Cached translations for locale '${locale}'`);
                } else {
                    failedCount++;
                    logger.error(`[RELOAD] ✗ Failed to load translations for locale '${locale}'`);
                }
            }
        });
        
        const newCacheSize = Object.keys(translationsCache).length;
        logger.success(`[RELOAD] ✓ Cache reload completed. Loaded: ${loadedCount}, Failed: ${failedCount}, Total cached: ${newCacheSize}`);
        
        // Log available locales
        if (newCacheSize > 0) {
            logger.info(`[RELOAD] Available locales: ${Object.keys(translationsCache).join(', ')}`);
        } else {
            logger.warn(`[RELOAD] ⚠ No translations loaded! Cache is empty.`);
        }
    } catch (error) {
        logger.error(`[RELOAD] ✗ Error during cache reload:`, error.message);
        logger.error(`[RELOAD] Stack trace:`, error.stack);
    }
}

function reloadConfigsCache() {
    logger.info(`[RELOAD] Starting configs cache reload...`);
    const oldConfigs = configsCache !== null;
    
    // Clear configs timestamp
    configsTimestamp = null;
    
    configsCache = loadConfigs();
    
    const newConfigs = configsCache !== null && Object.keys(configsCache).length > 0;
    if (newConfigs) {
        logger.success(`[RELOAD] ✓ Configs cache reloaded successfully`);
    } else {
        logger.warn(`[RELOAD] ⚠ Configs cache is empty or failed to load`);
    }
}

// Initial load on startup
logger.info('\n' + '='.repeat(60));
logger.info('🚀 Starting Translations API Server');
logger.info('='.repeat(60));
logger.info(`📁 Translations directory: ${TRANSLATIONS_DIR}`);
logger.info(`📄 Configs file: ${CONFIGS_FILE}`);
logger.info(`🌍 Base path: ${BASE_PATH}`);
logger.info('='.repeat(60) + '\n');

logger.info('📦 Loading initial cache...');
reloadTranslationsCache();
reloadConfigsCache();
logger.info('✓ Initial cache loading completed\n');

// File watcher - enable in production if ENABLE_FILE_WATCHER=true
const enableFileWatcher = process.env.ENABLE_FILE_WATCHER === 'true' || process.env.NODE_ENV !== 'production';
if (enableFileWatcher) {
    try {
        fs.watch(TRANSLATIONS_DIR, { recursive: false }, (eventType, filename) => {
            console.log(`[WATCHER] File system event detected: ${eventType} on ${filename}`);
            
            if (filename && filename.startsWith('translations.')) {
                logger.info(`[WATCHER] 🔄 Translations file changed: ${filename}`);
                logger.info(`[WATCHER] Event type: ${eventType}`);
                
                // Small delay to ensure file write is complete
                setTimeout(() => {
                    logger.info(`[WATCHER] Reloading translations cache...`);
                    reloadTranslationsCache();
                    logger.success(`[WATCHER] ✓ Translations cache reloaded for ${filename}`);
                }, 100);
            } else if (filename === 'configs.json') {
                logger.info(`[WATCHER] 🔄 Configs file changed: ${filename}`);
                logger.info(`[WATCHER] Event type: ${eventType}`);
                
                setTimeout(() => {
                    logger.info(`[WATCHER] Reloading configs cache...`);
                    reloadConfigsCache();
                    logger.success(`[WATCHER] ✓ Configs cache reloaded`);
                }, 100);
            } else if (filename) {
                console.log(`[WATCHER] Ignored file change: ${filename} (not a translation/config file)`);
            }
        });
        logger.success('File watcher initialized for auto-reload');
    } catch (error) {
        logger.warn('File watcher could not be initialized:', error.message);
        logger.warn('Auto-reload disabled. Use POST /api/reload endpoint or restart server to load changes.');
    }
} else {
    logger.info('File watcher disabled in production. Use POST /api/reload endpoint to reload cache after file changes.');
}

router.get('/api/translations/:locale', validateLocale, (req, res) => {
    try {
        const { locale } = req.params;
        console.log(`[API] GET /api/translations/${locale} - Request received`);
        
        if (!locale || typeof locale !== 'string' || locale.length > 10) {
            logger.warn(`[API] Invalid locale format: ${locale}`);
            return res.status(400).json({
                success: false,
                error: 'Invalid locale format'
            });
        }
        
        // Always load directly from file (no cache)
        console.log(`[API] Loading translations for locale '${locale}' directly from file...`);
        const translations = loadTranslations(locale);
        
        if (!translations) {
            logger.warn(`[API] ✗ Translations not found for locale: ${locale}`);
            
            // Try to get available locales from directory
            let availableLocales = [];
            try {
                if (fs.existsSync(TRANSLATIONS_DIR)) {
                    const files = fs.readdirSync(TRANSLATIONS_DIR);
                    availableLocales = files
                        .filter(file => file.match(/^translations\.(.+)\.json$/))
                        .map(file => file.match(/^translations\.(.+)\.json$/)[1]);
                }
            } catch (error) {
                console.log(`[API] Could not read directory for available locales`);
            }
            
            return res.status(404).json({
                success: false,
                error: `Translations not found for locale: ${locale}`,
                availableLocales: availableLocales
            });
        }
        
        const keyCount = Object.keys(translations).length;
        logger.success(`[API] ✓ Loaded and served translations for '${locale}' directly from file (${keyCount} keys)`);
        
        res.json({
            success: true,
            locale,
            translations,
            cached: false,
            timestamp: new Date().toISOString()
        });
    } catch (error) {
        logger.error(`[API] ✗ Error in /api/translations/:locale:`, error.message);
        if (process.env.NODE_ENV !== 'production') {
            logger.error(`[API] Stack trace:`, error.stack);
        }
        res.status(500).json({
            success: false,
            error: 'Internal server error',
            message: process.env.NODE_ENV === 'production' ? 'Failed to fetch translations' : error.message
        });
    }
});

router.get('/api/configs', (req, res) => {
    try {
        console.log(`[API] GET /api/configs - Request received`);
        
        // Always load directly from file (no cache)
        console.log(`[API] Loading configs directly from file...`);
        const configs = loadConfigs();
        
        logger.success(`[API] ✓ Loaded and served configs directly from file`);
        
        res.json({
            success: true,
            configs: configs || {},
            cached: false,
            timestamp: new Date().toISOString()
        });
    } catch (error) {
        logger.error(`[API] ✗ Error in /api/configs:`, error.message);
        if (process.env.NODE_ENV !== 'production') {
            logger.error(`[API] Stack trace:`, error.stack);
        }
        res.status(500).json({
            success: false,
            error: 'Internal server error',
            message: process.env.NODE_ENV === 'production' ? 'Failed to fetch configs' : error.message
        });
    }
});

router.get('/api/configs/:key', validateConfigKey, (req, res) => {
    try {
        const { key } = req.params;
        
        if (!key || typeof key !== 'string' || key.length === 0) {
            return res.status(400).json({
                success: false,
                error: 'Invalid config key'
            });
        }
        
        const keys = key.split('.');
        
        let value = configsCache;
        for (const k of keys) {
            if (value && typeof value === 'object' && k in value) {
                value = value[k];
            } else {
                return res.status(404).json({
                    success: false,
                    error: `Config not found: ${key}`
                });
            }
        }
        
        res.json({
            success: true,
            key,
            value,
            timestamp: new Date().toISOString()
        });
    } catch (error) {
        logger.error('Error in /api/configs/:key:', error.message);
        res.status(500).json({
            success: false,
            error: 'Internal server error',
            message: process.env.NODE_ENV === 'production' ? 'Failed to fetch config' : error.message
        });
    }
});

router.get('/api/discord/config', (req, res) => {
    try {
        const configs = loadConfigs();
        
        if (!configs || !configs.discord) {
            return res.status(404).json({
                success: false,
                error: 'Discord config not found'
            });
        }
        
        const discordConfig = configs.discord;
        
        const response = {
            success: true,
            presence: discordConfig.presence || {},
            identity: discordConfig.identity || {},
            timestamp: new Date().toISOString()
        };
        
        res.json(response);
    } catch (error) {
        res.status(500).json({
            success: false,
            error: 'Internal server error',
            message: process.env.NODE_ENV === 'production' ? 'Failed to fetch Discord config' : error.message
        });
    }
});

router.get('/api/translations', (req, res) => {
    try {
        const availableLocales = Object.keys(translationsCache);
        res.json({
            success: true,
            locales: availableLocales,
            count: availableLocales.length,
            timestamp: new Date().toISOString()
        });
    } catch (error) {
        logger.error('Error in /api/translations:', error.message);
        res.status(500).json({
            success: false,
            error: 'Internal server error'
        });
    }
});

router.get('/health', (req, res) => {
    try {
        const availableLocales = Object.keys(translationsCache);
        const configsKeys = configsCache ? Object.keys(configsCache) : [];
        
        res.json({
            status: 'ok',
            service: 'translations-api',
            version: '1.0.0',
            uptime: process.uptime(),
            availableLocales,
            configsLoaded: configsCache !== null,
            configsKeys,
            timestamp: new Date().toISOString()
        });
    } catch (error) {
        res.status(503).json({
            status: 'error',
            service: 'translations-api',
            error: error.message
        });
    }
});

router.get('/api/stats', (req, res) => {
    try {
        console.log(`[API] GET /api/stats - Request received`);
        
        const availableLocales = Object.keys(translationsCache);
        const translationsCount = {};
        const fileInfo = {};
        
        availableLocales.forEach(locale => {
            const translations = translationsCache[locale];
            if (translations) { 
                const countKeys = (obj) => {
                    let count = 0;
                    for (const key in obj) {
                        if (typeof obj[key] === 'object' && obj[key] !== null && !Array.isArray(obj[key])) {
                            count += countKeys(obj[key]);
                        } else {
                            count++;
                        }
                    }
                    return count;
                };
                translationsCount[locale] = countKeys(translations);
                
                // Get file info
                const filePath = path.join(TRANSLATIONS_DIR, `translations.${locale}.json`);
                if (fs.existsSync(filePath)) {
                    const stats = fs.statSync(filePath);
                    fileInfo[locale] = {
                        size: stats.size,
                        modified: stats.mtime.toISOString(),
                        exists: true
                    };
                } else {
                    fileInfo[locale] = {
                        exists: false
                    };
                }
            }
        });
        
        const configsKeys = configsCache ? Object.keys(configsCache) : [];
        const configsFileInfo = {};
        
        if (fs.existsSync(CONFIGS_FILE)) {
            const stats = fs.statSync(CONFIGS_FILE);
            configsFileInfo.exists = true;
            configsFileInfo.size = stats.size;
            configsFileInfo.modified = stats.mtime.toISOString();
        } else {
            configsFileInfo.exists = false;
        }
        
        logger.info(`[API] ✓ Stats requested. Locales: ${availableLocales.length}, Total keys: ${Object.values(translationsCount).reduce((a, b) => a + b, 0)}`);
        
        res.json({
            success: true,
            stats: {
                locales: {
                    count: availableLocales.length,
                    list: availableLocales
                },
                translations: {
                    counts: translationsCount,
                    total: Object.values(translationsCount).reduce((a, b) => a + b, 0),
                    fileInfo: fileInfo
                },
                configs: {
                    loaded: configsCache !== null,
                    keys: configsKeys,
                    count: configsKeys.length,
                    fileInfo: configsFileInfo
                },
                cache: {
                    translationsDir: TRANSLATIONS_DIR,
                    configsFile: CONFIGS_FILE,
                    fileWatcherEnabled: enableFileWatcher
                }
            },
            timestamp: new Date().toISOString()
        });
    } catch (error) {
        logger.error(`[API] ✗ Error in /api/stats:`, error.message);
        if (process.env.NODE_ENV !== 'production') {
            logger.error(`[API] Stack trace:`, error.stack);
        }
        res.status(500).json({
            success: false,
            error: 'Internal server error'
        });
    }
});

// Get cache debug info endpoint
router.get('/api/debug', (req, res) => {
    try {
        console.log(`[API] GET /api/debug - Request received`);
        
        const debugInfo = {
            cache: {
                translations: {
                    count: Object.keys(translationsCache).length,
                    locales: Object.keys(translationsCache),
                    details: {}
                },
                configs: {
                    loaded: configsCache !== null,
                    keys: configsCache ? Object.keys(configsCache) : []
                }
            },
            files: {
                translationsDir: TRANSLATIONS_DIR,
                configsFile: CONFIGS_FILE,
                translationsDirExists: fs.existsSync(TRANSLATIONS_DIR),
                configsFileExists: fs.existsSync(CONFIGS_FILE)
            },
            settings: {
                basePath: BASE_PATH,
                fileWatcherEnabled: enableFileWatcher,
                nodeEnv: process.env.NODE_ENV || 'development'
            }
        };
        
        // Add file details for each locale
        Object.keys(translationsCache).forEach(locale => {
            const filePath = path.join(TRANSLATIONS_DIR, `translations.${locale}.json`);
            if (fs.existsSync(filePath)) {
                const stats = fs.statSync(filePath);
                debugInfo.cache.translations.details[locale] = {
                    cached: true,
                    fileExists: true,
                    fileSize: stats.size,
                    fileModified: stats.mtime.toISOString(),
                    keyCount: Object.keys(translationsCache[locale]).length
                };
            } else {
                debugInfo.cache.translations.details[locale] = {
                    cached: true,
                    fileExists: false
                };
            }
        });
        
        // List all files in directory
        if (fs.existsSync(TRANSLATIONS_DIR)) {
            try {
                const allFiles = fs.readdirSync(TRANSLATIONS_DIR);
                debugInfo.files.allFiles = allFiles;
                debugInfo.files.translationFiles = allFiles.filter(f => f.match(/^translations\.(.+)\.json$/));
            } catch (error) {
                debugInfo.files.readError = error.message;
            }
        }
        
        logger.info(`[API] ✓ Debug info requested`);
        res.json({
            success: true,
            debug: debugInfo,
            timestamp: new Date().toISOString()
        });
    } catch (error) {
        logger.error(`[API] ✗ Error in /api/debug:`, error.message);
        res.status(500).json({
            success: false,
            error: 'Internal server error',
            message: error.message
        });
    }
});

// Reload cache endpoint - useful for production when files are updated
router.post('/api/reload', (req, res) => {
    try {
        logger.info(`[API] POST /api/reload - Manual cache reload requested`);
        logger.info(`[API] Reload triggered by: ${req.ip || req.connection.remoteAddress}`);
        
        const beforeLocales = Object.keys(translationsCache);
        console.log(`[API] Cache before reload: ${beforeLocales.length} locales (${beforeLocales.join(', ')})`);
        
        reloadTranslationsCache();
        reloadConfigsCache();
        
        const afterLocales = Object.keys(translationsCache);
        logger.success(`[API] ✓ Cache reloaded successfully`);
        logger.info(`[API] Cache after reload: ${afterLocales.length} locales (${afterLocales.join(', ')})`);
        
        res.json({
            success: true,
            message: 'Cache reloaded successfully',
            availableLocales: afterLocales,
            configsLoaded: configsCache !== null && Object.keys(configsCache).length > 0,
            timestamp: new Date().toISOString()
        });
    } catch (error) {
        logger.error(`[API] ✗ Error reloading cache:`, error.message);
        if (process.env.NODE_ENV !== 'production') {
            logger.error(`[API] Stack trace:`, error.stack);
        }
        res.status(500).json({
            success: false,
            error: 'Internal server error',
            message: process.env.NODE_ENV === 'production' ? 'Failed to reload cache' : error.message
        });
    }
});

router.use((err, req, res, next) => {
    logger.error('Unhandled error:', err.message);
    if (process.env.NODE_ENV !== 'production') {
        logger.error('Stack trace:', err.stack);
    }
    res.status(500).json({
        success: false,
        error: 'Internal server error',
        message: process.env.NODE_ENV === 'production' ? 'An error occurred' : err.message
    });
});

app.use(BASE_PATH, router);


// 404 GLOBAL
app.use((req, res) => {
    res.status(404).json({
        success: false,
        error: 'Endpoint not found',
        path: req.path,
        method: req.method
    });
});

const PORT = process.env.PORT || process.env.TRANSLATIONS_PORT || 3009;
app.listen(PORT, '0.0.0.0', () => {
    logger.success('\n' + '='.repeat(60));
    logger.success('✅ Translations & Configs API Server Started Successfully');
    logger.success('='.repeat(60));
    logger.info(`🌐 Server listening on: http://0.0.0.0:${PORT}`);
    logger.info(`📡 Base path: ${BASE_PATH}`);
    logger.info(`🔗 Health check: http://localhost:${PORT}${BASE_PATH}/health`);
    logger.info(`🔄 Reload endpoint: POST http://localhost:${PORT}${BASE_PATH}/api/reload`);
    logger.info(`📊 Stats endpoint: GET http://localhost:${PORT}${BASE_PATH}/api/stats`);
    logger.info(`🌍 Environment: ${process.env.NODE_ENV || 'development'}`);
    logger.info(`📁 Translations directory: ${TRANSLATIONS_DIR}`);
    
    // Detailed cache status
    const locales = Object.keys(translationsCache);
    logger.info(`\n📦 Cache Status:`);
    logger.info(`   Translations: ${locales.length} locale(s) loaded`);
    if (locales.length > 0) {
        locales.forEach(locale => {
            const keys = translationsCache[locale] ? Object.keys(translationsCache[locale]).length : 0;
            logger.info(`   - ${locale}: ${keys} keys`);
        });
    } else {
        logger.warn(`   ⚠ No translations loaded!`);
    }
    
    logger.info(`   Configs: ${configsCache && Object.keys(configsCache).length > 0 ? '✓ Loaded' : '✗ Not loaded'}`);
    
    // File watcher status
    logger.info(`\n👀 File Watcher: ${enableFileWatcher ? '✓ Enabled' : '✗ Disabled'}`);
    if (!enableFileWatcher) {
        logger.info(`   Use POST ${BASE_PATH}/api/reload to reload cache after file changes`);
    }
    

});

module.exports = app;
