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

/* =========================
   Parse a bash-style config file
   Handles: KEY=value and KEY=value  # inline comment
========================= */
function parseConfigFile(filePath) {
    const config = {};
    if (!fs.existsSync(filePath)) return config;

    const lines = fs.readFileSync(filePath, 'utf8').split('\n');
    for (const line of lines) {
        const trimmed = line.trim();
        if (!trimmed || trimmed.startsWith('#')) continue;
        const eqIdx = trimmed.indexOf('=');
        if (eqIdx === -1) continue;
        const key = trimmed.substring(0, eqIdx).trim();
        let value = trimmed.substring(eqIdx + 1).trim();
        // Strip inline comment (space + #)
        const commentIdx = value.search(/\s+#/);
        if (commentIdx !== -1) value = value.substring(0, commentIdx).trim();
        if (key && value !== undefined) config[key] = value;
    }
    return config;
}

/* =========================
   Parse Port from Config
========================= */
function parsePortFromConfig(portConfig) {
    if (!portConfig) return 1111;
    const port = Number(portConfig);
    return port >= 1 && port <= 65535 ? port : 1111;
}

/* =========================
   Export Configuration
========================= */
const libreportalConfig = parseConfigFile(path.join(__dirname, '..', '..', 'libreportal.config'));
const webuiLoginsConfig = parseConfigFile(path.join(__dirname, '..', '..', 'webui_logins'));
const webuiLogsConfig = parseConfigFile(path.join(__dirname, '..', '..', 'webui_logs'));

// Merge: later sources override earlier. webui_logins / webui_logs hold
// CFG_WEBUI_* keys generated from the system configs/webui/* and bind-mounted
// in via libreportal's compose.
const fileConfig = { ...libreportalConfig, ...webuiLoginsConfig, ...webuiLogsConfig };

const PORT = parsePortFromConfig(fileConfig.CFG_LIBREPORTAL_PORT_1) || 1111;
if (!PORT || PORT < 1 || PORT > 65535) {
    console.warn('Invalid or missing CFG_LIBREPORTAL_PORT_1 in libreportal.config, using default port 1111');
}

const COMMAND_TIMEOUT = Number(fileConfig.CFG_LIBREPORTAL_TIMEOUT || 30000);

module.exports = {
    PORT,
    COMMAND_TIMEOUT,
    fileConfig,
    FRONTEND_PATH: path.join(__dirname, '..', '..', 'frontend')
};
