"""t1203: opponent minis scale to fit above the field on narrow portrait screens.
Usage: python3 test/t1203-mini-scale-playwright.py ROOT [tag]"""
import sys, json
from playwright.sync_api import sync_playwright
URL = sys.argv[1].rstrip("/") + "/"
TAG = sys.argv[2] if len(sys.argv) > 2 else "live"
fails = []
def check(ok, msg):
    print(("OK   " if ok else "FAIL ") + msg)
    if not ok: fails.append(msg)

ROUND_FOR = {6: 12, 8: 23, 12: 57, 16: 107, 31: 437}

MEASURE = """() => {
  const minis = [...document.querySelectorAll('#minis .mini')];
  const fieldTop = app.fieldY, vw = innerWidth;
  const out = minis.map(el => { const r = el.getBoundingClientRect(); const c = el.querySelector('canvas').getBoundingClientRect();
    return { id: el.dataset.player, slot: +el.dataset.slot, elim: el.classList.contains('eliminated'),
      x: r.left, y: r.top, w: r.width, bottom: r.bottom, right: r.right, cw: c.width, ch: c.height, font: parseFloat(getComputedStyle(el).fontSize) }; });
  return { fieldTop, vw, hud: app.hudH, mini: app.miniLayout.mini, minis: out };
}"""

def start(page, n, elim_idx):
    page.evaluate(f"""() => {{
        teardownPlay && teardownPlay();
        hideEl('menu');
        app.offline = true;
        startPlay({{ planet: Planet.defaultPlanet(), offline: true, round: {ROUND_FOR[n]} }});
    }}""")
    page.wait_for_function(f"() => app.mode === 'playing' && app.battle && app.battle.bots.length === {n}")
    page.evaluate("() => { app.core.noSpawn = true; for (const b of app.battle.bots) { b.core.noSpawn = true; } }")
    if elim_idx:
        page.evaluate(f"() => {{ for (const i of {json.dumps(elim_idx)}) app.battle.bots[i].core.state = 'gameover'; }}")
    page.wait_for_timeout(600)
    return page.evaluate(MEASURE)

with sync_playwright() as p:
    br = p.chromium.launch()
    for vw, vh in ((412, 915), (360, 800), (460, 900)):
        ctx = br.new_context(viewport={"width": vw, "height": vh}, is_mobile=True, has_touch=True, device_scale_factor=2)
        page = ctx.new_page(); errs = []
        page.on("pageerror", lambda e: errs.append(str(e)))
        page.goto(URL + "index.html", wait_until="networkidle")
        for n, elim in ((6, []), (6, [1, 4]), (8, [0, 2, 5]), (12, [3]), (16, [0, 1, 2, 3])):
            m = start(page, n, elim)
            tag = f"{vw}x{vh}-{n}bots" + (f"-{len(elim)}out" if elim else "")
            ms = m["minis"]
            above = all(q["bottom"] <= m["fieldTop"] + 0.5 for q in ms)
            inside = all(q["x"] >= -0.5 and q["right"] <= m["vw"] + 0.5 and q["y"] >= m["hud"] - 0.5 for q in ms)
            check(len(ms) == n and above and inside, f"{tag}: all {len(ms)} minis above the field (field top {m['fieldTop']}, lowest {max(q['bottom'] for q in ms):.0f}) and on screen; canvas {m['mini']['w']}x{m['mini']['h']}, font {ms[0]['font']}px")
            check(m["mini"]["fits"] and [q["slot"] for q in ms] == list(range(n)), f"{tag}: order unchanged while they fit")
            check(all(abs(q["cw"] - m["mini"]["w"]) < 1 for q in ms) and ms[0]["font"] >= 9, f"{tag}: canvas and label scaled ({ms[0]['cw']:.0f}px, {ms[0]['font']}px)")
            if vw != 460 or n in (6,):
                page.screenshot(path=f"/workspace/meteors-shots/t1203-{TAG}-{tag}.png")
        # overflow: 31 bots, 11 defeated
        elim = [i for i in range(31) if i % 3 == 0]
        m = start(page, 31, elim)
        ms = m["minis"]
        hidden = [q for q in ms if q["bottom"] > m["fieldTop"] + 0.5]
        alive_ok = all(q["bottom"] <= m["fieldTop"] + 0.5 for q in ms if not q["elim"])
        check(not m["mini"]["fits"] and m["mini"]["w"] == 32, f"{vw}x{vh}-31bots: minimum size used (canvas {m['mini']['w']}x{m['mini']['h']}), capacity {m['mini']['capacity']}")
        check(alive_ok and hidden and all(q["elim"] for q in hidden), f"{vw}x{vh}-31bots: living all visible, only defeated behind the field ({len(hidden)} hidden, all defeated)")
        alive_slots = [q["slot"] for q in ms if not q["elim"]]
        check(alive_slots == sorted(alive_slots), f"{vw}x{vh}-31bots: stable order of the living")
        page.screenshot(path=f"/workspace/meteors-shots/t1203-{TAG}-{vw}x{vh}-31bots-11out.png")
        # Online uses the same layout: fake an 8-opponent lobby (2 out) and render its minis.
        page.evaluate("() => { teardownPlay && teardownPlay(); }")
        m = page.evaluate("""() => {
            const players = [{ id: 'me', name: 'Ik', is_me: true }];
            for (let i = 1; i <= 8; i++) players.push({ id: 'p' + i, name: 'Speler ' + i, score: i, eliminated: i === 2 || i === 5, snapshot: { blocks: [] }, planet: Planet.defaultPlanet() });
            Online.lobby = { players };
            app.online = true; app.offline = false; app.battle = null;
            hideEl('menu'); document.getElementById('minis').hidden = false;
            app._layoutN = -1; layout();
            Online.renderMinis(document.getElementById('minis'));
            return true; }""")
        page.wait_for_timeout(200)
        m = page.evaluate(MEASURE)
        ms = m["minis"]
        check(len(ms) == 8 and all(q["bottom"] <= m["fieldTop"] + 0.5 and q["x"] >= -0.5 and q["right"] <= m["vw"] + 0.5 for q in ms) and abs(ms[0]["cw"] - m["mini"]["w"]) < 1, f"{vw}x{vh}-online-8: online minis use the same scaled top layout (canvas {m['mini']['w']}px, lowest {max(q['bottom'] for q in ms):.0f} <= field {m['fieldTop']})")
        page.screenshot(path=f"/workspace/meteors-shots/t1203-{TAG}-{vw}x{vh}-online-8.png")
        page.evaluate("() => { app.online = false; Online.lobby = null; }")
        check(not errs, f"{vw}x{vh}: no page errors {errs[:2]}")
        ctx.close()
    br.close()
print("ALL OK" if not fails else f"{len(fails)} FAILED")
sys.exit(1 if fails else 0)
