#!/usr/bin/env python3
"""t1181: sender/receiver flight latency and smoothness with two real browser clients.

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"
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/t1181-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)


def analyse(tracks, t_ref):
    """First appearance (ms after t_ref), max per-frame jump (px) and path length per flight."""
    out = []
    for k, pts in tracks.items():
        if len(pts) < 2:
            continue
        first = pts[0][0] - t_ref
        jumps = []
        for a, b in zip(pts, pts[1:]):
            dt = max(1, b[0] - a[0])
            d = ((b[1] - a[1]) ** 2 + (b[2] - a[2]) ** 2) ** 0.5
            jumps.append(d / (dt / 16.7))  # px per 60 Hz frame
        out.append({"id": k, "first_ms": first, "frames": len(pts), "start": [round(pts[0][1]), round(pts[0][2])],
                    "max_jump_px": round(max(jumps), 1), "median_jump_px": round(sorted(jumps)[len(jumps) // 2], 1),
                    "max_kink_px": round(max([abs(y - x) for x, y in zip(jumps, jumps[1:])] or [0]), 1),
                    "dur_ms": pts[-1][0] - pts[0][0]})
    return sorted(out, key=lambda r: r["first_ms"])


def main():
    global URL
    port = free_port(); URL = f"http://127.0.0.1:{port}/"
    proc = start_php(port, Path(tempfile.mkdtemp(prefix="meteors-t1181-")))
    metrics = {}
    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.wait_for_timeout(1500)
            for pg in (p1, p2):
                pg.evaluate(PROBE)
            # Several rounds so the poll phase varies.
            rounds = []
            for rnd in range(4):
                for pg in (p1, p2):
                    pg.evaluate("() => { window.__probe.tracks = {}; window.__probe.culls = {}; }")
                p1.wait_for_timeout(137 * rnd)
                t_shot = p1.evaluate("() => Date.now()")
                p1.evaluate(SHOOT, 3)
                if rnd == 0:
                    p1.wait_for_timeout(120); p1.screenshot(path=str(SHOTS / f"t1181-{TAG}-desktop-sender-120ms.png"))
                    p1.wait_for_timeout(330); p1.screenshot(path=str(SHOTS / f"t1181-{TAG}-desktop-sender-450ms.png"))
                    p2.wait_for_timeout(500); p2.screenshot(path=str(SHOTS / f"t1181-{TAG}-mobile-receiver.png"))
                p1.wait_for_timeout(3200)
                s = p1.evaluate("() => window.__probe")
                r = p2.evaluate("() => window.__probe")
                cull = min(s["culls"].values()) if s["culls"] else t_shot
                rounds.append({"sender": analyse(s["tracks"], cull), "receiver": analyse(r["tracks"], cull)})
            metrics["rounds"] = rounds
            # t1182: falling blocks on the receiver's mini of the sender.
            p2.evaluate("""() => {
              const R = window.__mini = { rows: [] };
              const orig = Online._drawMini;
              Online._drawMini = function (canvas, snapshot, planet, shownY) {
                if (snapshot && snapshot.blocks) {
                  for (const b of snapshot.blocks) if (b.color === 3 && b.col === 7) {
                    const y = (shownY && shownY[b.id] != null) ? shownY[b.id] : b.y;
                    R.rows.push([performance.now(), b.id, y, b.state]);
                  }
                }
                return orig.apply(this, arguments);
              };
            }""")
            p1.evaluate("""() => {
              const b = app.core.createBlock(7, 12.6, 3, 'falling');
              b.vy = -app.planet.fallSpeed;
            }""")
            p2.wait_for_timeout(1400)
            p2.screenshot(path=str(SHOTS / f"t1181-{TAG}-mobile-mini-falling.png"))
            p2.wait_for_timeout(2600)
            rows = p2.evaluate("() => window.__mini.rows")
            fall_speed = p1.evaluate("() => app.planet.fallSpeed")
            steps = []
            falling = [r for r in rows if r[3] == 'falling']
            for a_, b_ in zip(falling, falling[1:]):
                if a_[1] == b_[1]:
                    steps.append(round(a_[2] - b_[2], 4))
            # Only judge motion until the block reaches its resting spot
            # (prediction stops on top of the stack, it never locks).
            last = max([i for i, s in enumerate(steps) if abs(s) > 1e-6] or [0])
            steps = steps[:last + 1]
            moving = [s for s in steps if abs(s) > 1e-6]
            metrics["mini"] = {
                "frames_falling": len(falling),
                "frames_moving": len(moving),
                "share_moving": round(len(moving) / max(1, len(steps)), 3),
                "max_step_cells": max([abs(s) for s in steps] or [0]),
                "fall_speed": fall_speed,
                # A jump: > 0.5 cell in one frame AND far faster than the
                # real fall (long frames from renderer stalls are not jumps).
                "jumps_over_half_cell": sum(1 for a_, b_ in zip(falling, falling[1:])
                                            if a_[1] == b_[1] and abs(a_[2] - b_[2]) > 0.5
                                            and abs(a_[2] - b_[2]) / max(1e-3, (b_[0] - a_[0]) / 1000) > 2.5 * fall_speed),
                "upward_steps": sum(1 for s in steps if s < -1e-6),
                "landed_seen": any(r[3] != 'falling' for r in rows),
                "big_steps": [[round(a_[0]-falling[0][0]), round(b_[0]-a_[0]), round(a_[2],3), round(b_[2],3)] for a_, b_ in zip(falling, falling[1:]) if a_[1]==b_[1] and abs(a_[2]-b_[2])>0.3],
                "series": [[round(r[0]-falling[0][0]), round(r[2],3)] for r in falling][::6] if falling else [],
            }
            metrics["errors"] = errs
            b.close()
    finally:
        proc.terminate()
    # Summaries
    # Own outgoing shots leave the top of the sender's main field; flights
    # that start low on the screen are incoming garbage from the opponent.
    sf = [f for r in metrics["rounds"] for f in r["sender"] if f["start"][1] < 400]
    rf = [f for r in metrics["rounds"] for f in r["receiver"]]
    summ = {
        "tag": TAG,
        "sender_flights": len(sf),
        "sender_first_ms": [f["first_ms"] for f in sf],
        "sender_max_jump_px": max([f["max_jump_px"] for f in sf] or [0]),
        "receiver_flights": len(rf),
        "receiver_first_ms": [f["first_ms"] for f in rf],
        "receiver_max_jump_px": max([f["max_jump_px"] for f in rf] or [0]),
        "receiver_starts": [f["start"] for f in rf][:6],
        "sender_max_kink_px": max([f["max_kink_px"] for f in sf] or [0]),
        "receiver_max_kink_px": max([f["max_kink_px"] for f in rf] or [0]),
        "sender_first_ms_median": sorted(f["first_ms"] for f in sf if f["first_ms"] >= 0)[len(sf) // 2] if sf else None,
        "receiver_first_ms_median": sorted(f["first_ms"] for f in rf if f["first_ms"] >= 0)[len(rf) // 2] if rf else None,
        "errors": metrics["errors"],
        "mini": metrics.get("mini"),
    }
    print(json.dumps(summ, indent=1))
    Path(f"/workspace/meteors-shots/t1181-{TAG}-metrics.json").write_text(json.dumps({"summary": summ, **metrics}, indent=1))
    return summ


if __name__ == "__main__":
    s = main()
    if TAG == "after":
        check(s["sender_flights"] >= 12, f"sender drew a flight for every shot ({s['sender_flights']})")
        check(max(s["sender_first_ms"] or [9999]) <= 120, f"sender flight starts within ~1-2 frames of the cull (max {max(s['sender_first_ms'] or [0])} ms)")
        check(s["receiver_flights"] >= 12, f"receiver drew the opponent's flights ({s['receiver_flights']})")
        check(not s["errors"], f"no page errors {s['errors'][:2]}")
        m = s["mini"] or {}
        check(m.get("share_moving", 0) > 0.8, f"mini: falling block moves on most frames ({m.get('share_moving')})")
        check(m.get("jumps_over_half_cell", 99) == 0, f"mini: no jumps > 0.5 cell ({m.get('jumps_over_half_cell')})")
        check(m.get("upward_steps", 99) == 0, f"mini: never moves up ({m.get('upward_steps')})")
        sys.exit(1 if FAILURES else 0)
