#!/usr/bin/env python3
"""Layout and flight-arc visuals for t1125 (wide / narrow / mobile)."""
from __future__ import annotations

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

from playwright.sync_api import sync_playwright

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


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


def check(cond, msg):
    if not cond:
        FAILURES.append(msg)
        print("FAIL", msg)
    else:
        print("OK  ", 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_http(port):
    proc = subprocess.Popen(
        ["python3", "-m", "http.server", str(port), "--bind", "127.0.0.1",
         "--directory", str(ROOT / "build")],
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL,
    )
    time.sleep(0.35)
    if proc.poll() is not None:
        raise RuntimeError("http.server failed to start")
    return proc


def open_offline(page, url, round_n=1):
    page.goto(url, wait_until="domcontentloaded", timeout=15000)
    page.wait_for_timeout(400)
    page.locator("#btn-play").click()
    page.wait_for_selector("#planet-select:not([hidden])", timeout=8000)
    page.locator("#btn-planet-go").click()
    page.wait_for_function(
        "() => app && app.mode === 'playing' && app.offline && app.battle && app.core",
        timeout=10000,
    )
    if round_n != 1:
        page.evaluate(
            """(round) => {
                teardownPlay();
                startPlay({ planet: app.planet, offline: true, round: round });
            }""",
            round_n,
        )
        page.wait_for_function(
            "() => app && app.mode === 'playing' && app.battle && app.miniLayout",
            timeout=8000,
        )
        page.wait_for_timeout(250)


LAYOUT_INFO = """() => {
    const plan = app.miniLayout || {};
    const fieldEl = app.scene && app.scene.canvas;
    const fr = fieldEl ? fieldEl.getBoundingClientRect() : null;
    const minis = [...document.querySelectorAll('#minis .mini')].map((el) => {
        const r = el.getBoundingClientRect();
        const c = el.querySelector('canvas');
        const cr = c ? c.getBoundingClientRect() : r;
        return {
            id: el.getAttribute('data-player'),
            left: r.left, right: r.right, top: r.top, bottom: r.bottom,
            cx: cr.left + cr.width / 2,
            cy: cr.top + cr.height / 2
        };
    });
    return {
        mode: plan.mode,
        sidesClass: document.getElementById('minis').classList.contains('sides'),
        n: plan.n,
        field: fr ? { left: fr.left, right: fr.right, top: fr.top, bottom: fr.bottom,
                       x: app.fieldX, y: app.fieldY, w: app.fieldW, h: app.fieldH } : null,
        positions: plan.positions || [],
        minis,
        tile: app.tile,
        vw: window.innerWidth,
        vh: window.innerHeight
    };
}"""



INJECT_FLIGHTS = """(age) => {
    if (age == null) age = 0.55;
    const plan = app.miniLayout;
    const field = app.scene.canvas.getBoundingClientRect();
    function miniCell(id, col, y) {
        if (Online.miniCellViewport) {
            const p = Online.miniCellViewport(id, col, y);
            if (p && isFinite(p.x)) return p;
        }
        const el = document.querySelector('#minis .mini[data-player="' + id + '"] canvas');
        if (!el) return { x: 80, y: 80 };
        return Online.cellViewport(col, y, el.getBoundingClientRect());
    }
    const bots = (app.battle.bots || []).map(b => b.id);
    const a = bots[0] || 'bot-1';
    const b = bots[1] || bots[0] || 'bot-2';
    const landCol = 3;
    // Launch from the real top-row cell, not from above the canvas (t1134).
    const pStart = Online.cellViewport(4, 13, field);
    const pEnd = Online.fieldEntry ? Online.fieldEntry(landCol) : Online.cellViewport(landCol, 13, field);
    if (typeof Online.clearFlights === 'function') Online.clearFlights();
    const flights = [
        { id: 'vis-p2e', client_id: 'vis-p2e', from_id: 'player', target_id: a, miss: false, color: 0, flight_duration: 1.2, age: age, land_col: landCol, col: 4, y: 13 },
        { id: 'vis-e2p', client_id: 'vis-e2p', from_id: a, target_id: 'player', miss: false, color: 1, flight_duration: 1.2, age: age, land_col: landCol, col: 2, y: 13 },
        { id: 'vis-e2e', client_id: 'vis-e2e', from_id: a, target_id: b, miss: false, color: 2, flight_duration: 1.2, age: age, land_col: 7, col: 5, y: 13 },
        { id: 'vis-emiss', client_id: 'vis-emiss', from_id: b, target_id: null, miss: true, color: 3, flight_duration: 1.2, age: Math.min(age, 0.45), col: 1, y: 13 }
    ];
    const aOut = miniCell(a, 2, 13);
    const bOut = miniCell(b, 1, 13);
    const locals = {
        'vis-p2e': { from_id: 'player', color: 0, startX: pStart.x, startY: pStart.y, col: 4, y: 13, land_col: landCol },
        'vis-e2p': { from_id: a, color: 1, startX: aOut.x, startY: aOut.y, col: 2, y: 13, land_col: landCol },
        'vis-e2e': { from_id: a, color: 2, startX: aOut.x, startY: aOut.y, col: 5, y: 13, land_col: 7 },
        'vis-emiss': { from_id: b, color: 3, startX: bOut.x, startY: bOut.y, col: 1, y: 13 }
    };
    Online.spawnFlights(flights, locals);
    Online.tickFlights();
    const front = [...document.querySelectorAll('#flights .flight')].map(el => ({
        src: el.getAttribute('src') || el.src,
        transform: el.style.transform,
        parent: 'front'
    }));
    const back = [...document.querySelectorAll('#flights-back .flight')].map(el => ({
        src: el.getAttribute('src') || el.src,
        transform: el.style.transform,
        parent: 'back'
    }));
    const kinds = (Online._flights || []).map(f => {
        const raw = Math.min(0.999, Math.max(0, (performance.now() - f.t0) / f.duration));
        const u = f.miss ? Online.easeInOutCubic(raw) : Online.smoothParam(raw, 0.85, 0.85);
        const pt = Online.flightPointAt(f, u);
        const samples = [];
        if (f.kind === 'enemy-to-player' || f.kind === 'player-to-enemy')
        {
            for (let i = 0; i <= 16; i++)
            {
                const su = i / 16;
                const sp = Online.flightPointAt(f, su);
                const inside = !!(f.field && Online.pointInFieldInterior(sp.x, sp.y, f.field));
                const allowed = !f.field || Online.pointAllowedOnArc(sp, f.field, f.start, f.end);
                samples.push({ u: su, x: sp.x, y: sp.y, inside: inside, allowed: allowed });
            }
        }
        const d0 = f.curve ? Online.curveDeriv(f.curve, 0) : null;
        const d1 = f.curve ? Online.curveDeriv(f.curve, 1) : null;
        return {
            kind: f.kind, miss: f.miss,
            startScale: f.startScale, endScale: f.endScale,
            parent: (f.el && f.el.parentElement && f.el.parentElement.id) || '',
            src: (f.el && (f.el.getAttribute('src') || f.el.src)) || '',
            color: f.color,
            landCol: f.landCol,
            start: f.start,
            end: f.end,
            pos: pt,
            samples: samples,
            insideNow: f.field ? Online.pointInFieldInterior(pt.x, pt.y, f.field) : false,
            hasCurve: !!f.curve,
            segments: (f.curve && f.curve.segments) ? f.curve.segments.length : (f.curve ? 1 : 0),
            d0: d0, d1: d1
        };
    });
    const expectedEndX = field.left + ((landCol + 0.5) / 10) * field.width;
    const expectedEndY = field.top + (1 - (13.5) / 13) * field.height;
    const expectedStartY = field.top + (1 - (13.5) / 13) * field.height;
    return {
        front: front.length,
        back: back.length,
        kinds,
        expectedEndX,
        expectedEndY,
        expectedStartY,
        field: { left: field.left, right: field.right, top: field.top, bottom: field.bottom,
                 width: field.width, height: field.height },
        pad: field.top,
        hudH: app.hudH,
        mode: plan.mode,
        tile: app.tile
    };
}"""



EDGE = 16


def assert_sides(info, tag, expect_rows=False, expect_one_row=False, n=None):
    check(info["mode"] == "sides", f"{tag}: mode is sides (got {info['mode']})")
    check(info["sidesClass"], f"{tag}: #minis has .sides")
    field = info["field"]
    minis = info["minis"]
    positions = info.get("positions") or []
    vw = info.get("vw") or 0
    check(len(minis) >= 1, f"{tag}: at least one mini ({len(minis)})")
    if n is not None:
        check(len(minis) == n, f"{tag}: expected {n} minis, got {len(minis)}")
    if field:
        check(field["top"] >= 56 + 70 or field.get("y", 0) >= 56 + 70
              or (info.get("vh") or 900) < 600 and field["top"] >= 56 + 80,
              f"{tag}: wide layout has top padding (field.top={field['top']:.1f}, y={field.get('y')})")
    if not field or not minis:
        return

    # Bottom-aligned with the field (row 0).
    row0 = []
    for i, m in enumerate(minis):
        pos = positions[i] if i < len(positions) else {}
        if pos.get("row", 0) == 0:
            row0.append(m)
            check(abs(m["bottom"] - field["bottom"]) <= 10,
                  f"{tag}: mini {i} ({m['id']}) is bottom-aligned "
                  f"(bottom={m['bottom']:.1f} field.bottom={field['bottom']:.1f})")
        check(m["top"] >= 40,
              f"{tag}: mini {i} stays under the HUD (top={m['top']:.1f})")
        # Every mini sits entirely to the left or right of the field.
        left_of = m["right"] <= field["left"] + 2
        right_of = m["left"] >= field["right"] - 2
        check(left_of or right_of,
              f"{tag}: mini {i} is beside the field, not above it")

    # Alternating sides, outer-edge anchored, filling inward (t1133).
    if len(minis) >= 1:
        check(minis[0]["left"] <= EDGE + 6,
              f"{tag}: bot 1 is at the left outer edge (left={minis[0]['left']:.1f})")
    if len(minis) >= 2:
        check(minis[1]["right"] >= vw - EDGE - 6,
              f"{tag}: bot 2 is at the right outer edge (right={minis[1]['right']:.1f} vw={vw})")
    if len(minis) >= 3:
        check(minis[2]["left"] > minis[0]["left"] + 20,
              f"{tag}: bot 3 is inward of bot 1, toward the field "
              f"({minis[0]['left']:.1f} → {minis[2]['left']:.1f})")
        # Same row when they fit (3 bots on a wide-enough side).
        if positions and positions[0].get("row") == 0 and positions[2].get("row") == 0:
            check(abs(minis[2]["bottom"] - minis[0]["bottom"]) <= 6,
                  f"{tag}: bot 3 shares the bottom row with bot 1")
    if len(minis) >= 4:
        check(minis[3]["right"] < minis[1]["right"] - 20,
              f"{tag}: bot 4 is inward of bot 2, toward the field")

    if expect_one_row:
        rows = [p.get("row", 0) for p in positions] if positions else []
        check(rows and all(r == 0 for r in rows),
              f"{tag}: all minis sit in a single row (rows={rows})")
    if expect_rows:
        rows = [p.get("row", 0) for p in positions] if positions else []
        check(any(r >= 1 for r in rows),
              f"{tag}: wraps to a second row (rows={rows})")
        # Wrapped minis start again at the outer edges and sit above row 0.
        lefts = [(i, minis[i], positions[i]) for i in range(len(minis))
                 if i < len(positions) and positions[i].get("side") == "left"]
        r0 = [t for t in lefts if t[2].get("row") == 0 and t[2].get("fromOuter") == 0]
        r1 = [t for t in lefts if t[2].get("row") == 1 and t[2].get("fromOuter") == 0]
        if r0 and r1:
            check(abs(r1[0][1]["left"] - r0[0][1]["left"]) <= 4,
                  f"{tag}: wrapped left mini is again at the outer edge")
            check(r1[0][1]["bottom"] <= r0[0][1]["top"] + 8,
                  f"{tag}: wrapped row sits above the first")


def assert_top(info, tag):
    check(info["mode"] == "top", f"{tag}: mode is top (got {info['mode']})")
    check(not info["sidesClass"], f"{tag}: #minis is not .sides")
    field = info["field"]
    minis = info["minis"]
    check(len(minis) >= 1, f"{tag}: at least one mini")
    if not field or not minis:
        return
    for i, m in enumerate(minis):
        check(m["bottom"] <= field["top"] + 12,
              f"{tag}: mini {i} sits above the field "
              f"(bottom={m['bottom']:.1f} field.top={field['top']:.1f})")


def assert_flights(info, tag, expect_behind=True, expect_around=True):
    check(info["front"] >= 3, f"{tag}: front flights present ({info['front']})")
    kinds = {k["kind"]: k for k in info["kinds"]}
    check("player-to-enemy" in kinds, f"{tag}: player-to-enemy")
    check("enemy-to-player" in kinds, f"{tag}: enemy-to-player")
    check("enemy-miss" in kinds, f"{tag}: enemy-miss")
    if "player-to-enemy" in kinds:
        k = kinds["player-to-enemy"]
        check(k["startScale"] > k["endScale"],
              f"{tag}: player-to-enemy shrinks ({k['startScale']:.2f}→{k['endScale']:.2f})")
        check("gray" in (k.get("src") or "").lower() or k.get("color") == -1,
              f"{tag}: player-to-enemy is grey (src={k.get('src')} color={k.get('color')})")
        if k.get("start") and info.get("expectedStartY") is not None:
            check(k["start"]["y"] <= info["field"]["top"] + 2,
                  f"{tag}: player-to-enemy starts at the exit (at/above the canvas top) "
                  f"(start.y={k['start']['y']:.1f} field.top={info['field']['top']:.1f})")
            check(abs(k["start"]["y"] - info["expectedStartY"]) < 8,
                  f"{tag}: player-to-enemy starts at the y=13 exit pose "
                  f"(start.y={k['start']['y']:.1f} expected={info['expectedStartY']:.1f})")
        if k.get("d0"):
            check(k["d0"]["y"] < 0,
                  f"{tag}: player-to-enemy leaves going up (d0.y={k['d0']['y']:.1f})")
        check(k.get("hasCurve"), f"{tag}: player-to-enemy uses a smooth curve")
        if expect_around:
            forbidden = [s for s in (k.get("samples") or []) if s.get("inside") and not s.get("allowed")]
            check(len(forbidden) == 0,
                  f"{tag}: player-to-enemy stays in launch/land corridors "
                  f"({len(forbidden)} forbidden {forbidden[:3]})")
    if "enemy-to-player" in kinds:
        k = kinds["enemy-to-player"]
        check(k["endScale"] > k["startScale"],
              f"{tag}: enemy-to-player grows ({k['startScale']:.2f}→{k['endScale']:.2f})")
        check(k.get("landCol") == 3,
              f"{tag}: enemy-to-player landCol is 3 (got {k.get('landCol')})")
        if k.get("end") and info.get("expectedEndX"):
            check(abs(k["end"]["x"] - info["expectedEndX"]) < 3,
                  f"{tag}: arc ends at column 3 "
                  f"(end.x={k['end']['x']:.1f} expected={info['expectedEndX']:.1f})")
        if k.get("end") and info.get("expectedEndY") is not None:
            check(abs(k["end"]["y"] - info["expectedEndY"]) < 8,
                  f"{tag}: arc ends at the spawn pose (y=13) "
                  f"(end.y={k['end']['y']:.1f} expected={info['expectedEndY']:.1f})")
            check(k["end"]["y"] < info["field"]["top"] + 2,
                  f"{tag}: incoming end is at/above the canvas top "
                  f"(end.y={k['end']['y']:.1f} field.top={info['field']['top']:.1f})")
        if k.get("d1"):
            check(k["d1"]["y"] > 0,
                  f"{tag}: enemy-to-player arrives going down (d1.y={k['d1']['y']:.1f})")
        check(abs(k.get("endScale", 0) - 1) < 0.05,
              f"{tag}: incoming ends at full tile scale ({k.get('endScale')})")
        check(k.get("hasCurve"), f"{tag}: enemy-to-player uses a smooth curve")
        check("gray" in (k.get("src") or "").lower() or k.get("color") == -1,
              f"{tag}: enemy-to-player is grey (src={k.get('src')} color={k.get('color')})")
        if expect_around and k.get("samples"):
            forbidden = [s for s in k["samples"] if s.get("inside") and not s.get("allowed")]
            check(len(forbidden) == 0,
                  f"{tag}: enemy-to-player stays in launch/land corridors "
                  f"({len(forbidden)} forbidden {forbidden[:3]})")
    if "enemy-to-enemy" in kinds:
        k = kinds["enemy-to-enemy"]
        check(abs(k["startScale"] - k["endScale"]) < 0.05,
              f"{tag}: enemy-to-enemy stays small ({k['startScale']:.2f})")
        check(k["parent"] == "flights-back",
              f"{tag}: enemy-to-enemy is in #flights-back (got {k['parent']})")
        if expect_behind:
            check(info["back"] >= 1, f"{tag}: at least one behind-field flight")
        check("gray" in (k.get("src") or "").lower() or k.get("color") == -1,
              f"{tag}: enemy-to-enemy is grey (src={k.get('src')} color={k.get('color')})")
    if "enemy-miss" in kinds:
        k = kinds["enemy-miss"]
        check(k["startScale"] < 0.7,
              f"{tag}: enemy-miss starts small ({k['startScale']:.2f})")
        check(k["parent"] == "flights",
              f"{tag}: enemy-miss is in #flights (got {k['parent']})")
        check(k.get("color") != -1,
              f"{tag}: enemy-miss keeps the sender colour (color={k.get('color')})")


def run_viewport(browser, url, name, width, height, is_mobile, round_n, expect_mode,
                 expect_one_row=False, expect_rows=False, n_minis=None):
    context = browser.new_context(
        viewport={"width": width, "height": height},
        device_scale_factor=1,
        is_mobile=is_mobile,
        has_touch=is_mobile,
    )
    page = context.new_page()
    open_offline(page, url, round_n=round_n)
    page.wait_for_timeout(300)
    info = page.evaluate(LAYOUT_INFO)
    field = info.get("field") or {}
    print(f"--- {name} layout:", {k: info[k] for k in ('mode', 'n', 'tile', 'vw', 'vh', 'sidesClass')},
          "fieldY", field.get("y"), "field.top", field.get("top"),
          "positions", info.get("positions"))
    if expect_mode == "sides":
        assert_sides(info, name, expect_rows=expect_rows, expect_one_row=expect_one_row,
                     n=n_minis)
    else:
        assert_top(info, name)
    shot(page, f"t1138-{name}-layout.png")

    flights = page.evaluate(INJECT_FLIGHTS, 0.55)
    print(f"--- {name} flights:", {k: flights[k] for k in ('front', 'back', 'expectedEndX', 'expectedEndY', 'expectedStartY', 'hudH', 'mode') if k in flights})
    for knd in flights["kinds"]:
        print(f"    {knd['kind']}: color={knd.get('color')} landCol={knd.get('landCol')} "
              f"src={knd.get('src')} curve={knd.get('hasCurve')}/{knd.get('segments')} "
              f"start={knd.get('start')} end={knd.get('end')} pos={knd.get('pos')}")
    assert_flights(flights, name)
    shot(page, f"t1138-{name}-midarc.png")

    if name in ("1024x532-3bots", "1920x1080-8bots", "desktop-wide"):
        for age, label in ((0.18, "early"), (0.85, "late")):
            page.evaluate(INJECT_FLIGHTS, age)
            shot(page, f"t1138-{name}-midarc-{label}.png")
    context.close()


def record_arcs_video(browser, url, width, height, round_n):
    """A short webm of two volleys flying out, over, and into the field (t1138)."""
    VIDEO.mkdir(parents=True, exist_ok=True)
    raw_dir = VIDEO / f"_raw_{width}x{height}"
    if raw_dir.exists():
        for old in raw_dir.glob("*"):
            old.unlink()
    raw_dir.mkdir(parents=True, exist_ok=True)
    dest = VIDEO / f"t1138-arcs-{width}x{height}.webm"
    context = browser.new_context(
        viewport={"width": width, "height": height},
        device_scale_factor=1,
        record_video_dir=str(raw_dir),
        record_video_size={"width": width, "height": height},
    )
    page = context.new_page()
    open_offline(page, url, round_n=round_n)
    page.wait_for_timeout(400)
    # Live volleys at age 0 so tickFlights animates them in the game loop.
    page.evaluate(INJECT_FLIGHTS, 0)
    page.wait_for_timeout(1300)
    page.evaluate(INJECT_FLIGHTS, 0)
    page.wait_for_timeout(1400)
    page.close()
    context.close()
    raw = list(raw_dir.glob("*.webm"))
    if raw:
        raw[0].replace(dest)
        print(f"wrote {dest} ({dest.stat().st_size} bytes)")
    else:
        FAILURES.append(f"video {width}x{height}: no webm produced")
        print(f"FAIL video {width}x{height}: no webm produced")
        return
    if dest.stat().st_size < 10000:
        FAILURES.append(f"video {width}x{height}: suspiciously small ({dest.stat().st_size} bytes)")


def main():

    port = free_port()
    http = start_http(port)
    url = f"http://127.0.0.1:{port}/"
    try:
        with sync_playwright() as p:
            browser = p.chromium.launch(
                executable_path=CHROME,
                args=CHROME_ARGS,
                headless=True,
            )
            # Tim's short wide window, 3 bots (ronde 3)
            run_viewport(browser, url, "1024x532-3bots", 1024, 532, False, 3, "sides",
                         expect_one_row=True, n_minis=3)
            # 8 bots: wrap on 1280, one row on 1400 and 1920
            run_viewport(browser, url, "1280x900-8bots", 1280, 900, False, 25, "sides",
                         expect_rows=True, n_minis=8)
            run_viewport(browser, url, "1400x900-8bots", 1400, 900, False, 25, "sides",
                         expect_one_row=True, n_minis=8)
            run_viewport(browser, url, "1920x1080-8bots", 1920, 1080, False, 25, "sides",
                         expect_one_row=True, n_minis=8)
            record_arcs_video(browser, url, 1920, 1080, 25)
            record_arcs_video(browser, url, 1024, 532, 3)
            browser.close()
    finally:
        http.terminate()
        try:
            http.wait(timeout=3)
        except subprocess.TimeoutExpired:
            http.kill()

    if FAILURES:
        print(f"\n{len(FAILURES)} failure(s):")
        for f in FAILURES:
            print(" -", f)
        return 1
    print("\nall minis/flights checks passed")
    return 0


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