const fs = require('fs');
const path = require('path');

const colors = {
    reset: '\x1b[0m',
    bright: '\x1b[1m',
    red: '\x1b[31m',
    green: '\x1b[32m',
    yellow: '\x1b[33m',
    blue: '\x1b[34m',
    magenta: '\x1b[35m',
    cyan: '\x1b[36m'
};

// Logs directory
const LOGS_DIR = path.join(__dirname, '..', 'logs');
const LOG_FILE = path.join(LOGS_DIR, `server-${new Date().toISOString().split('T')[0]}.log`);

// Ensure logs directory exists
if (!fs.existsSync(LOGS_DIR)) {
    fs.mkdirSync(LOGS_DIR, { recursive: true });
}

function getTimestamp() {
    return new Date().toISOString();
}

function writeToFile(level, message, ...args) {
    try {
        const timestamp = getTimestamp();
        const logMessage = `[${timestamp}] [${level.toUpperCase()}] ${message} ${args.length > 0 ? JSON.stringify(args) : ''}\n`;
        fs.appendFileSync(LOG_FILE, logMessage, 'utf8');
    } catch (error) {
        // Silently fail if can't write to file
        console.error('Failed to write to log file:', error.message);
    }
}

function log(level, message, ...args) {
    const timestamp = getTimestamp();
    const color = colors[level] || colors.reset;
    
    // Output to console
    console.log(`${color}[${timestamp}] [${level.toUpperCase()}]${colors.reset} ${message}`, ...args);
    
    // Also write to file
    writeToFile(level, message, ...args);
}

const logger = {
    info: (message, ...args) => log('cyan', message, ...args),
    success: (message, ...args) => log('green', message, ...args),
    warn: (message, ...args) => log('yellow', message, ...args),
    error: (message, ...args) => log('red', message, ...args),
    debug: (message, ...args) => {
        if (process.env.NODE_ENV !== 'production') {
            log('blue', message, ...args);
        } else {
            // In production, still write debug to file but not console
            writeToFile('debug', message, ...args);
        }
    },
    // Get log file path
    getLogFile: () => LOG_FILE,
    getLogsDir: () => LOGS_DIR
};

module.exports = logger;
