"use strict";
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.config = void 0;
const dotenv = __importStar(require("dotenv"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const fs = __importStar(require("fs"));
dotenv.config();
// Load JSON config file if it exists
let fileConfig = {};
const configPaths = [
    process.env.APPSTATS_CONFIG,
    path.join(process.cwd(), 'agent-config.json'),
    path.join(__dirname, '..', 'agent-config.json'),
    path.join(__dirname, 'agent-config.json'),
    // Common install locations
    'C:\\EmtelleAnalytics\\Agent\\agent-config.json',
    'C:\\AppStats\\Agent\\agent-config.json',
    '/opt/appstats/agent/agent-config.json',
];
for (const p of configPaths) {
    if (p && fs.existsSync(p)) {
        try {
            // Strip BOM (Byte Order Mark) that PowerShell's Out-File adds
            let raw = fs.readFileSync(p, 'utf-8');
            if (raw.charCodeAt(0) === 0xFEFF) {
                raw = raw.slice(1);
            }
            fileConfig = JSON.parse(raw);
            console.log(`[AppStats] Loaded config from: ${p}`);
            break;
        }
        catch (e) {
            console.error(`[AppStats] Failed to parse config file ${p}:`, e);
        }
    }
}
const deriveWsUrlFromHttp = (httpUrl, fallbackWsUrl) => {
    try {
        const httpParsed = new URL(String(httpUrl || '').trim());
        const wsProto = httpParsed.protocol === 'https:' ? 'wss:' : 'ws:';
        let wsPort = '';
        try {
            const fallbackParsed = new URL(String(fallbackWsUrl || '').trim());
            wsPort = fallbackParsed.port || '';
        }
        catch { }
        if (!wsPort)
            wsPort = wsProto === 'wss:' ? '443' : '80';
        return `${wsProto}//${httpParsed.hostname}${wsPort ? `:${wsPort}` : ''}`;
    }
    catch {
        return String(fallbackWsUrl || '').trim();
    }
};
const normalizeTransportMode = (value) => {
    const raw = String(value || '').trim().toLowerCase();
    if (raw === 'force_wss' || raw === 'force-wss')
        return 'force_wss';
    if (raw === 'force-wireguard')
        return 'force_wireguard';
    if (raw === 'force_wireguard')
        return 'force_wireguard';
    return 'auto';
};
const normalizeChannelPriority = (value) => {
    const defaults = ['wireguard', 'primary', 'secondary'];
    const rawItems = Array.isArray(value)
        ? value.map((v) => String(v || '').trim().toLowerCase())
        : String(value || '').split(',').map((v) => v.trim().toLowerCase()).filter(Boolean);
    const normalized = [];
    for (const item of rawItems) {
        if (item === 'wireguard' || item === 'primary' || item === 'secondary') {
            if (!normalized.includes(item))
                normalized.push(item);
        }
    }
    for (const fallback of defaults) {
        if (!normalized.includes(fallback))
            normalized.push(fallback);
    }
    return normalized;
};
const resolvedServerUrl = process.env.SERVER_URL || fileConfig.serverUrl || fileConfig.serverId || 'http://localhost:3000';
const resolvedWsUrl = process.env.WS_URL || fileConfig.wsUrl || 'ws://localhost:3001';
const resolvedPrimaryServerUrl = process.env.PRIMARY_SERVER_URL || fileConfig.primaryServerUrl || resolvedServerUrl;
const resolvedPrimaryWsUrl = process.env.PRIMARY_WS_URL || fileConfig.primaryWsUrl || resolvedWsUrl;
const resolvedSecondaryServerUrl = process.env.SECONDARY_SERVER_URL || fileConfig.secondaryServerUrl || '';
const resolvedSecondaryWsUrl = process.env.SECONDARY_WS_URL
    || fileConfig.secondaryWsUrl
    || (resolvedSecondaryServerUrl ? deriveWsUrlFromHttp(resolvedSecondaryServerUrl, resolvedPrimaryWsUrl) : '');
const resolvedTransportMode = normalizeTransportMode(process.env.REPORTING_TRANSPORT_MODE
    || process.env.TRANSPORT_MODE
    || fileConfig.transportMode);
const resolvedChannelPriority = normalizeChannelPriority(process.env.REPORTING_CHANNEL_PRIORITY
    || process.env.CHANNEL_PRIORITY
    || fileConfig.channelPriority);
const resolvedWireguardUrl = String(fileConfig.wireguardUrl || fileConfig.wireguardServerUrl || '').trim();
const resolvedWireguardWsUrl = String(fileConfig.wireguardWsUrl || fileConfig.wireguardWsServerUrl || '').trim();
const resolvedWireguardActive = fileConfig.wireguardActive === true;
exports.config = {
    server: {
        url: resolvedServerUrl,
        wsUrl: resolvedWsUrl,
        primaryUrl: resolvedPrimaryServerUrl,
        primaryWsUrl: resolvedPrimaryWsUrl,
        secondaryUrl: resolvedSecondaryServerUrl,
        secondaryWsUrl: resolvedSecondaryWsUrl,
        transportMode: resolvedTransportMode,
        channelPriority: resolvedChannelPriority,
        wireguardUrl: resolvedWireguardUrl,
        wireguardWsUrl: resolvedWireguardWsUrl,
        wireguardActive: resolvedWireguardActive,
        token: process.env.AGENT_TOKEN || fileConfig.token || '',
    },
    agent: {
        tags: process.env.AGENT_TAGS
            ? process.env.AGENT_TAGS.split(',').map(s => s.trim())
            : (fileConfig.tags || ['default']),
        groups: process.env.AGENT_GROUPS
            ? process.env.AGENT_GROUPS.split(',').map(s => s.trim())
            : (fileConfig.groups || ['default']),
        hostname: os.hostname(),
        platform: os.platform(),
        arch: os.arch(),
        allowTlsDowngrade: process.env.WS_ALLOW_TLS_DOWNGRADE === 'false'
            ? false
            : (fileConfig.allowTlsDowngrade === false ? false : true),
    },
    intervals: {
        system: parseInt(process.env.SYSTEM_INTERVAL || '') || fileConfig?.collectors?.system?.interval || 30000,
        process: parseInt(process.env.PROCESS_INTERVAL || '') || fileConfig?.collectors?.process?.interval || 60000,
        network: parseInt(process.env.NETWORK_INTERVAL || '') || fileConfig?.collectors?.network?.interval || 60000,
        wifi: parseInt(process.env.WIFI_INTERVAL || '') || fileConfig?.collectors?.wifi?.interval || 120000,
        productivity: parseInt(process.env.PRODUCTIVITY_INTERVAL || '') || fileConfig?.collectors?.productivity?.interval || 5000,
        activity: parseInt(process.env.ACTIVITY_INTERVAL || '') || fileConfig?.collectors?.activity?.interval || 5000,
        browser: parseInt(process.env.BROWSER_INTERVAL || '') || 30000,
        heartbeat: fileConfig?.heartbeatInterval || 60000,
    },
    logging: {
        level: process.env.LOG_LEVEL || 'info',
        file: process.env.LOG_FILE || path.join(process.cwd(), 'logs', 'agent.log'),
    },
    upgrade: {
        autoUpdate: process.env.AUTO_UPDATE !== 'false',
        checkInterval: parseInt(process.env.UPDATE_CHECK_INTERVAL || '3600000'),
        installPath: process.env.INSTALL_PATH || path.resolve(__dirname, '..'),
    },
};
//# sourceMappingURL=config.js.map