#!/usr/bin/env python3
"""Stage-2 online flow: two Playwright contexts against a local PHP server.
Also a live solo/online-panel check where the public site is reachable.
"""
from __future__ import annotations

import json
import os
import shutil
import socket
import subprocess
import sys
import tempfile
import time
from pathlib import Path

from playwright.sync_api import sync_playwright

ROOT = Path("/workspace/meteors")
OUT = Path("/workspace/meteors-shots")
OUT.mkdir(parents=True, exist_ok=True)
CHROME = "/usr/bin/google-chrome"
CHROME_ARGS = [
    "--use-gl=angle",
    "--use-angle=swiftshader",
    "--no-sandbox",
    "--disable-dev-shm-usage",
]
LIVE = "https://projects.timfalken.com/meteors/"
PHP = shutil.which("php") or str(Path.home() / ".local/bin/php")
FAILURES = []


def free_port():
    s = socket.socket()
    s.bind(("127.0.0.1", 0))
    port = s.getsockname()[1]
    s.close()
    return port


def check(cond, msg):
    if not cond:
        FAILURES.append(msg)
        print("FAIL", msg)
    else:
        print("OK  ", msg)
    return cond


def shot(page, name):
    path = OUT / name
    page.screenshot(path=str(path), full_page=False)
    print(f"wrote {path} ({path.stat().st_size} bytes)")
    return path


def start_php(port, data_dir):
    env = os.environ.copy()
    env["METEORS_DATA_DIR"] = str(data_dir)
    proc = subprocess.Popen(
        [PHP, "-S", f"127.0.0.1:{port}", "-t", str(ROOT / "build"), str(ROOT / "build" / "router.php")],
        cwd=str(ROOT / "build"),
        stdout=subprocess.DEVNULL,
        stderr=subprocess.PIPE,
        env=env,
    )
    time.sleep(0.4)
    if proc.poll() is not None:
        err = proc.stderr.read().decode("utf-8", "replace") if proc.stderr else ""
        raise RuntimeError("php -S failed: " + err)
    return proc


def login(page, n, next_path="index.html?online=1"):
    # Log in first (test= is only honoured on loopback), then open the online panel.
    page.goto(f"{URL}auth.php?test={n}&next=index.html", wait_until="domcontentloaded", timeout=15000)
    page.wait_for_timeout(300)
    page.goto(f"{URL}{next_path}", wait_until="domcontentloaded", timeout=15000)
    page.wait_for_timeout(400)


def wait_visible(page, sel, timeout=8000):
    page.locator(sel).wait_for(state="visible", timeout=timeout)


def run_two_contexts(browser):
    print("\n======== two local contexts ========")
    c1 = browser.new_context(viewport={"width": 1280, "height": 800})
    c2 = browser.new_context(viewport={"width": 1100, "height": 760})
    p1 = c1.new_page()
    p2 = c2.new_page()
    bag = []
    for p, tag in ((p1, "p1"), (p2, "p2")):
        p.on("pageerror", lambda e, tag=tag: bag.append(f"{tag} pageerror: {e}"))
        p.on("console", lambda m, tag=tag: bag.append(f"{tag} {m.type}: {m.text}") if m.type == "error" else None)

    login(p1, 1)
    login(p2, 2)
    wait_visible(p1, "#online-panel")
    wait_visible(p2, "#online-panel")
    check(p1.locator("#online-home").is_visible() or p1.locator("#online-lobby").is_visible(),
          "user 1 landed in the online panel")
    check(p2.locator("#online-home").is_visible() or p2.locator("#online-lobby").is_visible(),
          "user 2 landed in the online panel")
    # If we landed in a leftover lobby, leave first.
    for p in (p1, p2):
        if p.locator("#online-lobby").is_visible() and p.locator("#btn-leave-lobby").is_visible():
            p.locator("#btn-leave-lobby").click()
            p.wait_for_timeout(400)

    wait_visible(p1, "#btn-create")
    shot(p1, "stage2-online-home.png")
    p1.locator("#btn-create").click()
    wait_visible(p1, "#online-lobby")
    p1.wait_for_function("() => document.getElementById('lobby-code') && document.getElementById('lobby-code').textContent.trim().length >= 4", timeout=8000)
    code = p1.locator("#lobby-code").inner_text().strip()
    check(len(code) >= 4, f"lobby code visible ({code!r})")
    shot(p1, "stage2-lobby-host.png")

    wait_visible(p2, "#join-code")
    p2.locator("#join-code").fill(code)
    p2.locator("#btn-join").click()
    wait_visible(p2, "#online-lobby")
    p2.wait_for_timeout(500)
    players2 = p2.locator("#lobby-players li").count()
    players1 = p1.locator("#lobby-players li").count()
    # Host poll should pick up the joiner shortly.
    for _ in range(12):
        if p1.locator("#lobby-players li").count() >= 2:
            break
        p1.wait_for_timeout(400)
    players1 = p1.locator("#lobby-players li").count()
    check(players2 >= 2, f"guest sees two players ({players2})")
    check(players1 >= 2, f"host sees two players ({players1})")
    shot(p2, "stage2-lobby-guest.png")

    p1.locator("#btn-ready").click()
    p2.locator("#btn-ready").click()
    # Host start becomes enabled once both ready (poll).
    start = p1.locator("#btn-start")
    enabled = False
    for _ in range(16):
        if start.is_visible() and start.is_enabled():
            enabled = True
            break
        p1.wait_for_timeout(400)
    check(enabled, "host Starten is enabled when both are ready")
    shot(p1, "stage2-lobby-ready.png")
    start.click()

    # Both should enter the game: HUD + canvas + opponent minis.
    for p, name in ((p1, "host"), (p2, "guest")):
        p.wait_for_function("() => app && app.mode === 'playing' && app.online && app.core", timeout=10000)
        p.wait_for_selector("canvas", state="visible", timeout=8000)
        p.wait_for_timeout(600)
        nminis = p.locator("#minis .mini").count()
        check(nminis >= 1, f"{name} sees at least one opponent miniature ({nminis})")
        hud = p.locator("#hud").is_visible()
        check(hud, f"{name} HUD visible")
    shot(p1, "stage2-game-host.png")
    shot(p2, "stage2-game-guest.png")

    # Inject a shot so we can screenshot the flight tween.
    p1.evaluate(
        """() => {
            if (!app.core) return;
            const shots = [{id: 9001, color: 0, col: 4, y: 12}];
            Online.rememberFlightLocal(shots[0], window.innerWidth/2, 200);
            Online.queueShots(shots);
            // Force a poll-like result locally so the tween plays even before the server answers.
            Online.spawnFlights([{client_id: '9001', miss: false, target_id: Online.aliveOpponents()[0] && Online.aliveOpponents()[0].id, color: 0, flight_duration: 1.2}], {'9001': {col: 4, y: 12, color: 0}});
        }"""
    )
    p1.wait_for_timeout(350)
    flights = p1.evaluate("() => document.querySelectorAll('#flights .flight').length")
    check(flights >= 1, f"flight tween appears ({flights})")
    shot(p1, "stage2-flight.png")

    # Incoming garbage path: ingest a grey on the guest and wait a frame.
    p2.evaluate("() => { const b = app.core.ingestGarbage(); return b && {col: b.col, color: b.color, state: b.state}; }")
    p2.wait_for_timeout(200)
    grey = p2.evaluate("() => app.core.blocks.some(b => b.color === -1 && b.state === 'falling')")
    check(grey, "ingestGarbage drops a falling grey on the guest")
    shot(p2, "stage2-garbage.png")

    if bag:
        print("console:", bag[:12])
    c1.close()
    c2.close()


def run_live(browser):
    print("\n======== live site ========")
    try:
        ctx = browser.new_context(viewport={"width": 1280, "height": 800})
        page = ctx.new_page()
        page.goto(LIVE, wait_until="networkidle", timeout=20000)
        page.wait_for_timeout(600)
        title = page.locator("h1")
        check(title.is_visible() and "Meteors" in title.inner_text(), "live menu title")
        shot(page, "stage2-live-menu.png")
        # Solo still works.
        page.locator("#btn-survival").click()
        page.wait_for_timeout(600)
        if page.locator("#planet-select").is_visible():
            page.locator("#btn-planet-go").click()
            page.wait_for_timeout(800)
        playing = page.evaluate("() => app && app.mode === 'playing'")
        check(playing, "live solo Play still starts a game")
        shot(page, "stage2-live-solo.png")
        # Back via evaluating return — game-over takes 2s+ after a full lock, so just reload.
        page.goto(LIVE, wait_until="networkidle", timeout=20000)
        page.wait_for_timeout(400)
        if page.locator("#btn-online").is_visible():
            page.locator("#btn-online").click()
            page.wait_for_timeout(1200)
            shot(page, "stage2-live-online-panel.png")
            # Either unconfigured notice, login, or a live API error — solo is already confirmed.
            panel = page.locator("#online-panel").is_visible()
            check(panel, "live Online spelen opens the panel")
            body = page.locator("#online-panel").inner_text()
            print("live online panel text:", body[:400].replace("\n", " / "))
        ctx.close()
    except Exception as e:
        check(False, f"live site check: {e}")


def main():
    global URL
    if not Path(PHP).is_file():
        print("php not found at", PHP)
        return 1
    port = free_port()
    URL = f"http://127.0.0.1:{port}/"
    data = Path(tempfile.mkdtemp(prefix="meteors-pw-"))
    print("PHP", PHP, "URL", URL, "data", data)
    proc = start_php(port, data)
    try:
        with sync_playwright() as p:
            browser = p.chromium.launch(executable_path=CHROME, args=CHROME_ARGS, headless=True)
            run_two_contexts(browser)
            run_live(browser)
            browser.close()
    finally:
        proc.terminate()
        try:
            proc.wait(timeout=3)
        except Exception:
            proc.kill()
        shutil.rmtree(data, ignore_errors=True)

    print("\n======== summary ========")
    if FAILURES:
        print(f"{len(FAILURES)} failure(s):")
        for f in FAILURES:
            print(" -", f)
        return 1
    print("all stage-2 playwright checks passed")
    return 0


if __name__ == "__main__":
    sys.exit(main())
