"use strict";
/**
 * Logger for RepairIQ Sync Agent
 *
 * Logs to console (standalone mode) or file (service mode)
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.log = log;
exports.isService = isService;
exports.getLogFilePath = getLogFilePath;
exports.initLogger = initLogger;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const WATCH_FOLDER = process.env.WATCH_FOLDER || 'C:\\RepairIQ-EMS';
const LOG_FOLDER = path.join(WATCH_FOLDER, 'logs');
const LOG_FILE = path.join(LOG_FOLDER, 'sync-agent.log');
// Detect if running as a Windows Service
// When running as a service, there's no console window and process.stdout.isTTY is false
const IS_SERVICE = !process.stdout.isTTY && process.platform === 'win32';
/**
 * Ensure log folder exists
 */
function ensureLogFolder() {
    if (!fs.existsSync(LOG_FOLDER)) {
        fs.mkdirSync(LOG_FOLDER, { recursive: true });
    }
}
/**
 * Rotate log file if it gets too large (> 10MB)
 */
function rotateLogFile() {
    try {
        if (fs.existsSync(LOG_FILE)) {
            const stats = fs.statSync(LOG_FILE);
            const fileSizeMB = stats.size / (1024 * 1024);
            if (fileSizeMB > 10) {
                const backupFile = LOG_FILE.replace('.log', `.${Date.now()}.log`);
                fs.renameSync(LOG_FILE, backupFile);
                // Keep only last 5 backup files
                const logFiles = fs
                    .readdirSync(LOG_FOLDER)
                    .filter((f) => f.startsWith('sync-agent.') && f.endsWith('.log'))
                    .sort()
                    .reverse();
                if (logFiles.length > 5) {
                    logFiles.slice(5).forEach((f) => {
                        fs.unlinkSync(path.join(LOG_FOLDER, f));
                    });
                }
            }
        }
    }
    catch (error) {
        // Ignore rotation errors
    }
}
/**
 * Log message to console and/or file
 */
function log(message, level = 'INFO') {
    const timestamp = new Date().toISOString();
    const logMessage = `[${timestamp}] [${level}] ${message}`;
    // Always log to console in standalone mode
    if (!IS_SERVICE) {
        console.log(logMessage);
    }
    // Always log to file (both service and standalone modes)
    try {
        ensureLogFolder();
        rotateLogFile();
        fs.appendFileSync(LOG_FILE, logMessage + '\n');
    }
    catch (error) {
        // If we can't write to file in standalone mode, at least log to console
        if (!IS_SERVICE) {
            console.error(`Failed to write to log file: ${error}`);
        }
    }
}
/**
 * Check if running as a Windows Service
 */
function isService() {
    return IS_SERVICE;
}
/**
 * Get log file path
 */
function getLogFilePath() {
    return LOG_FILE;
}
/**
 * Initialize logger and log startup information
 */
function initLogger() {
    const mode = IS_SERVICE ? 'Windows Service' : 'Standalone';
    log(`==========================================================`);
    log(`RepairIQ Sync Agent Starting in ${mode} Mode`);
    log(`Process ID: ${process.pid}`);
    log(`Node Version: ${process.version}`);
    log(`Platform: ${process.platform} ${process.arch}`);
    log(`Log File: ${LOG_FILE}`);
    log(`==========================================================`);
}
//# sourceMappingURL=logger.js.map