#!/usr/bin/env python3
"""t1192: 5 blocks at once to an opponent with 2 open columns — none may be lost.

Usage: t1181-flights-playwright.py [ROOT] [TAG]
ROOT defaults to /workspace/meteors (its build/ is served by php -S).
Desktop (1280x800) is the sender; mobile (390x844, touch, DPR 3) is the receiver.
Writes /workspace/meteors-shots/t1181-<TAG>-*.png and prints JSON metrics.
"""
from __future__ import annotations

import json
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(sys.argv[1]) if len(sys.argv) > 1 else Path("/workspace/meteors")
TAG = sys.argv[2] if len(sys.argv) > 2 else "after"
ROUNDS = 3
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"
ARGS = ["--use-gl=angle", "--use-angle=swiftshader", "--no-sandbox", "--disable-dev-shm-usage"]
FAILURES = []
URL = None

# Records, per frame, every flight element's on-screen centre, plus the
# Date.now() when each of my shots left the field (cull).
PROBE = """() => {
  if (window.__probe) return;
  const P = window.__probe = { culls: {}, tracks: {}, frames: 0 };
  const orig = GameCore.prototype.consumeOutgoingShots;
  GameCore.prototype.consumeOutgoingShots = function () {
    const shots = orig.call(this);
    if (this === app.core) for (const s of shots) P.culls[String(s.id)] = Date.now();
    return shots;
  };
  let ids = new WeakMap(); let next = 1;
  function f() {
    P.frames++;
    const now = Date.now();
    for (const el of document.querySelectorAll('#flights .flight, #flights-back .flight')) {
      if (!ids.has(el)) ids.set(el, 'el' + (next++));
      const k = ids.get(el);
      const r = el.getBoundingClientRect();
      if (!r.width) continue;
      (P.tracks[k] = P.tracks[k] || []).push([now, r.left + r.width / 2, r.top + r.height / 2]);
    }
    requestAnimationFrame(f);
  }
  requestAnimationFrame(f);
}"""

SHOOT = """(n) => {
  const out = [];
  for (let i = 0; i < n; i++) {
    const b = app.core.createBlock(2 + 2 * i, 13.0, i % 5, 'flying');
    b.vy = 6;
    out.push(b.id);
  }
  return out;
}"""


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


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)
    log = open(f"/tmp/t1192-php-{TAG}.log", "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)
    return proc


def login(page, n):
    page.goto(f"{URL}auth.php?test={n}&next=index.html", wait_until="domcontentloaded")
    page.wait_for_timeout(300)
    page.goto(f"{URL}index.html?online=1", wait_until="domcontentloaded")
    page.wait_for_function("() => typeof Online !== 'undefined' && Online.me", timeout=15000)
    page.locator("#online-panel").wait_for(state="visible", timeout=8000)



SETUP_RECEIVER = """() => {
  const g = app.core;
  g.spawnInterval = 1e9; g.playTime = 99;
  for (const b of g.blocks.slice()) g.removeBlock(b);
  for (let c = 0; c < 10; c++) { if (c === 3 || c === 7) continue; for (let r = 0; r < 13; r++) g.place(c, r, (r + c) % 5, 'locked'); }
  const R = window.__recv = { incoming: 0, ownShots: 0 };
  const origIn = Online.onIncoming;
  Online.onIncoming = function (list) { R.incoming += list.length; return origIn.apply(this, arguments); };
  const origC = GameCore.prototype.consumeOutgoingShots;
  GameCore.prototype.consumeOutgoingShots = function () { const s = origC.call(this); if (this === app.core) R.ownShots += s.length; return s; };
}"""

COUNT = """() => {
  const g = app.core;
  const gray = g.blocks.filter(b => (b.col === 3 || b.col === 7)).length;
  return { inOpen: gray, pending: g.pendingGarbage ? g.pendingGarbage() : null, incoming: window.__recv.incoming,
           ownShots: window.__recv.ownShots, state: g.state, score: g.score };
}"""

SHOOT5 = """() => { for (let i = 0; i < 5; i++) { const b = app.core.createBlock(i * 2, 13.0, i % 5, 'flying'); b.vy = 6; } }"""


def main():
    global URL
    port = free_port(); URL = f"http://127.0.0.1:{port}/"
    proc = start_php(port, Path(tempfile.mkdtemp(prefix="meteors-t1192-")))
    m = {"rounds": []}
    try:
        with sync_playwright() as p:
            b = p.chromium.launch(executable_path=CHROME, args=ARGS, headless=True)
            c1 = b.new_context(viewport={"width": 1280, "height": 800})
            c2 = b.new_context(viewport={"width": 390, "height": 844}, is_mobile=True, has_touch=True, device_scale_factor=3)
            p1, p2 = c1.new_page(), c2.new_page()
            errs = []
            for pg, tag in ((p1, "desktop"), (p2, "mobile")):
                pg.on("pageerror", lambda e, tag=tag: errs.append(f"{tag}: {e}"))
            login(p1, 1); login(p2, 2)
            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 pg in (p1, p2):
                pg.wait_for_function("() => app && app.mode === 'playing' && app.online && app.core", timeout=10000)
            p1.evaluate("() => { app.core.spawnInterval = 1e9; app.core.playTime = 99; for (const b of app.core.blocks.slice()) app.core.removeBlock(b); }")
            p2.evaluate(SETUP_RECEIVER)
            p1.wait_for_timeout(500)
            for rnd in range(ROUNDS):
                before = p2.evaluate(COUNT)
                p1.evaluate(SHOOT5)
                if rnd == 0:
                    p2.wait_for_timeout(1500)
                    p2.screenshot(path=str(SHOTS / f"t1192-{TAG}-mobile-receiving.png"))
                    p1.screenshot(path=str(SHOTS / f"t1192-{TAG}-desktop-sender.png"))
                    p2.wait_for_timeout(5000)
                else:
                    p2.wait_for_timeout(6500)
                after = p2.evaluate(COUNT)
                got = after["incoming"] - before["incoming"]
                landed = after["inOpen"] - before["inOpen"]
                m["rounds"].append({"incoming": got, "landed": landed, "pending": after["pending"], "own_shots": after["ownShots"]})
                print("round", rnd, m["rounds"][-1])
            p2.screenshot(path=str(SHOTS / f"t1192-{TAG}-mobile-after.png"))
            m["final"] = p2.evaluate(COUNT)
            m["errors"] = errs
            b.close()
    finally:
        proc.terminate()
    (SHOTS / f"t1192-{TAG}-metrics.json").write_text(json.dumps(m, indent=1))
    tot_in = sum(r["incoming"] for r in m["rounds"]); tot_land = sum(r["landed"] for r in m["rounds"])
    print(json.dumps({"incoming": tot_in, "landed": tot_land, "final": m["final"]}))
    if TAG != "before":
        check(tot_in >= 8, f"receiver got {tot_in} incoming blocks over {ROUNDS} volleys of 5")
        check(tot_land == tot_in, f"all received blocks landed ({tot_land}/{tot_in})")
        check(m["final"]["ownShots"] == 0, "none culled off the top as the receiver's own shot")
        check(m["final"]["pending"] == 0, "queue empty at the end")
        check(not m["errors"], f"no page errors {m['errors'][:2]}")
    sys.exit(1 if FAILURES else 0)


if __name__ == "__main__":
    main()
