/**
 * Extension logger - captures logs to disk for analysis
 * Writes to .vscode/logs/acurity-extension.log
 */

import * as fs from "fs";
import * as path from "path";
import * as os from "os";

let logFile = null;
let loggingEnabled = false;
let logReady = Promise.resolve();
let writeQueue = Promise.resolve();

function queueLogWrite(text) {
    if (!logFile) {
        return;
    }

    writeQueue = writeQueue
        .then(() => logReady)
        .then(() => fs.promises.appendFile(logFile, text))
        .catch((e) => {
            console.error('[Acurity Logger] Failed to write to log file:', e.message);
        });
}

/**
 * Initialize the logger
 */
function initLogger() {
    const logsDir = path.join(os.homedir(), '.vscode', 'logs');
    logFile = path.join(logsDir, 'acurity-extension.log');

    logReady = fs.promises
        .mkdir(logsDir, { recursive: true })
        .then(() => fs.promises.writeFile(logFile, `[Acurity Extension Log]\nStarted at: ${new Date().toISOString()}\n\n`))
        .catch((e) => {
            console.error('[Acurity Logger] Failed to initialize:', e.message);
            logFile = null;
        });
}

/**
 * Enables or disables extension logging.
 * @param {boolean} enabled - True to enable logging
 */
function setLoggingEnabled(enabled) {
    loggingEnabled = !!enabled;
}

function isLoggingEnabled() {
    return loggingEnabled;
}

/**
 * Log a message to file and console
 * @param {string} level - DEBUG, LOG, WARN, or ERROR
 * @param {string} message - Log message
 * @param {any} data - Optional data to log
 */
function log(level, message, data) {
    if (!loggingEnabled && level !== 'ERROR') {
        return;
    }

    const timestamp = new Date().toISOString();
    const prefix = `[${timestamp}] [${level}]`;
    const logMessage = data ? `${prefix} ${message} ${JSON.stringify(data)}` : `${prefix} ${message}`;
    
    // Always log to console
    if (level === 'ERROR') {
        console.error(logMessage);
    } else if (level === 'WARN') {
        console.warn(logMessage);
    } else {
        console.log(logMessage);
    }
    
    // Queue file writes asynchronously to avoid blocking extension runtime paths.
    queueLogWrite(logMessage + '\n');
}

const debug = (msg, data) => log('DEBUG', msg, data);
const logExport = (msg, data) => log('LOG', msg, data);
const warn = (msg, data) => log('WARN', msg, data);
const error = (msg, data) => log('ERROR', msg, data);

export {
    initLogger,
    setLoggingEnabled,
    isLoggingEnabled,
    debug,
    logExport as log,
    warn,
    error
};

