#!/usr/bin/env python3
"""Drag tests (t1104/t1106/t1107/t1109/t1110): 1:1 tracking, poisoned-pointer
regression, cell-corner grabs, under-flyer / landed-cluster drags, flame size."""
from __future__ import annotations

import socket
import subprocess
import sys
import time
from pathlib import Path

from playwright.sync_api import sync_playwright

OUT = Path("/workspace/meteors-shots")
OUT.mkdir(parents=True, exist_ok=True)
ROOT = Path("/workspace/meteors")
CHROME = "/usr/bin/google-chrome"
CHROME_ARGS = [
    "--use-gl=angle",
    "--use-angle=swiftshader",
    "--no-sandbox",
    "--disable-dev-shm-usage",
    "--disable-gpu-sandbox",
]

DESKTOP = {
    "name": "desktop-mouse",
    "viewport": {"width": 1280, "height": 900},
    "device_scale_factor": 1,
    "is_mobile": False,
    "has_touch": False,
    "user_agent": None,
    "input": "mouse",
}
ANDROID = {
    "name": "android-touch",
    "viewport": {"width": 393, "height": 851},
    "device_scale_factor": 2,
    "is_mobile": True,
    "has_touch": True,
    "user_agent": (
        "Mozilla/5.0 (Linux; Android 14; Pixel 7) AppleWebKit/537.36 "
        "(KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36"
    ),
    "input": "touch",
}
ANDROID_DPR3 = {
    "name": "android-dpr3",
    "viewport": {"width": 393, "height": 851},
    "device_scale_factor": 3,
    "is_mobile": True,
    "has_touch": True,
    "user_agent": (
        "Mozilla/5.0 (Linux; Android 14; Pixel 7) AppleWebKit/537.36 "
        "(KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36"
    ),
    "input": "touch",
}
IOS = {
    "name": "ios-touch",
    "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"
    ),
    "input": "touch",
}

FAILURES = []
URL = None


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


def field_to_client(page, col, field_y):
    return page.evaluate(
        """([col, fieldY]) => {
            const c = app.scene.canvas;
            const r = c.getBoundingClientRect();
            const w = Planet.FIELD_WIDTH;
            const h = Planet.FIELD_HEIGHT;
            return {
                x: r.left + ((col + 0.5) / w) * r.width,
                y: r.top + (1 - fieldY / h) * r.height
            };
        }""",
        [col, field_y],
    )


def touch_start(cdp, x, y):
    cdp.send(
        "Input.dispatchTouchEvent",
        {"type": "touchStart", "touchPoints": [{"x": x, "y": y, "id": 1}]},
    )


def touch_move(cdp, x, y):
    cdp.send(
        "Input.dispatchTouchEvent",
        {"type": "touchMove", "touchPoints": [{"x": x, "y": y, "id": 1}]},
    )


def touch_end(cdp):
    cdp.send("Input.dispatchTouchEvent", {"type": "touchEnd", "touchPoints": []})


def pointer_down(page, cdp, kind, x, y):
    if kind == "mouse":
        page.mouse.move(x, y)
        page.mouse.down()
    else:
        touch_start(cdp, x, y)


def pointer_move(page, cdp, kind, x, y):
    if kind == "mouse":
        page.mouse.move(x, y)
    else:
        touch_move(cdp, x, y)


def pointer_up(page, cdp, kind):
    if kind == "mouse":
        page.mouse.up()
    else:
        touch_end(cdp)


def drag_to(page, cdp, kind, x1, y1, x2, y2, steps=12, end=True):
    pointer_down(page, cdp, kind, x1, y1)
    for i in range(1, steps + 1):
        t = i / steps
        pointer_move(page, cdp, kind, x1 + (x2 - x1) * t, y1 + (y2 - y1) * t)
    if end:
        pointer_up(page, cdp, kind)


def reset_board(page, stacks):
    page.evaluate(
        """(stacks) => {
            const g = app.core;
            g.spawnInterval = 1e9;
            g.spawnTimer = 0;
            g.blocks.length = 0;
            g.clusters = Object.create(null);
            g.score = 0;
            g.drag = null;
            g.state = 'playing';
            g.nextBlockId = 1;
            g.nextClusterId = 1;
            app.selectTween = null;
            for (const [col, colors] of Object.entries(stacks)) {
                colors.forEach((color, row) => g.place(+col, row, color));
            }
        }""",
        stacks,
    )
    page.wait_for_timeout(80)


def board(page):
    return page.evaluate(
        """() => app.core.blocks.map((b) => ({
            id: b.id, col: b.col, y: b.y, color: b.color, state: b.state
        }))"""
    )


def col_ys(page, col):
    return {b["color"]: b["y"] for b in board(page) if b["col"] == col}


def check(cond, msg, device):
    if not cond:
        FAILURES.append(f"[{device}] {msg}")
        print(f"FAIL [{device}] {msg}")
    else:
        print(f"OK   [{device}] {msg}")
    return cond


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


def start_play(page, kind):
    page.goto(URL, wait_until="networkidle", timeout=20000)
    page.wait_for_timeout(400)
    btn = page.locator("#btn-survival")
    btn.wait_for(state="visible", timeout=5000)
    if kind == "touch":
        box = btn.bounding_box()
        cdp = page.context.new_cdp_session(page)
        touch_start(cdp, box["x"] + box["width"] / 2, box["y"] + box["height"] / 2)
        touch_end(cdp)
        page.wait_for_timeout(400)
    else:
        cdp = None
        btn.click()
        page.wait_for_timeout(400)
    if page.evaluate("() => app && app.mode") == "planet-select":
        go = page.locator("#btn-planet-go")
        go.wait_for(state="visible", timeout=5000)
        go.click()
        page.wait_for_timeout(400)
    if page.evaluate("() => app.mode") != "playing":
        if page.locator("#btn-survival").is_visible():
            page.locator("#btn-survival").click()
            page.wait_for_timeout(400)
        if page.locator("#btn-planet-go").is_visible():
            page.locator("#btn-planet-go").click()
            page.wait_for_timeout(400)
    page.wait_for_function("() => app && app.mode === 'playing' && app.core && app.scene", timeout=8000)
    page.wait_for_selector("canvas", state="visible", timeout=5000)
    if cdp is None:
        cdp = page.context.new_cdp_session(page)
    return cdp


def nearly(a, b, eps=0.15):
    return abs(a - b) <= eps


def run_device(browser, device):
    name = device["name"]
    kind = device["input"]
    print(f"\n======== {name} ({kind}, dpr={device['device_scale_factor']}) ========")
    kw = dict(
        viewport=device["viewport"],
        device_scale_factor=device["device_scale_factor"],
        is_mobile=device["is_mobile"],
        has_touch=device["has_touch"],
    )
    if device["user_agent"]:
        kw["user_agent"] = device["user_agent"]
    context = browser.new_context(**kw)
    page = context.new_page()
    bag = []
    page.on("console", lambda m: bag.append(f"{m.type}: {m.text}"))
    page.on("pageerror", lambda e: bag.append(f"pageerror: {e}"))
    cdp = start_play(page, kind)
    check(page.evaluate("() => app.mode") == "playing", "play started", name)

    # --- 1 tile down ---
    reset_board(page, {"2": [0, 1, 2, 3, 4]})
    p0 = field_to_client(page, 2, 1.5)
    p1 = field_to_client(page, 2, 0.5)
    drag_to(page, cdp, kind, p0["x"], p0["y"], p1["x"], p1["y"], steps=10, end=True)
    page.wait_for_timeout(60)
    ys = col_ys(page, 2)
    check(nearly(ys.get(1, -99), 0), f"1 tile down: grabbed color 1 at y=0, ys={ys}", name)
    check(nearly(ys.get(0, -99), 1), f"1 tile down: swapped neighbour to y=1, ys={ys}", name)
    check(nearly(ys.get(2, -99), 2) and nearly(ys.get(3, -99), 3) and nearly(ys.get(4, -99), 4),
          f"1 tile down: rest of the stack unmoved, ys={ys}", name)

    # --- 1 tile up ---
    reset_board(page, {"3": [0, 1, 2, 3, 4]})
    p0 = field_to_client(page, 3, 0.5)
    p1 = field_to_client(page, 3, 1.5)
    drag_to(page, cdp, kind, p0["x"], p0["y"], p1["x"], p1["y"], steps=10, end=True)
    page.wait_for_timeout(60)
    ys = col_ys(page, 3)
    check(nearly(ys.get(0, -99), 1), f"1 tile up: grabbed color 0 at y=1, ys={ys}", name)
    check(nearly(ys.get(1, -99), 0), f"1 tile up: neighbour at y=0, ys={ys}", name)
    check(nearly(ys.get(2, -99), 2), f"1 tile up: rest unmoved, ys={ys}", name)

    # --- 2 tiles, then stop: pointer held still, nothing else moves ---
    reset_board(page, {"4": [0, 1, 2, 3, 4]})
    p0 = field_to_client(page, 4, 0.5)
    p1 = field_to_client(page, 4, 2.5)
    drag_to(page, cdp, kind, p0["x"], p0["y"], p1["x"], p1["y"], steps=14, end=False)
    page.wait_for_timeout(50)
    mid = col_ys(page, 4)
    check(nearly(mid.get(0, -99), 2), f"2 tiles: grabbed color 0 at y=2, ys={mid}", name)
    check(nearly(mid.get(1, -99), 0) and nearly(mid.get(2, -99), 1) and nearly(mid.get(3, -99), 3),
          f"2 tiles: walked both neighbours, ys={mid}", name)
    # Pointer stops: more moves at the same point, then a short wait.
    for _ in range(6):
        pointer_move(page, cdp, kind, p1["x"], p1["y"])
        page.wait_for_timeout(30)
    after = col_ys(page, 4)
    check(after == mid, f"pointer stopped: stack stays put, mid={mid} after={after}", name)
    pointer_up(page, cdp, kind)
    page.wait_for_timeout(80)
    end = col_ys(page, 4)
    check(end == mid, f"after release: still at the pointer row, mid={mid} end={end}", name)
    shot(page, f"t1104-drag-{name}.png")

    # --- t1109: press at cell corners grabs the occupant (mouse and touch)
    run_cell_corner_grabs(page, cdp, kind, name)

    # --- t1107: still stack under a flying cluster is draggable
    run_under_flyer_drag(page, cdp, kind, name)

    # --- t1107: drag within a landed cluster
    run_landed_cluster_drag(page, cdp, kind, name)

    # --- t1110: flame is 3x, with a visual screenshot (once per device)
    run_flame_size(page, name)

    if bag:
        print(f"console [{name}]: {bag[:8]}")
    context.close()


def field_point(page, fx, fy):
    """Map exact field coordinates (not cell-centres) to client pixels."""
    return page.evaluate(
        """([fx, fy]) => {
            const c = app.scene.canvas;
            const r = c.getBoundingClientRect();
            return {
                x: r.left + (fx / 10) * r.width,
                y: r.top + (1 - fy / 13) * r.height
            };
        }""",
        [fx, fy],
    )


def grab_id(page):
    return page.evaluate(
        """() => {
            const g = app.core;
            if (!g.drag) return null;
            const b = g.blockById(g.drag.blockId);
            return b ? { id: b.id, col: b.col, y: b.y, color: b.color } : null;
        }"""
    )


def run_cell_corner_grabs(page, cdp, kind, name):
    reset_board(page, {"2": [0, 1, 2]})
    page.wait_for_timeout(50)
    target = page.evaluate(
        """() => {
            const b = app.core.blocks.find((x) => x.col === 2 && Math.abs(x.y - 1) < 0.01);
            return b ? b.id : null;
        }"""
    )
    corners = [(2.05, 1.05, "bottom-left"), (2.05, 1.95, "top-left"),
               (2.95, 1.05, "bottom-right"), (2.95, 1.95, "top-right")]
    for fx, fy, label in corners:
        pt = field_point(page, fx, fy)
        pointer_down(page, cdp, kind, pt["x"], pt["y"])
        page.wait_for_timeout(30)
        grabbed = grab_id(page)
        check(
            grabbed is not None and grabbed["id"] == target,
            f"t1109 corner {label} ({kind}) grabs cell occupant, grabbed={grabbed} want id={target}",
            name,
        )
        pointer_up(page, cdp, kind)
        page.wait_for_timeout(40)
    shot(page, f"t1109-corners-{name}.png")


def run_under_flyer_drag(page, cdp, kind, name):
    reset_board(page, {"3": [0, 1, 2]})
    page.evaluate(
        """() => {
            const g = app.core;
            const cluster = { id: g.nextClusterId++, jumpHeight: 3, vy: 0, decel: 0, phase: 'up' };
            g.clusters[cluster.id] = cluster;
            const b = g.createBlock(3, 8, g.constructor.COLOR_GRAY, 'flying');
            b.clusterId = cluster.id;
            b.vy = 0;
            b.flame = true;
        }"""
    )
    page.wait_for_timeout(40)
    p0 = field_to_client(page, 3, 0.5)
    p1 = field_to_client(page, 3, 1.5)
    drag_to(page, cdp, kind, p0["x"], p0["y"], p1["x"], p1["y"], steps=10, end=True)
    page.wait_for_timeout(60)
    info = page.evaluate(
        """() => {
            const g = app.core;
            const still = g.blocks.filter((b) => b.state === 'still' && b.col === 3)
                .map((b) => ({ color: b.color, y: b.y }));
            const flyer = g.blocks.find((b) => b.state === 'flying' && b.col === 3);
            return { still, flyerY: flyer ? flyer.y : null, flyerState: flyer ? flyer.state : null };
        }"""
    )
    ys = {b["color"]: b["y"] for b in info["still"]}
    check(nearly(ys.get(0, -99), 1), f"t1107 under-flyer: color 0 moved to y=1, info={info}", name)
    check(nearly(ys.get(1, -99), 0), f"t1107 under-flyer: color 1 swapped to y=0, info={info}", name)
    check(info["flyerState"] == "flying" and info["flyerY"] is not None and info["flyerY"] > 6,
          f"t1107 under-flyer: flyer left alone, info={info}", name)


def run_landed_cluster_drag(page, cdp, kind, name):
    page.evaluate(
        """() => {
            const g = app.core;
            g.spawnInterval = 1e9;
            g.spawnTimer = 0;
            g.blocks.length = 0;
            g.clusters = Object.create(null);
            g.drag = null;
            g.state = 'playing';
            g.nextBlockId = 1;
            g.nextClusterId = 1;
            const cluster = { id: g.nextClusterId++, jumpHeight: 3, vy: 0, decel: 0, phase: 'landed' };
            g.clusters[cluster.id] = cluster;
            const specs = [[0, -1], [1, 1], [2, 2]];
            for (const [y, color] of specs) {
                const b = g.createBlock(6, y, color, 'settling');
                b.clusterId = cluster.id;
                b.vy = 0;
                b.settleTime = 0;
            }
        }"""
    )
    page.wait_for_timeout(50)
    p0 = field_to_client(page, 6, 0.5)
    p1 = field_to_client(page, 6, 2.2)
    drag_to(page, cdp, kind, p0["x"], p0["y"], p1["x"], p1["y"], steps=12, end=True)
    page.wait_for_timeout(60)
    info = page.evaluate(
        """() => app.core.blocks.map((b) => ({
            color: b.color, y: b.y, state: b.state, clusterId: b.clusterId
        }))"""
    )
    by_y = {round(b["y"]): b for b in info}
    check(
        by_y.get(2) is not None and by_y[2]["color"] == -1 and by_y[2]["clusterId"] is not None,
        f"t1107 landed: grey dragged within cluster to y=2, info={info}",
        name,
    )


def run_flame_size(page, name):
    page.evaluate(
        """() => {
            const g = app.core;
            g.spawnInterval = 1e9;
            g.spawnTimer = 0;
            g.blocks.length = 0;
            g.clusters = Object.create(null);
            g.drag = null;
            g.state = 'playing';
            g.nextBlockId = 1;
            g.nextClusterId = 1;
            g.place(1, 0, 2);
            g.place(2, 0, 2);
            g.place(3, 0, 2);
            g.resolveMatches();
        }"""
    )
    # Let the view sync and the rockets rise a little so the flames are visible.
    page.wait_for_timeout(200)
    info = page.evaluate(
        """() => {
            const t = app.tile;
            const flames = Object.keys(app.flames).map((id) => {
                const f = app.flames[id];
                return {
                    visible: !!(f.renderer && f.renderer.visible),
                    sx: f.transform.size.x,
                    sy: f.transform.size.y
                };
            }).filter((f) => f.visible);
            return {
                t,
                expected: t * 0.85 * 3,
                flames,
                flying: app.core.blocks.filter((b) => b.flame).length
            };
        }"""
    )
    ok = (
        info
        and info["flying"] >= 3
        and info["flames"]
        and all(abs(f["sx"] - info["expected"]) < 0.51 and abs(f["sy"] - info["expected"]) < 0.51
                for f in info["flames"])
    )
    check(ok, f"t1110 flame is 3x (w and h), info={info}", name)
    shot(page, f"t1110-flame-{name}.png")


def run_poisoned_pointer_regression(browser):
    """t1106: pointermoves poisoned to fieldY 9.5, touchmoves correct to 1.5.
    Before the fix the block teleported to y=9; after, it stops at y=1.
    This is the regression that failed on the old pointer-only path.
    """
    name = "poisoned-pointer"
    print(f"\n======== {name} ========")
    kw = dict(
        viewport={"width": 412, "height": 915},
        device_scale_factor=2.625,
        is_mobile=True,
        has_touch=True,
        user_agent=(
            "Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 "
            "(KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36"
        ),
    )
    context = browser.new_context(**kw)
    page = context.new_page()
    start_play(page, "touch")
    reset_board(page, {"2": [0, 1, 2, 3, 4, 0, 1, 2, 3, 4]})
    page.wait_for_timeout(50)
    result = page.evaluate(
        """() => {
            const c = app.scene.canvas;
            const r = c.getBoundingClientRect();
            const toClient = (fy) => ({
                x: r.left + (2.5 / 10) * r.width,
                y: r.top + (1 - fy / 13) * r.height
            });
            const p0 = toClient(0.5);
            const pGood = toClient(1.5);
            const pBad = toClient(9.5);
            const fireP = (type, x, y) => {
                const ev = new PointerEvent(type, {
                    bubbles: true, cancelable: true, composed: true,
                    pointerId: 42, pointerType: 'touch', isPrimary: true,
                    clientX: x, clientY: y, pageX: x, pageY: y,
                    buttons: type === 'pointerup' ? 0 : 1, width: 28, height: 28,
                    pressure: type === 'pointerup' ? 0 : 0.5
                });
                (type === 'pointerdown' ? c : window).dispatchEvent(ev);
            };
            const fireT = (type, x, y) => {
                const t = new Touch({
                    identifier: 1, target: c, clientX: x, clientY: y,
                    pageX: x, pageY: y, screenX: x, screenY: y,
                    radiusX: 14, radiusY: 14, force: 0.5
                });
                const ev = new TouchEvent(type, {
                    bubbles: true, cancelable: true, composed: true,
                    touches: type.includes('end') || type.includes('cancel') ? [] : [t],
                    targetTouches: type.includes('end') || type.includes('cancel') ? [] : [t],
                    changedTouches: [t]
                });
                c.dispatchEvent(ev);
                document.dispatchEvent(ev);
            };
            fireP('pointerdown', p0.x, p0.y);
            fireT('touchstart', p0.x, p0.y);
            const midYs = [];
            const steps = 8;
            for (let i = 1; i <= steps; i++) {
                const t = i / steps;
                fireP('pointermove', p0.x, p0.y + (pBad.y - p0.y) * t);
                fireT('touchmove', p0.x, p0.y + (pGood.y - p0.y) * t);
                const b = app.core.blockById(app.core.drag && app.core.drag.blockId);
                if (b) midYs.push(Math.round(b.y * 100) / 100);
            }
            fireT('touchend', pGood.x, pGood.y);
            fireP('pointerup', pGood.x, pGood.y);
            const colors = app.core.blocks
                .filter((b) => b.col === 2)
                .sort((a, b) => a.y - b.y)
                .map((b) => ({ color: b.color, y: Math.round(b.y * 100) / 100, state: b.state }));
            const moved = colors.find((b) => b.color === 0);
            return { moved, colors, midYs, drag: app.core.drag };
        }"""
    )
    moved = result.get("moved") or {}
    # Must end at y=1 (one tile up), never at the top (y=9).
    ok = moved.get("y") is not None and abs(moved["y"] - 1) <= 0.15
    check(
        ok,
        f"t1106 poisoned pointer + correct touch leaves color 0 at y=1, result={result}",
        name,
    )
    check(
        moved.get("y") is None or moved["y"] < 4,
        f"t1106 must not teleport to the top, y={moved.get('y')}",
        name,
    )
    context.close()


def main():
    global URL
    port = free_port()
    URL = f"http://127.0.0.1:{port}/"
    print("serving", URL, "from", ROOT / "build")
    httpd = subprocess.Popen(
        ["python3", "-m", "http.server", str(port), "--bind", "127.0.0.1", "--directory", str(ROOT / "build")],
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL,
    )
    try:
        time.sleep(0.4)
        with sync_playwright() as p:
            browser = p.chromium.launch(
                executable_path=CHROME,
                args=CHROME_ARGS,
                headless=True,
            )
            for device in (DESKTOP, ANDROID, ANDROID_DPR3, IOS):
                run_device(browser, device)
            run_poisoned_pointer_regression(browser)
            browser.close()
    finally:
        httpd.terminate()
        try:
            httpd.wait(timeout=3)
        except Exception:
            httpd.kill()

    print("\n======== summary ========")
    if FAILURES:
        print(f"{len(FAILURES)} failure(s):")
        for f in FAILURES:
            print(" -", f)
        return 1
    print("all drag tests passed")
    return 0


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