#!/usr/bin/env python3
"""t1193: in-game menu (pause / resume / back to main menu) and login return.

Usage: python3 test/t1193-menu-playwright.py URL TAG
Logged-out checks run anywhere (live too). With a local dev server
(?test= logins) the logged-in reward flow for solo and Offline Strijd and
the online-panel login link are checked as well.
"""
import json, sys
from pathlib import Path
from playwright.sync_api import sync_playwright

URL = sys.argv[1] if len(sys.argv) > 1 else "https://projects.timfalken.com/meteors/"
if not URL.endswith("/"): URL += "/"
TAG = sys.argv[2] if len(sys.argv) > 2 else "live"
LOCAL = "127.0.0.1" in URL or "localhost" in URL
SHOTS = Path("/workspace/meteors-shots")
fails = []

def check(c, m):
    print(("OK   " if c else "FAIL ") + m)
    if not c: fails.append(m)

def shot(page, name):
    page.screenshot(path=str(SHOTS / f"t1193-{TAG}-{name}.png"))

def start(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(600)

def rect(page, sel):
    return page.evaluate("(s) => { const r = document.querySelector(s).getBoundingClientRect(); return [r.left, r.top, r.right, r.bottom]; }", sel)

def overlap(a, b):
    return not (a[2] <= b[0] or b[2] <= a[0] or a[3] <= b[1] or b[3] <= a[1])

def press(page, sel, mobile):
    if mobile: page.locator(sel).tap()
    else: page.locator(sel).click()

def layout_and_pause(page, name, mobile, mode):
    btn = rect(page, "#btn-game-menu")
    check(page.evaluate("() => !document.getElementById('btn-game-menu').hidden"), f"{name}/{mode}: menu button visible")
    vw = page.evaluate("() => innerWidth")
    check(btn[2] <= vw and btn[2] > vw - 70 and btn[1] < 60, f"{name}/{mode}: button at the top right {btn}")
    for sel in ("#planet-name", "#planet-stats", "#score", "#offline-hud"):
        vis = page.evaluate("(s) => { const e = document.querySelector(s); return !!e && !e.closest('[hidden]') && e.getBoundingClientRect().width > 0; }", sel)
        if vis:
            check(not overlap(btn, rect(page, sel)), f"{name}/{mode}: button does not overlap {sel}")
    check(btn[2] - btn[0] >= 36 and btn[3] - btn[1] >= 36, f"{name}/{mode}: touch target ≥ 36 px")
    shot(page, f"{name}-{mode}-hud")
    press(page, "#btn-game-menu", mobile)
    page.wait_for_selector("#game-menu:not([hidden])", timeout=3000)
    t0 = page.evaluate("() => [app.core.playTime, app.core.blocks.map(b => b.y).join(',')]")
    page.wait_for_timeout(1200)
    t1 = page.evaluate("() => [app.core.playTime, app.core.blocks.map(b => b.y).join(','), app.paused]")
    check(t0[0] == t1[0] and t0[1] == t1[1] and t1[2], f"{name}/{mode}: game paused while the menu is open (playTime {t0[0]:.2f})")
    texts = page.evaluate("() => [...document.querySelectorAll('#game-menu button')].map(b => b.textContent.trim())")
    check(len(texts) == 2 and texts[1], f"{name}/{mode}: menu buttons {texts}")
    shot(page, f"{name}-{mode}-menu")
    press(page, "#btn-game-resume", mobile)
    page.wait_for_timeout(700)
    t2 = page.evaluate("() => [app.core.playTime, app.paused, document.getElementById('game-menu').hidden]")
    check(t2[0] > t1[0] and not t2[1] and t2[2], f"{name}/{mode}: resume continues ({t1[0]:.2f} → {t2[0]:.2f})")

def logged_out(br, name, vp, mobile):
    ctx = br.new_context(viewport=vp, is_mobile=mobile, has_touch=mobile, device_scale_factor=3 if mobile else 1)
    ctx.add_init_script("try { sessionStorage.setItem('meteors-login-prompt', '1'); } catch (e) {}")
    page = ctx.new_page(); errs = []
    page.on("pageerror", lambda e: errs.append(str(e)))
    page.goto(URL + "index.html?t1193=" + TAG, wait_until="networkidle")
    check(page.locator("#menu-login").get_attribute("href") == "auth.php", f"{name}: menu login → auth.php (returns to the main menu)")
    check(page.locator("#btn-login").get_attribute("href") == "auth.php?return=online", f"{name}: Online-screen login → auth.php?return=online")
    # Solo
    start(page)
    layout_and_pause(page, name, mobile, "solo")
    page.evaluate("() => { app.core.score = 7; }")
    press(page, "#btn-game-menu", mobile)
    page.wait_for_selector("#game-menu:not([hidden])")
    press(page, "#btn-game-quit", mobile)
    page.wait_for_function("() => !document.getElementById('menu').hidden && app.mode === 'menu'", timeout=5000)
    last = page.locator("#last-score strong").inner_text()
    check(last == "7", f"{name}/solo: logged out → straight to the main menu (last score {last})")
    check(page.evaluate("() => document.getElementById('reward').hidden"), f"{name}/solo: no reward screen when logged out")
    shot(page, f"{name}-solo-quit-menu")
    # Offline Strijd
    start(page, "#btn-play")
    layout_and_pause(page, name, mobile, "offline")
    press(page, "#btn-game-menu", mobile)
    page.wait_for_selector("#game-menu:not([hidden])")
    press(page, "#btn-game-quit", mobile)
    page.wait_for_function("() => !document.getElementById('menu').hidden && app.mode === 'menu'", timeout=5000)
    st = page.evaluate("() => ({ battle: app.battle, offline: app.offline, result: !document.getElementById('offline-result').hidden })")
    check(st["battle"] is None and not st["offline"] and not st["result"], f"{name}/offline: battle ended, back in the main menu (no next round) {st}")
    check(not errs, f"{name}: no page errors {errs[:2]}")
    # ?online=1 is one-shot
    page.goto(URL + "index.html?online=1", wait_until="networkidle")
    page.wait_for_timeout(400)
    check("online=1" not in page.url, f"{name}: ?online=1 removed from the address after use ({page.url})")
    ctx.close()

def logged_in(br, name, vp, mobile):
    ctx = br.new_context(viewport=vp, is_mobile=mobile, has_touch=mobile, device_scale_factor=3 if mobile else 1)
    page = ctx.new_page(); errs = []
    page.on("pageerror", lambda e: errs.append(str(e)))
    page.goto(URL + "auth.php?test=1&next=index.html", wait_until="domcontentloaded")
    page.goto(URL + "index.html", wait_until="networkidle")
    page.wait_for_function("() => typeof Online !== 'undefined' && Online.me", timeout=15000)
    check(page.evaluate("() => !document.getElementById('menu').hidden && app.mode !== 'online'"), f"{name}: after login → main menu, logged in")
    before = int(page.locator("#menu-points").inner_text().strip() or 0)
    for mode, button in (("solo", "#btn-survival"), ("offline", "#btn-play")):
        start(page, button)
        page.wait_for_function("() => app.playToken", timeout=8000)
        page.wait_for_timeout(3600)
        page.evaluate("() => { app.core.score = 9; }")
        press(page, "#btn-game-menu", mobile)
        page.wait_for_selector("#game-menu:not([hidden])")
        press(page, "#btn-game-quit", mobile)
        page.wait_for_function("() => !document.getElementById('reward').hidden", timeout=5000)
        page.wait_for_timeout(400)
        title = page.locator("#reward-title").inner_text().strip()
        check(title == "Game ended", f"{name}/{mode}: reward screen first, title {title!r}")
        page.wait_for_function("() => Reward.debugState() && Reward.debugState().phase === 'hold'", timeout=30000)
        d = page.evaluate("() => Reward.debugState()")
        shot(page, f"{name}-{mode}-loggedin-reward")
        check(d["after"] - d["before"] == 9, f"{name}/{mode}: 9 points added via play_finish ({d['before']} → {d['after']})")
        page.wait_for_function("() => !document.getElementById('menu').hidden && app.mode === 'menu'", timeout=8000)
        pts = int(page.locator("#menu-points").inner_text().strip())
        check(pts == before + 9, f"{name}/{mode}: main menu shows {pts} == {before + 9}")
        if mode == "offline":
            check(page.evaluate("() => app.battle === null"), f"{name}/offline: no next round after quitting")
        before = pts
    # Quitting right away (< 3 s): server cap gives 0, cannot farm points.
    start(page)
    page.wait_for_function("() => app.playToken", timeout=8000)
    page.evaluate("() => { app.core.score = 500; }")
    press(page, "#btn-game-menu", mobile)
    page.wait_for_selector("#game-menu:not([hidden])")
    press(page, "#btn-game-quit", mobile)
    page.wait_for_function("() => Reward.debugState() && Reward.debugState().phase === 'hold'", timeout=30000)
    d = page.evaluate("() => Reward.debugState()")
    check(d["after"] - d["before"] == 0, f"{name}: quick quit with a faked score of 500 → 0 points (server cap)")
    page.wait_for_function("() => !document.getElementById('menu').hidden", timeout=8000)
    shot(page, f"{name}-loggedin-menu")
    check(not errs, f"{name}: logged-in no page errors {errs[:2]}")
    ctx.close()

with sync_playwright() as pw:
    br = pw.chromium.launch(args=["--use-gl=angle", "--use-angle=swiftshader"])
    for name, vp, mobile in (("desktop", {"width": 1280, "height": 800}, False), ("mobile", {"width": 390, "height": 844}, True)):
        logged_out(br, name, vp, mobile)
        if LOCAL:
            logged_in(br, name, vp, mobile)
    br.close()
print("ALL OK" if not fails else f"{len(fails)} FAIL")
sys.exit(1 if fails else 0)
