#!/usr/bin/env python3
"""Touch input for Meteors: real touch sequences on Android- and iOS-like viewports."""
from __future__ import annotations

import json
import sys
import time
import subprocess
import socket
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",
]

ANDROID = {
    "name": "android-chrome",
    "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"
    ),
}
IOS = {
    "name": "ios-safari",
    "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"
    ),
}

FAILURES = []
LOG = []


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": 0, "force": 1.0}]},
    )


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


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


def touch_drag(cdp, x1, y1, x2, y2, steps=16):
    touch_start(cdp, x1, y1)
    for i in range(1, steps + 1):
        t = i / steps
        touch_move(cdp, x1 + (x2 - x1) * t, y1 + (y2 - y1) * t)
    touch_end(cdp)


def reset_board(page, stacks):
    """stacks: {col: [colors from bottom]}"""
    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.evaluate("() => { if (typeof syncSprites === 'function') { /* maybe closed */ } }")
    # Give the view one frame to draw.
    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 grab_state(page):
    return page.evaluate(
        """() => ({
            drag: app.core.drag && {
                blockId: app.core.drag.blockId,
                accum: app.core.drag.accum,
                startedAsTop: app.core.drag.startedAsTop
            },
            tween: app.selectTween && {
                phase: app.selectTween.phase,
                scale: app.selectTween.scale,
                t: app.selectTween.t,
                blockId: app.selectTween.blockId
            }
        })"""
    )


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)")
    return path


def start_play(page):
    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)
    # Real touch tap on the Play button (mobile browsers may swallow click).
    box = btn.bounding_box()
    cdp = page.context.new_cdp_session(page)
    touch_drag(
        cdp,
        box["x"] + box["width"] / 2,
        box["y"] + box["height"] / 2,
        box["x"] + box["width"] / 2,
        box["y"] + box["height"] / 2,
        steps=1,
    )
    page.wait_for_timeout(400)
    # Stage 3: Spelen opens the planet picker first.
    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)
    # Fallback if the touch didn't start the game (desktop-like click path).
    if page.evaluate("() => app.mode") != "playing":
        if page.locator("#btn-survival").is_visible():
            btn.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)
    return cdp


def run_device(browser, device):
    name = device["name"]
    print(f"\n======== {name} ========")
    context = browser.new_context(
        viewport=device["viewport"],
        device_scale_factor=device["device_scale_factor"],
        is_mobile=device["is_mobile"],
        has_touch=device["has_touch"],
        user_agent=device["user_agent"],
    )
    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)
    check(page.evaluate("() => app.mode") == "playing", "play started", name)
    shot(page, f"t1102-touch-{name}-play.png")

    # --- Instant grab + click tween starts on pointerdown, no hold delay ---
    reset_board(page, {"2": [0, 1, 2, 3, 4]})
    page.wait_for_timeout(120)
    pos = field_to_client(page, 2, 1.5)  # centre of the block at y=1
    touch_start(cdp, pos["x"], pos["y"])
    # No wait-for-hold: inspect immediately, then after one frame.
    page.wait_for_timeout(16)
    st = grab_state(page)
    check(st.get("drag") is not None, f"instant grab on pointerdown, state={st}", name)
    tw = st.get("tween") or {}
    check(
        tw.get("phase") in ("press", "hold") and tw.get("blockId") is not None,
        f"click tween starts immediately on pointerdown, tween={tw}",
        name,
    )
    # Drag without any extra hold delay: swipe up two tiles.
    dest = field_to_client(page, 2, 1.5 + 2)
    for i in range(1, 9):
        t = i / 8
        touch_move(cdp, pos["x"], pos["y"] + (dest["y"] - pos["y"]) * t)
    page.wait_for_timeout(40)
    mid = board(page)
    # The grabbed block (color 1 at y=1) should have moved up.
    grabbed = [b for b in mid if b["color"] == 1]
    check(
        grabbed and grabbed[0]["y"] >= 2.9,
        f"immediate drag (no hold) swaps upward, grabbed={grabbed}",
        name,
    )
    touch_end(cdp)
    page.wait_for_timeout(80)

    # --- Fast swipe: several tiles in a short sequence, no skip ---
    reset_board(page, {"3": [0, 1, 2, 3, 4]})
    page.wait_for_timeout(80)
    p0 = field_to_client(page, 3, 0.5)
    p1 = field_to_client(page, 3, 0.5 + 4)
    # Few steps: a fast swipe that jumps a long way between events.
    touch_drag(cdp, p0["x"], p0["y"], p1["x"], p1["y"], steps=3)
    page.wait_for_timeout(80)
    after = {b["color"]: b["y"] for b in board(page) if b["col"] == 3}
    check(
        after.get(0) == 4,
        f"fast swipe walks every tile (bottom ends at top), after={after}",
        name,
    )
    check(
        after.get(1) == 0 and after.get(2) == 1 and after.get(3) == 2 and after.get(4) == 3,
        f"fast swipe does not skip neighbours, after={after}",
        name,
    )
    shot(page, f"t1102-touch-{name}-after-swipe.png")

    # --- Horizontal slop: slightly diagonal swipe stays in column ---
    reset_board(page, {"4": [0, 1, 2, 3], "5": [3, 4, 0, 1]})
    page.wait_for_timeout(80)
    q0 = field_to_client(page, 4, 0.5)
    q1 = field_to_client(page, 4.4, 0.5 + 3)  # drift 0.4 tiles toward col 5
    # field_to_client uses (col+0.5)*tile, so 4.4 means 0.4 into the slop visually.
    q1 = field_to_client(page, 4.4, 3.5)
    colors_before_5 = [b["color"] for b in sorted(board(page), key=lambda b: b["y"]) if b["col"] == 5]
    touch_drag(cdp, q0["x"], q0["y"], q1["x"], q1["y"], steps=10)
    page.wait_for_timeout(80)
    col4 = {b["color"]: (b["y"], b["col"]) for b in board(page) if b["color"] == 0 and b["state"] == "still"}
    moved = [b for b in board(page) if b["color"] == 0 and b.get("id") is not None]
    # The bottom block of col 4 (color 0) should be at the top of col 4, not in col 5.
    bottoms = [b for b in board(page) if b["col"] == 4]
    top4 = max(bottoms, key=lambda b: b["y"]) if bottoms else None
    colors_after_5 = [b["color"] for b in sorted(board(page), key=lambda b: b["y"]) if b["col"] == 5]
    check(
        top4 and top4["color"] == 0 and top4["col"] == 4,
        f"diagonal drag stays in starting column, top4={top4}, col5={colors_after_5}",
        name,
    )
    check(
        colors_after_5 == colors_before_5,
        f"neighbour column untouched, before={colors_before_5} after={colors_after_5}",
        name,
    )
    shot(page, f"t1102-touch-{name}-diagonal.png")

    # --- Snap: press slightly above the top block still grabs it ---
    reset_board(page, {"1": [2, 3]})
    page.wait_for_timeout(80)
    # Top block occupies [1, 2); press at 2.25 (0.25 above).
    s = field_to_client(page, 1, 2.25)
    touch_start(cdp, s["x"], s["y"])
    page.wait_for_timeout(16)
    st = grab_state(page)
    check(st.get("drag") is not None, f"snap-grab slightly above the block, state={st}", name)
    touch_end(cdp)
    page.wait_for_timeout(50)

    if bag:
        print(f"console [{name}]: {bag[:8]}")
    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 (ANDROID, IOS):
                run_device(browser, device)
            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 touch tests passed")
    return 0


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