#!/usr/bin/env python3
"""t1136: online multiplayer uses the same presentation as Offline Strijd.

Two (and a third) Playwright clients against a local PHP server with
loopback test-auth. After the match starts we inspect MiniLayout and
feed shot_flights through Online._handleTransitions — the same path
a real poll uses — then assert sides/outer-edge/pad, around-field
C¹ arcs, land_col endings, grey hits, launch from the cell, and a
smooth dive into the spawn pose.
"""
from __future__ import annotations

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",
]
PHP = shutil.which("php") or str(Path.home() / ".local/bin/php")
FAILURES = []
URL = ""


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=open(str(Path(data_dir) / "php.log"), "w"),
        env=env,
    )
    time.sleep(0.5)
    if proc.poll() is not None:
        log = Path(data_dir) / "php.log"
        err = log.read_text(encoding="utf-8", errors="replace") if log.exists() else ""
        raise RuntimeError("php -S failed: " + err)
    return proc


def login(page, n):
    page.goto(f"{URL}auth.php?test={n}&next=index.html",
              wait_until="domcontentloaded", timeout=15000)
    page.wait_for_timeout(250)
    page.goto(f"{URL}index.html?online=1",
              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)


INSPECT = """() => {
    const plan = app.miniLayout || {};
    const fieldEl = app.scene && app.scene.canvas;
    const fr = fieldEl ? fieldEl.getBoundingClientRect() : null;
    const minis = [...document.querySelectorAll('#minis .mini')].map((el) => {
        const r = el.getBoundingClientRect();
        return {
            id: el.getAttribute('data-player'),
            left: r.left, right: r.right, top: r.top, bottom: r.bottom
        };
    });
    const me = Online.mePlayer && Online.mePlayer();
    const ops = (Online.opponents && Online.opponents()) || [];
    return {
        mode: plan.mode,
        sidesClass: document.getElementById('minis').classList.contains('sides'),
        n: plan.n,
        fieldY: app.fieldY,
        hudH: app.hudH,
        pad: (typeof MiniLayout !== 'undefined') ? MiniLayout.ARC_TOP_PAD : null,
        field: fr ? { left: fr.left, right: fr.right, top: fr.top, bottom: fr.bottom,
                       width: fr.width, height: fr.height } : null,
        minis,
        positions: plan.positions || [],
        me: me && me.id,
        opponents: ops.map(o => o.id),
        online: !!app.online,
        offline: !!app.offline,
        vw: window.innerWidth,
        vh: window.innerHeight
    };
}"""


POLL_FLIGHTS = """() => {
    const me = Online.mePlayer();
    const ops = Online.opponents() || [];
    const a = ops[0];
    const b = ops[1] || ops[0];
    if (!a || !me) return { error: 'no opponents or me' };
    const field = app.scene.canvas.getBoundingClientRect();
    if (Online.clearFlights) Online.clearFlights();
    // Exact poll path: shot_flights only, no rememberFlightLocal (t1136).
    Online._handleTransitions('playing', {
        incoming: [],
        shot_results: [],
        shot_flights: [
            { id: 601, client_id: 'on-e2p', from_id: a.id, from_user: a.id,
              target_id: me.id, miss: false, color: 1, flight_duration: 1.2,
              age: 0.5, land_col: 3, col: 6, y: 13 },
            { id: 602, client_id: 'on-p2e', from_id: me.id, from_user: me.id,
              target_id: a.id, miss: false, color: 0, flight_duration: 1.2,
              age: 0.35, land_col: 5, col: 4, y: 13 },
            { id: 603, client_id: 'on-e2e', from_id: a.id, from_user: a.id,
              target_id: b.id, miss: false, color: 2, flight_duration: 1.2,
              age: 0.45, land_col: 7, col: 2, y: 13 },
            { id: 604, client_id: 'on-miss', from_id: b.id, from_user: b.id,
              target_id: null, miss: true, color: 3, flight_duration: 1.2,
              age: 0.3, col: 1, y: 13 }
        ]
    });
    Online.tickFlights();
    const expectedEndX = field.left + ((3 + 0.5) / 10) * field.width;
    const expectedEndY = field.top + (1 - 13.5 / 13) * field.height;
    const expectedStartY = field.top + (1 - 13.5 / 13) * field.height;
    const kinds = (Online._flights || []).map(f => {
        const raw = Math.min(0.999, Math.max(0, (performance.now() - f.t0) / f.duration));
        const u = f.miss ? Online.easeInOutCubic(raw) : Online.smoothParam(raw, 0.85, 0.85);
        const pt = Online.flightPointAt(f, u);
        const samples = [];
        if (f.kind === 'enemy-to-player' || f.kind === 'player-to-enemy') {
            for (let i = 0; i <= 16; i++) {
                const su = i / 16;
                const sp = Online.flightPointAt(f, su);
                const inside = !!(f.field && Online.pointInFieldInterior(sp.x, sp.y, f.field));
                const allowed = !f.field || Online.pointAllowedOnArc(sp, f.field, f.start, f.end);
                samples.push({ u: su, inside, allowed });
            }
        }
        return {
            kind: f.kind, miss: f.miss, color: f.color, landCol: f.landCol,
            start: f.start, end: f.end, pos: pt,
            startScale: f.startScale, endScale: f.endScale,
            parent: (f.el && f.el.parentElement && f.el.parentElement.id) || '',
            src: (f.el && (f.el.getAttribute('src') || f.el.src)) || '',
            hasCurve: !!f.curve,
            d0: f.curve ? Online.curveDeriv(f.curve, 0) : null,
            d1: f.curve ? Online.curveDeriv(f.curve, 1) : null,
            samples,
            forbidden: samples.filter(s => s.inside && !s.allowed).length
        };
    });
    return {
        kinds,
        expectedEndX, expectedEndY, expectedStartY,
        field: { left: field.left, right: field.right, top: field.top,
                 bottom: field.bottom, width: field.width, height: field.height },
        front: document.querySelectorAll('#flights .flight').length,
        back: document.querySelectorAll('#flights-back .flight').length
    };
}"""


def assert_layout(info, tag, n_ops):
    check(info.get("online") is True, f"{tag}: app.online is true")
    check(info.get("offline") is False, f"{tag}: not in offline mode")
    check(info.get("mode") == "sides", f"{tag}: mode is sides (got {info.get('mode')})")
    check(info.get("sidesClass"), f"{tag}: #minis has .sides")
    check((info.get("n") or 0) >= 1, f"{tag}: at least one opponent mini (n={info.get('n')})")
    if (info.get("n") or 0) < n_ops:
        print(f"note {tag}: wanted {n_ops} opponents, got {info.get('n')} (flights still verified)")
    pad = info.get("pad") or 0
    if pad and info.get("hudH") is not None and info.get("fieldY") is not None:
        check(info["fieldY"] >= info["hudH"] + pad - 1,
              f"{tag}: ARC_TOP_PAD (fieldY={info['fieldY']} hud={info['hudH']} pad={pad})")
    field = info.get("field") or {}
    minis = info.get("minis") or []
    vw = info.get("vw") or 0
    # Outer-edge: first two minis sit near the left and right screen edges.
    if len(minis) >= 1:
        lefts = sorted(minis, key=lambda m: m["left"])
        check(lefts[0]["left"] < 40,
              f"{tag}: leftmost mini is on the outer left edge ({lefts[0]['left']:.0f})")
    if len(minis) >= 2:
        rights = sorted(minis, key=lambda m: -m["right"])
        check(abs(vw - rights[0]["right"]) < 40,
              f"{tag}: rightmost mini is on the outer right edge "
              f"(right={rights[0]['right']:.0f} vw={vw})")
        # Bottom-aligned with the field
        if field.get("bottom"):
            for m in minis:
                check(abs(m["bottom"] - field["bottom"]) < 16,
                      f"{tag}: mini {m['id']} bottom-aligned "
                      f"(mini={m['bottom']:.0f} field={field['bottom']:.0f})")


def assert_online_flights(info, tag):
    kinds = {k["kind"]: k for k in info.get("kinds") or []}
    check("player-to-enemy" in kinds, f"{tag}: player-to-enemy via shot_flights")
    check("enemy-to-player" in kinds, f"{tag}: enemy-to-player via shot_flights")
    if "player-to-enemy" in kinds:
        k = kinds["player-to-enemy"]
        check(k.get("hasCurve"), f"{tag}: p2e smooth curve")
        check(k.get("color") == -1 or "gray" in (k.get("src") or "").lower(),
              f"{tag}: p2e is grey")
        if k.get("start") and info.get("expectedStartY") is not None:
            check(k["start"]["y"] <= info["field"]["top"] + 2,
                  f"{tag}: p2e launches at the exit (at/above the canvas top) "
                  f"(y={k['start']['y']:.1f} top={info['field']['top']:.1f})")
            check(abs(k["start"]["y"] - info["expectedStartY"]) < 10,
                  f"{tag}: p2e start at y=13 exit pose")
        if k.get("d0"):
            check(k["d0"]["y"] < 0, f"{tag}: p2e leaves going up")
        check(k.get("forbidden", 0) == 0, f"{tag}: p2e corridors only")
    if "enemy-to-player" in kinds:
        k = kinds["enemy-to-player"]
        check(k.get("hasCurve"), f"{tag}: e2p smooth curve")
        check(k.get("landCol") == 3, f"{tag}: e2p land_col=3 (got {k.get('landCol')})")
        check(k.get("color") == -1 or "gray" in (k.get("src") or "").lower(),
              f"{tag}: e2p is grey")
        if k.get("end") and info.get("expectedEndX") is not None:
            check(abs(k["end"]["x"] - info["expectedEndX"]) < 4,
                  f"{tag}: e2p ends at land_col x")
            check(abs(k["end"]["y"] - info["expectedEndY"]) < 10,
                  f"{tag}: e2p ends at spawn pose y=13")
        if k.get("d1"):
            check(k["d1"]["y"] > 0, f"{tag}: e2p arrives going down")
        check(abs(k.get("endScale", 0) - 1) < 0.05, f"{tag}: e2p end scale is 1")
        check(k.get("forbidden", 0) == 0, f"{tag}: e2p corridors only")
    if "enemy-to-enemy" in kinds:
        k = kinds["enemy-to-enemy"]
        check(k["parent"] == "flights-back",
              f"{tag}: e2e behind the field ({k['parent']})")
        check(k.get("color") == -1 or "gray" in (k.get("src") or "").lower(),
              f"{tag}: e2e is grey")
        check(info.get("back", 0) >= 1, f"{tag}: #flights-back has a flight")
    if "enemy-miss" in kinds:
        k = kinds["enemy-miss"]
        check(k.get("color") != -1, f"{tag}: miss keeps sender colour")


def leave_if_needed(page):
    if page.locator("#online-lobby").is_visible() and page.locator("#btn-leave-lobby").is_visible():
        page.locator("#btn-leave-lobby").click()
        page.wait_for_timeout(400)


def start_match(browser, width, height, n_players=3):
    contexts = []
    pages = []
    for i in range(n_players):
        ctx = browser.new_context(viewport={"width": width, "height": height})
        page = ctx.new_page()
        contexts.append(ctx)
        pages.append(page)
        login(page, i + 1)
        wait_visible(page, "#online-panel")
        leave_if_needed(page)

    p1 = pages[0]
    wait_visible(p1, "#btn-create")
    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 ({code})")

    for p in pages[1:]:
        wait_visible(p, "#join-code")
        p.locator("#join-code").fill(code)
        p.locator("#btn-join").click()
        wait_visible(p, "#online-lobby")
        p.wait_for_timeout(400)
    for _ in range(20):
        if p1.locator("#lobby-players li").count() >= n_players:
            break
        p1.wait_for_timeout(300)
    counts = [pg.locator("#lobby-players li").count() for pg in pages]
    print(f"lobby player counts: {counts}")
    check(counts[0] >= 2, f"host sees at least 2 players ({counts[0]})")

    for p in pages:
        # ready
        btn = p.locator("#btn-ready")
        if btn.is_visible():
            btn.click()
        p.wait_for_timeout(200)

    start = p1.locator("#btn-start")
    enabled = False
    for _ in range(20):
        if start.is_visible() and start.is_enabled():
            enabled = True
            break
        p1.wait_for_timeout(300)
    check(enabled, "host can start")
    if not enabled:
        raise RuntimeError("host Starten stayed disabled")
    start.click()
    for i, p in enumerate(pages):
        try:
            p.wait_for_function(
                "() => app && app.mode === 'playing' && app.online && app.core",
                timeout=15000,
            )
        except Exception as e:
            state = p.evaluate(
                """() => ({
                    mode: typeof app === 'undefined' ? 'no-app' : app.mode,
                    online: !!(typeof app !== 'undefined' && app.online),
                    hasCore: !!(typeof app !== 'undefined' && app.core),
                    lobby: (typeof Online !== 'undefined' && Online.lobby)
                        ? { status: Online.lobby.status, n: (Online.lobby.players||[]).length }
                        : null,
                    visible: {
                        panel: !document.getElementById('online-panel').hidden,
                        lobby: !document.getElementById('online-lobby').hidden,
                        hud: !document.getElementById('hud').hidden,
                        planet: !document.getElementById('planet-select').hidden
                    }
                })"""
            )
            shot(p, f"t1136-debug-p{i+1}.png")
            print(f"start failed on player {i+1}: {state}")
            raise
        p.wait_for_selector("canvas", state="visible", timeout=8000)
        p.wait_for_timeout(500)
    return contexts, pages


def run_viewport(browser, name, width, height, n_players=3):
    print(f"\n======== online {name} ========")
    contexts, pages = start_match(browser, width, height, n_players=n_players)
    p1 = pages[0]
    info = p1.evaluate(INSPECT)
    print("layout", {k: info.get(k) for k in
                     ("mode", "n", "fieldY", "hudH", "pad", "online", "vw", "vh",
                      "sidesClass", "opponents")})
    assert_layout(info, name, n_players - 1)
    shot(p1, f"t1136-{name}-layout.png")

    flights = p1.evaluate(POLL_FLIGHTS)
    print("flights", {k: flights.get(k) for k in
                      ("front", "back", "expectedEndX", "expectedEndY", "expectedStartY")})
    for knd in flights.get("kinds") or []:
        print(f"    {knd['kind']}: land={knd.get('landCol')} color={knd.get('color')} "
              f"curve={knd.get('hasCurve')} start={knd.get('start')} end={knd.get('end')}")
    if flights.get("error"):
        check(False, f"{name}: {flights['error']}")
    else:
        assert_online_flights(flights, name)
        shot(p1, f"t1136-{name}-midarc.png")
        # early / late
        for age_delta, label in ((-0.3, "early"), (0.3, "late")):
            # re-inject by running POLL_FLIGHTS is mid; use evaluate with age via a small wrapper
            p1.evaluate(
                """(age) => {
                    const payload = { incoming: [], shot_results: [], shot_flights: [] };
                    // Just retick existing? Clear and let POLL-like ages set in a short helper.
                    const me = Online.mePlayer();
                    const ops = Online.opponents() || [];
                    const a = ops[0], b = ops[1] || ops[0];
                    if (Online.clearFlights) Online.clearFlights();
                    Online._handleTransitions('playing', {
                        incoming: [], shot_results: [],
                        shot_flights: [
                            { id: 701, client_id: 'e-'+age, from_id: a.id, target_id: me.id,
                              miss: false, color: 1, flight_duration: 1.2, age: age,
                              land_col: 3, col: 6, y: 13 },
                            { id: 702, client_id: 'p-'+age, from_id: me.id, target_id: a.id,
                              miss: false, color: 0, flight_duration: 1.2, age: age,
                              land_col: 5, col: 4, y: 13 }
                        ]
                    });
                    Online.tickFlights();
                }""",
                0.2 if label == "early" else 0.85,
            )
            shot(p1, f"t1136-{name}-midarc-{label}.png")

    for c in contexts:
        c.close()


def main():
    global URL
    port = free_port()
    data = tempfile.mkdtemp(prefix="meteors-online-")
    URL = f"http://127.0.0.1:{port}/"
    proc = start_php(port, data)
    try:
        with sync_playwright() as p:
            browser = p.chromium.launch(
                executable_path=CHROME, args=CHROME_ARGS, headless=True
            )
            run_viewport(browser, "1920x1080", 1920, 1080, n_players=2)
            run_viewport(browser, "1024x532", 1024, 532, n_players=2)
            browser.close()
    finally:
        proc.terminate()
        try:
            proc.wait(timeout=3)
        except subprocess.TimeoutExpired:
            proc.kill()
        shutil.rmtree(data, ignore_errors=True)

    if FAILURES:
        print(f"\n{len(FAILURES)} failure(s):")
        for f in FAILURES:
            print(" -", f)
        return 1
    print("\nall online presentation checks passed")
    return 0


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