#!/usr/bin/env python3
"""t1173/t1174: reward screen after solo, Offline Strijd rounds and online matches.

Local PHP server with ?test= logins. Screenshots in /workspace/meteors-shots/t1173-local-*.
"""
from __future__ import annotations

import os
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")
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"]
FAILURES = []
URL = None

STATE_JS = """() => {
    const el = document.getElementById('reward');
    const t = document.getElementById('reward-title');
    const r = t ? t.getBoundingClientRect() : null;
    const c = document.getElementById('reward-total');
    const cr = c ? c.getBoundingClientRect() : null;
    return {
        visible: !!el && !el.hidden,
        title: t && t.textContent,
        titleTop: r && r.top, titleH: r && r.height,
        counter: c && c.textContent,
        counterVisible: !!c && !c.parentNode.hidden,
        counterY: cr && (cr.top + cr.height / 2),
        vh: window.innerHeight,
        dbg: (typeof Reward !== 'undefined' && Reward.debugState) ? Reward.debugState() : null,
        mode: window.app && app.mode,
        menuPoints: (document.getElementById('menu-points') || {}).textContent,
        lifetime: (typeof Online !== 'undefined') ? Online.lifetimePoints : null,
    };
}"""


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


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


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, log_path):
    env = os.environ.copy()
    env["METEORS_DATA_DIR"] = str(data)
    log = open(log_path, "w")
    proc = 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=log, stderr=log,
    )
    time.sleep(0.5)
    if proc.poll() is not None:
        raise RuntimeError("php failed: " + Path(log_path).read_text(errors="replace"))
    return proc


def login(page, n, next_path="index.html"):
    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_function("() => typeof Online !== 'undefined' && Online.me", timeout=15000)
    page.wait_for_timeout(400)


def state(page):
    return page.evaluate(STATE_JS)


def pick_and_play(page, button="#btn-survival"):
    page.locator(button).click()
    page.wait_for_selector("#planet-select:not([hidden])", timeout=8000)
    page.wait_for_timeout(200)
    page.locator("#btn-planet-go").click()
    page.wait_for_function("() => window.app && app.mode === 'playing' && app.core", timeout=10000)
    page.wait_for_timeout(300)


def force_gameover(page, score):
    page.evaluate(
        """(s) => { app.core.score = s; app.core.state = 'gameover'; app.core.gameOverTime = 0; }""", score
    )


def watch_reward(page, prefix, expect_title, expect_earned):
    """Follow one reward run; returns the final debug state."""
    page.wait_for_function("() => !document.getElementById('reward').hidden", timeout=5000)
    page.wait_for_timeout(350)
    st = state(page)
    print("intro", {k: st[k] for k in ("title", "titleTop", "vh", "counterVisible")})
    check(st["title"] == expect_title, f"{prefix}: title {st['title']!r} == {expect_title!r}")
    mid = st["titleTop"] + st["titleH"] / 2
    check(abs(mid - st["vh"] / 2) < st["vh"] * 0.12, f"{prefix}: title centred first (mid {mid:.0f} / vh {st['vh']})")
    check(st["dbg"] and st["dbg"]["phase"] == "intro", f"{prefix}: phase intro at 0.35 s ({st['dbg'] and st['dbg']['phase']})")
    shot(page, f"t1173-local-{prefix}-1-centered.png")
    # After 1 s + 0.6 s tween: title at the top.
    page.wait_for_timeout(1500)
    st = state(page)
    check(st["titleTop"] < st["vh"] * 0.15, f"{prefix}: title rose to the top ({st['titleTop']:.0f})")
    if expect_earned > 0:
        page.wait_for_function(
            "() => Reward.debugState() && Reward.debugState().phase === 'count' && Reward.debugState().flying >= 1",
            timeout=6000,
        )
        page.wait_for_timeout(250)
        st = state(page)
        d = st["dbg"]
        print("counting", d, st["counter"])
        check(d["earned"] == expect_earned, f"{prefix}: earned {d['earned']} == {expect_earned}")
        check(st["counterVisible"], f"{prefix}: counter visible at the bottom")
        check(st["counterY"] > st["vh"] * 0.7, f"{prefix}: counter near bottom ({st['counterY']:.0f}/{st['vh']})")
        check(d["before"] <= int(st["counter"]) <= d["after"], f"{prefix}: counter {st['counter']} within [{d['before']}, {d['after']}]")
        check(d["flying"] >= 1, f"{prefix}: blocks are flying ({d['flying']})")
        shot(page, f"t1173-local-{prefix}-2-counting.png")
    page.wait_for_function("() => Reward.debugState() && Reward.debugState().phase === 'hold'", timeout=30000)
    st = state(page)
    d = st["dbg"]
    check(int(st["counter"]) == d["after"], f"{prefix}: final counter {st['counter']} == after {d['after']}")
    check(d["after"] - d["before"] == expect_earned, f"{prefix}: after-before == {expect_earned}")
    check(d["after"] == st["lifetime"], f"{prefix}: final == server lifetime ({st['lifetime']})")
    shot(page, f"t1173-local-{prefix}-3-final.png")
    page.wait_for_function("() => document.getElementById('reward').hidden", timeout=6000)
    page.wait_for_timeout(300)
    return d


def test_logged_out_solo(browser):
    print("\n== logged-out solo stays as before ==")
    ctx = browser.new_context(viewport={"width": 1280, "height": 800})
    page = ctx.new_page()
    page.goto(f"{URL}index.html", wait_until="networkidle")
    pick_and_play(page)
    page.wait_for_timeout(500)
    force_gameover(page, 7)
    page.wait_for_timeout(500)
    st = state(page)
    go = page.evaluate("() => !document.getElementById('game-over').hidden")
    check(not st["visible"], "logged out: no reward screen")
    check(go, "logged out: classic game-over overlay")
    shot(page, "t1173-local-loggedout-gameover.png")
    page.wait_for_function("() => !document.getElementById('menu').hidden", timeout=8000)
    check(True, "logged out: back to menu")
    ctx.close()


def test_solo(browser):
    print("\n== logged-in solo ==")
    ctx = browser.new_context(viewport={"width": 1280, "height": 800})
    page = ctx.new_page()
    errs = []
    page.on("pageerror", lambda e: errs.append(str(e)))
    login(page, 1)
    before = int(page.locator("#menu-points").inner_text().strip() or 0)
    pick_and_play(page)
    page.wait_for_function("() => app.playToken", timeout=8000)
    page.wait_for_timeout(3600)  # server needs >= 3 s and 4 pts/s → 12 allowed
    force_gameover(page, 12)
    d = watch_reward(page, "solo", "You lost...", 12)
    check(d["before"] == before, f"solo: counter started at the old profile total {before}")
    page.wait_for_function("() => !document.getElementById('menu').hidden", timeout=6000)
    page.wait_for_timeout(500)
    pts = int(page.locator("#menu-points").inner_text().strip())
    check(pts == before + 12, f"solo: menu shows new total {pts} == {before + 12}")
    check(not errs, f"solo: no page errors {errs[:3]}")
    shot(page, "t1173-local-solo-4-menu.png")

    print("\n== logged-in solo, 0 points ==")
    pick_and_play(page)
    page.wait_for_timeout(600)
    force_gameover(page, 0)
    page.wait_for_function("() => !document.getElementById('reward').hidden", timeout=5000)
    page.wait_for_function("() => Reward.debugState() && Reward.debugState().phase === 'hold'", timeout=6000)
    st = state(page)
    check(st["counterVisible"] and int(st["counter"]) == pts, f"zero: shows total {st['counter']} briefly")
    check(st["dbg"]["spawned"] == 0, "zero: no blocks")
    shot(page, "t1173-local-solo-zero.png")
    page.wait_for_function("() => !document.getElementById('menu').hidden", timeout=6000)
    ctx.close()


def test_offline(browser):
    print("\n== logged-in Offline Strijd: win a round, then lose ==")
    ctx = browser.new_context(viewport={"width": 1280, "height": 800})
    page = ctx.new_page()
    login(page, 1)
    pick_and_play(page, "#btn-play")
    page.wait_for_function("() => app.playToken && app.battle", timeout=8000)
    page.wait_for_timeout(3600)
    page.evaluate("() => { app.core.score = 8; for (const b of app.battle.bots) b.core.state = 'gameover'; }")
    watch_reward(page, "offline-won", "You won!", 8)
    page.wait_for_function("() => app.battle && app.battle.round === 2 && app.mode === 'playing'", timeout=6000)
    check(True, "offline: continued to round 2 after the reward")
    shot(page, "t1173-local-offline-round2.png")
    page.wait_for_function("() => app.playToken", timeout=8000)
    page.wait_for_timeout(3600)
    force_gameover(page, 5)
    watch_reward(page, "offline-lost", "You lost...", 5)
    page.wait_for_function("() => !document.getElementById('offline-result').hidden", timeout=6000)
    check(True, "offline: lost → offline result screen (as before)")
    shot(page, "t1173-local-offline-result.png")
    ctx.close()


def test_online(browser):
    print("\n== online two players ==")
    c1 = browser.new_context(viewport={"width": 1280, "height": 800})
    c2 = browser.new_context(viewport={"width": 390, "height": 844}, is_mobile=True, has_touch=True, device_scale_factor=2)
    p1, p2 = c1.new_page(), c2.new_page()
    login(p1, 1, "index.html?online=1")
    login(p2, 2, "index.html?online=1")
    for p in (p1, p2):
        p.locator("#online-panel").wait_for(state="visible", timeout=8000)
        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)
    p1.locator("#btn-create").click()
    p1.wait_for_function("() => (document.getElementById('lobby-code')||{}).textContent.trim().length >= 4", timeout=8000)
    code = p1.locator("#lobby-code").inner_text().strip()
    p2.locator("#join-code").fill(code)
    p2.locator("#btn-join").click()
    p2.locator("#online-lobby").wait_for(state="visible", timeout=8000)
    p1.locator("#btn-ready").click()
    p2.locator("#btn-ready").click()
    start = p1.locator("#btn-start")
    for _ in range(20):
        if start.is_visible() and start.is_enabled():
            break
        p1.wait_for_timeout(400)
    start.click()
    for p in (p1, p2):
        p.wait_for_function("() => app && app.mode === 'playing' && app.online && app.core", timeout=10000)
    b1 = p1.evaluate("() => app.onlineBefore")
    b2 = p2.evaluate("() => app.onlineBefore")
    p1.wait_for_timeout(1500)
    p1.evaluate("() => { app.core.score = 9; }")
    p2.evaluate("() => { app.core.score = 6; }")
    p1.wait_for_timeout(1200)  # let the scores reach the server
    p2.evaluate("() => { app.core.state = 'gameover'; app.core.gameOverTime = 0; }")
    p1.wait_for_function("() => !document.getElementById('reward').hidden", timeout=12000)
    p2.wait_for_function("() => !document.getElementById('reward').hidden", timeout=12000)
    p1.wait_for_timeout(300)
    s1, s2 = state(p1), state(p2)
    check(s1["title"] == "You won!", f"online winner sees You won! ({s1['title']!r})")
    check(s2["title"] == "You lost...", f"online loser sees You lost... ({s2['title']!r})")
    shot(p1, "t1173-local-online-winner-1-centered.png")
    shot(p2, "t1173-local-online-mobile-loser-1-centered.png")
    p1.wait_for_function("() => Reward.debugState() && Reward.debugState().phase === 'count'", timeout=8000)
    p1.wait_for_timeout(400)
    shot(p1, "t1173-local-online-winner-2-counting.png")
    p2.wait_for_function("() => Reward.debugState() && ['count','hold'].includes(Reward.debugState().phase)", timeout=8000)
    p2.wait_for_timeout(200)
    shot(p2, "t1173-local-online-mobile-loser-2-counting.png")
    for p, b, earned, tag in ((p1, b1, 9, "winner"), (p2, b2, 6, "loser")):
        p.wait_for_function("() => Reward.debugState() && Reward.debugState().phase === 'hold'", timeout=20000)
        d = state(p)["dbg"]
        check(d["before"] == b and d["after"] - d["before"] == earned,
              f"online {tag}: {d['before']} → {d['after']} (+{earned})")
    shot(p2, "t1173-local-online-mobile-loser-3-final.png")
    # Mobile: tap during the hold continues.
    p2.tap("#reward")
    p2.wait_for_function("() => document.getElementById('reward').hidden", timeout=3000)
    check(True, "mobile tap in the hold continues")
    for p, tag in ((p1, "winner"), (p2, "loser")):
        p.wait_for_function("() => app.mode === 'online' && !document.getElementById('online-lobby').hidden", timeout=15000)
        check(True, f"online {tag}: back in the lobby afterwards")
    shot(p1, "t1173-local-online-winner-4-lobby.png")
    c1.close()
    c2.close()


def main():
    global URL
    port = free_port()
    URL = f"http://127.0.0.1:{port}/"
    data = Path(tempfile.mkdtemp(prefix="meteors-t1173-"))
    proc = start_php(port, data, "/tmp/t1173-php.log")
    try:
        with sync_playwright() as p:
            browser = p.chromium.launch(executable_path=CHROME, args=CHROME_ARGS, headless=True)
            only = sys.argv[1:] or ["out", "solo", "offline", "online"]
            if "out" in only:
                test_logged_out_solo(browser)
            if "solo" in only:
                test_solo(browser)
            if "offline" in only:
                test_offline(browser)
            if "online" in only:
                test_online(browser)
            browser.close()
    finally:
        proc.terminate()
        try:
            proc.wait(timeout=3)
        except Exception:
            proc.kill()
    if FAILURES:
        print("FAILURES:")
        for f in FAILURES:
            print(" -", f)
        return 1
    print("ALL OK")
    return 0


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