#!/usr/bin/env python3
"""Stage 3: planet selection on desktop and mobile, plus two-player lobby picks."""
from __future__ import annotations

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

from playwright.sync_api import sync_playwright

ROOT = Path("/workspace/meteors")
SHOTS = Path("/workspace/meteors-shots")
SHOTS.mkdir(parents=True, exist_ok=True)
PHP = os.environ.get("PHP", "/home/box/.local/bin/php")
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/"
URL = None
FAILURES = []

MOBILE = {
    "viewport": {"width": 390, "height": 844},
    "device_scale_factor": 2,
    "is_mobile": True,
    "has_touch": True,
    "user_agent": (
        "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) "
        "AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 "
        "Mobile/15E148 Safari/604.1"
    ),
}


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


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


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


def start_php(port, data):
    env = os.environ.copy()
    env["METEORS_DATA_DIR"] = str(data)
    return subprocess.Popen(
        [PHP, "-S", f"127.0.0.1:{port}", "-t", str(ROOT / "build"), str(ROOT / "build" / "router.php")],
        cwd=str(ROOT / "build"),
        env=env,
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL,
    )


def open_picker(page):
    page.goto(URL, wait_until="networkidle", timeout=25000)
    page.wait_for_timeout(500)
    page.locator("#btn-survival").click()
    page.locator("#planet-select").wait_for(state="visible", timeout=8000)
    page.wait_for_timeout(300)


def cards(page):
    return page.locator("#planet-grid .planet-card")


def run_desktop(browser):
    print("\n======== desktop planet select ========")
    ctx = browser.new_context(viewport={"width": 1280, "height": 900})
    page = ctx.new_page()
    open_picker(page)
    n = cards(page).count()
    check(n >= 8 and n <= 12, f"catalog has 8–12 cards (got {n})")
    texts = [cards(page).nth(i).inner_text() for i in range(n)]
    joined = "\n".join(texts)
    for name in ("Terra", "Aurel", "Cinder", "Lunara", "Forge"):
        check(name in joined, f"desktop grid lists {name}")
    # Numeric stats, no long explanation — Terra mid values.
    terra = next(t for t in texts if t.startswith("Terra"))
    check("Terrans" in terra, "Terra people name")
    check("g 9.81" in terra and "d 1.05" in terra and "F 104 N" in terra and "Power 44%" in terra,
          "Terra numeric stats on the card")
    cinder = next(t for t in texts if t.startswith("Cinder"))
    check("Cindari" in cinder and "Power 92%" in cinder and "g 19.62" in cinder,
          "Cinder is the hardest (Power 92%)")
    aurel = next(t for t in texts if t.startswith("Aurel"))
    check("Aurelians" in aurel and "Power 0%" in aurel, "Aurel is the easiest (Power 0%)")
    # Each card has 5 unique placeholder images.
    imgs = page.locator("#planet-grid .planet-card").nth(0).locator("img")
    check(imgs.count() == 5, "five color placeholders on a card")
    shot(page, "stage3-planet-select-desktop.png")

    # Pick Cinder and start.
    page.locator('.planet-card[data-planet="cinder"]').click()
    page.wait_for_timeout(200)
    check("selected" in (page.locator('.planet-card[data-planet="cinder"]').get_attribute("class") or ""),
          "Cinder card is selected")
    page.locator("#btn-planet-go").click()
    page.wait_for_function("() => app && app.mode === 'playing' && app.core", timeout=8000)
    hud = page.evaluate("""() => ({
        name: document.getElementById('planet-name').textContent,
        stats: document.getElementById('planet-stats').textContent,
        id: app.planet && app.planet.id,
        miss: app.core && app.core.missChance,
        power: Planet.power(app.planet)
    })""")
    print("HUD", hud)
    check(hud["id"] == "cinder" and "Cinder" in hud["name"] and "Cindari" in hud["name"],
          "HUD shows Cinder · Cindari")
    check("Power 92%" in hud["stats"] and "g 19.62" in hud["stats"], "HUD shows Cinder numbers")
    check(abs(hud["miss"] - 0.05) < 1e-9, "GameCore missChance is Cinder's 5%")
    shot(page, "stage3-play-cinder-desktop.png")
    ctx.close()


def run_mobile(browser):
    print("\n======== mobile planet select ========")
    ctx = browser.new_context(**MOBILE)
    page = ctx.new_page()
    open_picker(page)
    n = cards(page).count()
    check(n >= 8, f"mobile grid has the catalog (got {n})")
    # Scroll to Cinder if needed, then pick it.
    card = page.locator('.planet-card[data-planet="cinder"]')
    card.scroll_into_view_if_needed()
    page.wait_for_timeout(200)
    shot(page, "stage3-planet-select-mobile.png")
    card.click()
    page.locator("#btn-planet-go").click()
    page.wait_for_function("() => app && app.mode === 'playing' && app.planet && app.planet.id === 'cinder'", timeout=8000)
    playing = page.evaluate("() => ({mode: app.mode, id: app.planet.id, w: window.innerWidth})")
    print("mobile play", playing)
    check(playing["mode"] == "playing" and playing["id"] == "cinder", "mobile starts Cinder after the picker")
    shot(page, "stage3-play-cinder-mobile.png")
    ctx.close()


def login(page, n):
    # test login, then land on the game with online panel openable
    page.goto(f"{URL}auth.php?test={n}&next=index.html", wait_until="networkidle", timeout=20000)
    page.wait_for_timeout(300)
    page.goto(f"{URL}index.html?online=1", wait_until="networkidle", timeout=20000)
    page.wait_for_timeout(600)
    # If the online panel isn't auto-opened, click the button.
    if not page.locator("#online-panel").is_visible():
        if page.locator("#btn-online").is_visible():
            page.locator("#btn-online").click()
            page.wait_for_timeout(800)


def run_lobby(browser):
    print("\n======== lobby planet picks (two contexts) ========")
    c1 = browser.new_context(viewport={"width": 1280, "height": 900})
    c2 = browser.new_context(viewport={"width": 1100, "height": 900})
    p1 = c1.new_page()
    p2 = c2.new_page()
    login(p1, 1)
    login(p2, 2)
    # Host creates a lobby (default planet), then picks Aurel.
    p1.locator("#btn-create").wait_for(state="visible", timeout=8000)
    p1.locator("#btn-create").click()
    p1.locator("#online-lobby").wait_for(state="visible", timeout=8000)
    p1.wait_for_timeout(400)
    p1.locator('#lobby-planet-grid .planet-card[data-planet="aurel"]').scroll_into_view_if_needed()
    p1.locator('#lobby-planet-grid .planet-card[data-planet="aurel"]').click()
    p1.wait_for_timeout(600)
    code = p1.locator("#lobby-code").inner_text().strip()
    check(len(code) == 4, f"lobby code {code}")
    # Guest joins and picks Cinder.
    p2.locator("#join-code").fill(code)
    p2.locator("#btn-join").click()
    p2.locator("#online-lobby").wait_for(state="visible", timeout=8000)
    p2.wait_for_timeout(500)
    p2.locator('#lobby-planet-grid .planet-card[data-planet="cinder"]').scroll_into_view_if_needed()
    p2.locator('#lobby-planet-grid .planet-card[data-planet="cinder"]').click()
    p2.wait_for_timeout(800)
    # Poll so both see each other's pick.
    p1.wait_for_timeout(1000)
    p2.wait_for_timeout(400)
    host_list = p1.locator("#lobby-players").inner_text()
    guest_list = p2.locator("#lobby-players").inner_text()
    print("host list:", host_list.replace("\n", " | "))
    print("guest list:", guest_list.replace("\n", " | "))
    check("Aurel" in host_list and "Cinder" in host_list, "host lobby shows both planet names")
    check("Aurel" in guest_list and "Cinder" in guest_list, "guest lobby shows both planet names")
    shot(p1, "stage3-lobby-planets-host.png")
    shot(p2, "stage3-lobby-planets-guest.png")
    # Ready and start; each plays their own planet.
    p1.locator("#btn-ready").click()
    p2.locator("#btn-ready").click()
    p1.wait_for_timeout(800)
    p1.locator("#btn-start").click()
    p1.wait_for_function("() => app && app.mode === 'playing' && app.online", timeout=10000)
    p2.wait_for_function("() => app && app.mode === 'playing' && app.online", timeout=10000)
    ids = {
        "host": p1.evaluate("() => ({id: app.planet.id, miss: app.core.missChance, name: app.planet.name})"),
        "guest": p2.evaluate("() => ({id: app.planet.id, miss: app.core.missChance, name: app.planet.name})"),
    }
    print("match planets", ids)
    check(ids["host"]["id"] == "aurel" and abs(ids["host"]["miss"] - 0.60) < 1e-9,
          "host plays Aurel (60% miss from own Power)")
    check(ids["guest"]["id"] == "cinder" and abs(ids["guest"]["miss"] - 0.05) < 1e-9,
          "guest plays Cinder (5% miss from own Power)")
    shot(p1, "stage3-game-aurel-host.png")
    shot(p2, "stage3-game-cinder-guest.png")
    c1.close()
    c2.close()


def run_live(browser):
    print("\n======== live site ========")
    try:
        ctx = browser.new_context(viewport={"width": 1280, "height": 900})
        page = ctx.new_page()
        page.goto(LIVE, wait_until="networkidle", timeout=25000)
        page.wait_for_timeout(800)
        if not page.locator("#btn-survival").is_visible():
            check(False, "live menu not reachable")
            ctx.close()
            return
        page.locator("#btn-survival").click()
        page.wait_for_timeout(1000)
        if page.locator("#planet-select").is_visible():
            n = page.locator("#planet-grid .planet-card").count()
            check(n >= 8, f"live planet grid has the catalog (got {n})")
            shot(page, "stage3-live-planet-select.png")
            page.locator('.planet-card[data-planet="terra"]').click()
            page.locator("#btn-planet-go").click()
            page.wait_for_timeout(800)
            playing = page.evaluate("() => app && app.mode === 'playing' && app.planet && app.planet.id")
            check(playing == "terra", "live solo starts on the chosen planet")
            shot(page, "stage3-live-play-terra.png")
        else:
            # Not deployed yet: just note it; this check is re-run after deploy.
            print("live planet select not present yet (expected before this deploy)")
            shot(page, "stage3-live-planet-select.png")
        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-pw3-"))
    print("PHP", PHP, "URL", URL)
    proc = start_php(port, data)
    try:
        with sync_playwright() as p:
            browser = p.chromium.launch(executable_path=CHROME, args=CHROME_ARGS, headless=True)
            run_desktop(browser)
            run_mobile(browser)
            run_lobby(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-3 playwright checks passed")
    return 0


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