import socketserver
import threading
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
from tools.serve_web_pc import FreeExilePCRequestHandler
from playwright.sync_api import sync_playwright

s = socketserver.TCPServer(('127.0.0.1', 0), FreeExilePCRequestHandler)
port = s.server_address[1]
threading.Thread(target=s.serve_forever, daemon=True).start()

print(f"Server started on port {port}")

with sync_playwright() as p:
    try:
        b = p.chromium.launch(channel="msedge", headless=True)
    except Exception:
        b = p.chromium.launch(headless=True)
    page = b.new_page(viewport={'width': 1920, 'height': 1080})
    errors = []
    page.on('pageerror', lambda e: errors.append(f"PageError: {e}"))
    page.on('console', lambda m: errors.append(f"ConsoleError: {m.text}") if m.type == 'error' else None)
    
    page.goto(f'http://127.0.0.1:{port}/index.html')
    page.wait_for_timeout(1500)
    
    res = page.evaluate("""() => {
        const el = document.querySelector('#skill-q .skill-icon');
        const style = window.getComputedStyle(el);
        const bg = style.backgroundImage;
        const match = bg.match(/url\\(["']?(.*?)["']?\\)/);
        const url = match ? match[1] : null;
        return new Promise((resolve) => {
            if (!url) return resolve({ found: false, naturalWidth: 0, url: null });
            const img = new Image();
            img.onload = () => resolve({ found: true, naturalWidth: img.naturalWidth, naturalHeight: img.naturalHeight, url });
            img.onerror = () => resolve({ found: true, naturalWidth: 0, error: true, url });
            img.src = url;
        });
    }""")
    print("IMAGE CHECK:", res)
    print("ALL ERRORS (Page & Console):", errors)
    assert len(errors) == 0, f"Found unexpected errors: {errors}"
    assert res['naturalWidth'] > 0, f"naturalWidth not > 0: {res}"
    print("SUCCESS: 0 errors and naturalWidth > 0 verified!")
    b.close()

s.shutdown()
