const fs = require('fs');
const puppeteer = require('puppeteer');
const { execSync } = require('child_process');
const path = require('path');

const JASONBOXINFO_URL = 'http://192.168.178.1/jason_boxinfo.xml';
const BROWSER_PATH = 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe';

let RouterTyp = '';
let RouterJasonSerial = '';
let RouterJasonMac = '';
let Router2hzStärke = '';
let Router5hzStärke = '';
let testVariable01 = [];

function errorLogFile(err, source = 'Unbekannt') {
    const timestamp = new Date().toISOString().replace(/[:]/g, '-');
    const dir = path.join(__dirname, 'errors');
    if (!fs.existsSync(dir)) fs.mkdirSync(dir);

    const filename = `error_${timestamp}.txt`;
    const filepath = path.join(dir, filename);
    const content = `[${new Date().toLocaleString()}] Fehlerquelle: ${source}\n\n${err.stack || err.message || err}`;
    fs.writeFileSync(filepath, content, 'utf-8');
}

function jasonSerialToMac(boxSerial) {
    return boxSerial.toLowerCase().match(/.{1,2}/g).slice(0, 5).join(':');
}

function delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

(async () => {
    console.log("--- Wlan-Test gestartet ---");
    let totalOutput = '';
    let testOutput = '';
    let boxSerial = '';
    let boxMacPrefix = '';
    let jasonContent = '';

    // === BOXINFO AUSLESEN ===
    try {
        const browser = await puppeteer.launch({
            headless: "new",
            executablePath: BROWSER_PATH,
            args: ['--no-sandbox', '--disable-setuid-sandbox']
        });

        const page = await browser.newPage();
        await page.goto(JASONBOXINFO_URL, { waitUntil: 'domcontentloaded' });
        jasonContent = await page.evaluate(() => document.body.innerText);
        await browser.close();

        const jasonSerial = jasonContent.match(/<j:Serial>(.+?)<\/j:Serial>/);
        RouterTyp = jasonContent.match(/<j:Name>(.+?)<\/j:Name>/)?.[1] || 'Unbekannt';
        RouterJasonSerial = jasonSerial?.[1]?.trim() || '';

        if (!RouterJasonSerial) {
            console.error("❌ Keine Serial in der jason_boxinfo gefunden!");
            return;
        }

        boxSerial = RouterJasonSerial;
        boxMacPrefix = jasonSerialToMac(boxSerial);
        RouterJasonMac = boxMacPrefix;

        totalOutput += `\n🔗 Router-Infos:\n`;
        totalOutput += `🔧 Typ: ${RouterTyp}\n`;
        totalOutput += `🔧 Serial: ${boxSerial}\n`;
        totalOutput += `🔧 MAC-Prefix: ${boxMacPrefix}\n\n`;
    } catch (err) {
        console.error("❌ Fehler bei jason_boxinfo:", err.message);
        errorLogFile(err, 'Jason-Boxinfo');
        return;
    }

    // === WLAN-SCAN MIT RETRY ===
    const maxRetryTime = 3 * 60 * 1000;
    const retryDelay = 1000;
    const startTime = Date.now();

    let Router2hzGefunden = false;
    let Router5hzGefunden = false;
    let Router2hzSignal = null;
    let Router5hzSignal = null;
    let macTreffer = 0;

    while (Date.now() - startTime < maxRetryTime) {
        try {
            const result = execSync('powershell -Command "netsh wlan show networks mode=bssid"', { encoding: 'utf-8' });
            const lines = result.split(/\r?\n/);
            testVariable01 = lines

            macTreffer = 0;
            Router2hzGefunden = false;
            Router5hzGefunden = false;
            Router2hzSignal = null;
            Router5hzSignal = null;

            for (let i = 0; i < lines.length; i++) {
                const trimmed = lines[i].trim();
                const match = trimmed.match(/BSSID[D]?\s*\d+\s*:\s*([0-9A-Fa-f:]{17})/);

                if (match) {
                    const mac = match[1].toLowerCase();
                    // console.log(`🔍 Vergleich: ${mac} ↔ ${boxMacPrefix}`);

                    if (mac.startsWith(boxMacPrefix)) {
                        console.log("✅ MAC-Übereinstimmung erkannt!");
                        macTreffer++;

                        let kanal = null;
                        let signal = null;

                        for (let j = 1; j <= 4 && i + j < lines.length; j++) {
                            const nextLine = lines[i + j].trim();
                            const kanalMatch = nextLine.match(/Kanal\s*:\s*(\d+)/);
                            if (kanalMatch) kanal = parseInt(kanalMatch[1]);

                            const signalMatch = nextLine.match(/Signal\s*:\s*(\d+)%/);
                            if (signalMatch) signal = parseInt(signalMatch[1]);
                        }

                        if (kanal !== null && signal !== null) {
                            if (kanal >= 1 && kanal <= 13) {
                                Router2hzGefunden = true;
                                Router2hzSignal = signal;
                                Router2hzStärke = `${signal}%`;
                            } else if (kanal >= 36 && kanal <= 165) {
                                Router5hzGefunden = true;
                                Router5hzSignal = signal;
                                Router5hzStärke = `${signal}%`;
                            }
                        }
                    }
                }
            }

            if (macTreffer > 0) break;
            else {
                console.log("⏳ Keine MAC-Übereinstimmung, neuer Versuch in 5 Sekunden...");
                await delay(retryDelay);
            }

        } catch (err) {
            console.error("❌ Fehler beim WLAN-Scan:", err.message);
            errorLogFile(err, 'WLAN-Scan');
            await delay(retryDelay);
        }
    }

    // === AUSWERTUNG ===
    testOutput += `\n🔍 Übereinstimmung:\n`;
    if (macTreffer > 0) {
        testOutput += `✅ ${macTreffer} BSSID(s) mit Router-MAC gefunden.\n`;
    } else {
        testOutput += `❌ Keine Übereinstimmung nach 3 Minuten.\n`;
        errorLogFile(`Kein MAC-Treffer für Prefix ${boxMacPrefix} nach 3 Minuten`, 'MAC-Abgleich');
        console.error(testOutput);
        fs.writeFileSync("wlanscan_debug.txt", totalOutput + testOutput, "utf-8");
        process.exit(1);
    }

    testOutput += `\n📡 Signalstärkenanalyse:\n`;
    if (Router2hzGefunden) {
        testOutput += `✅ 2,4 GHz Signal: ${Router2hzSignal}%\n`;
        if (Router2hzSignal < 80) testOutput += `⚠️  2,4 GHz Signal < 80%!\n`;
    } else {
        testOutput += `❌ 2,4 GHz NICHT gefunden!\n`;
    }

    if (Router5hzGefunden) {
        testOutput += `✅ 5 GHz Signal: ${Router5hzSignal}%\n`;
        if (Router5hzSignal < 80) testOutput += `⚠️  5 GHz Signal < 80%!\n`;
    } else {
        testOutput += `❌ 5 GHz NICHT gefunden!\n`;
    }

    if (!Router2hzGefunden || Router2hzSignal < 80 || !Router5hzGefunden || Router5hzSignal < 80) {
        errorLogFile(
            `Signalprüfung kritisch:\nTreffer: ${macTreffer}\n2,4GHz: ${Router2hzGefunden ? Router2hzSignal + '%' : 'NICHT GEFUNDEN'}\n5GHz: ${Router5hzGefunden ? Router5hzSignal + '%' : 'NICHT GEFUNDEN'}`,
            'WLAN-Signaltest'
        );
    }

    // === AUSGABE ===
    console.log(totalOutput);
    console.log(testOutput);
    console.log(`\n-----------------------------------\n`)
    // console.log(`${testVariable01}`)
    fs.writeFileSync("wlanscan_debug.txt", totalOutput + testOutput, "utf-8");
})();
