#!/usr/bin/env python3
"""Meaningless-fix display check driver (notebook Chrome, CDP 9224,
real GPU). Modelled on the proven cv_drive.py plumbing: fresh attach
to the existing game tab, fixed 1366x768 device metrics, container
FILL, click = mouseMoved + press(250ms) + release. Each invocation
runs ONE phase (argv[1]) against the persistent tab; game state
lives in the tab between invocations.
Phases: title, settings, settings_tabs, xl_patch_note, start_s1,
        demo_follow, forecast_idle, arm_test, shotonly NAME
"""
import base64, io, json, os, sys, time, urllib.request
import websocket
from PIL import Image

PORT = 9225
OUT = r"C:\Users\Public\kage_mf2_captures"
os.makedirs(OUT, exist_ok=True)
BASE = "https://rankshroud-preview.pages.dev/"

FILL = """(() => {
  const c = document.querySelector('#unity-canvas');
  const ct = document.querySelector('#unity-container');
  if(c && ct){ ct.style.width = '100%'; ct.style.height = '100%';
    c.style.width = '100%'; c.style.height = '100%';
    window.dispatchEvent(new Event('resize')); }
  return true; })()"""

def cell(r, c):
    return (0.083 + 0.153 * c, 0.828 - 0.212 * (3 - r))

def fp_of(png_bytes):
    im = Image.open(io.BytesIO(png_bytes)).convert("L").resize((48, 27))
    return list(im.getdata())

def fp_diff(a, b):
    return sum(abs(x - y) for x, y in zip(a, b)) / len(a)

class CDP:
    def __init__(self, ws_url):
        self.ws = websocket.create_connection(ws_url, timeout=90)
        self.mid = 0
        self.events = []
    def call(self, method, params=None, timeout=60):
        self.mid += 1
        mid = self.mid
        self.ws.send(json.dumps({"id": mid, "method": method, "params": params or {}}))
        self.ws.settimeout(timeout)
        while True:
            msg = json.loads(self.ws.recv())
            if msg.get("id") == mid:
                return msg.get("result", {})
            self.events.append(msg)

class Drv:
    def __init__(self, fresh=False):
        page = None
        if fresh:
            ver = json.loads(urllib.request.urlopen(
                f"http://127.0.0.1:{PORT}/json/version", timeout=10).read().decode())
            bws = websocket.create_connection(ver["webSocketDebuggerUrl"], timeout=30)
            bws.send(json.dumps({"id": 1, "method": "Target.createTarget",
                                 "params": {"url": "about:blank"}}))
            tid = None
            while True:
                msg = json.loads(bws.recv())
                if msg.get("id") == 1:
                    tid = msg.get("result", {}).get("targetId")
                    break
            bws.close()
            print("created target:", tid, flush=True)
            for _ in range(10):
                targets = json.loads(urllib.request.urlopen(
                    f"http://127.0.0.1:{PORT}/json/list", timeout=10).read().decode())
                for t in targets:
                    if t.get("id") == tid:
                        page = t
                        break
                if page:
                    break
                time.sleep(1)
        if page is None:
            targets = json.loads(urllib.request.urlopen(
                f"http://127.0.0.1:{PORT}/json/list", timeout=10).read().decode())
            for t in targets:
                if t.get("type") == "page" and "rankshroud" in t.get("url", ""):
                    page = t
                    break
            if page is None:
                for t in targets:
                    if t.get("type") == "page":
                        page = t
                        break
        print("attaching to:", page.get("url") if page else None, flush=True)
        self.cdp = CDP(page["webSocketDebuggerUrl"])
        self.cdp.call("Page.enable")
        self.cdp.call("Runtime.enable")
        self.cdp.call("Log.enable")
        self.cdp.call("Emulation.setDeviceMetricsOverride",
                      {"width": 1366, "height": 768, "deviceScaleFactor": 1,
                       "mobile": False})
        self.ev(FILL)
        self.exceptions = []
    def ev(self, expr, timeout=30):
        r = self.cdp.call("Runtime.evaluate",
                          {"expression": expr, "returnByValue": True}, timeout=timeout)
        res = r.get("result", {})
        if "exceptionDetails" in r:
            return {"EXC": str(r["exceptionDetails"])[:200]}
        return res.get("value")
    def shot_bytes(self):
        r = self.cdp.call("Page.captureScreenshot",
                          {"format": "png", "fromSurface": True}, timeout=60)
        return base64.b64decode(r["data"])
    def shot(self, name):
        raw = self.shot_bytes()
        path = os.path.join(OUT, name + ".png")
        with open(path, "wb") as fh:
            fh.write(raw)
        print("shot", name, len(raw), flush=True)
        return fp_of(raw)
    def fp(self):
        return fp_of(self.shot_bytes())
    def click_frac(self, fx, fy, press_ms=250):
        x, y = fx * 1366, fy * 768
        self.cdp.call("Input.dispatchMouseEvent",
                      {"type": "mouseMoved", "x": x, "y": y, "button": "none", "buttons": 0})
        self.cdp.call("Input.dispatchMouseEvent",
                      {"type": "mousePressed", "x": x, "y": y, "button": "left",
                       "buttons": 1, "clickCount": 1})
        time.sleep(press_ms / 1000.0)
        self.cdp.call("Input.dispatchMouseEvent",
                      {"type": "mouseReleased", "x": x, "y": y, "button": "left",
                       "buttons": 0, "clickCount": 1})
        print(f"click ({fx:.3f},{fy:.3f})", flush=True)
    def click_logical(self, lx, ly):
        self.click_frac(lx / 1920.0, ly / 1080.0)
    def wait_stable(self, timeout=40, tag=""):
        last = None
        stable = 0
        t0 = time.time()
        while time.time() - t0 < timeout:
            cur = self.fp()
            if last is not None and fp_diff(cur, last) < 0.6:
                stable += 1
                if stable >= 2:
                    print("stable", tag, flush=True)
                    return cur
            else:
                stable = 0
            last = cur
            time.sleep(1.2)
        print("stable TIMEOUT", tag, flush=True)
        return last
    def errors(self):
        out = []
        for m in self.cdp.events:
            if m.get("method") == "Log.entryAdded":
                e = m["params"]["entry"]
                if e.get("level") == "error":
                    out.append(e.get("text", "")[:200])
            if m.get("method") == "Runtime.exceptionThrown":
                out.append("EXC " + str(m["params"].get("exceptionDetails", {}))[:200])
        return out

def main():
    phase = sys.argv[1]
    if phase == "fresh_title":
        d = Drv(fresh=True)
        d.cdp.call("Page.navigate", {"url": BASE})
        print("nav fresh", flush=True)
        time.sleep(5)
        d.ev(FILL)
        d.wait_stable(timeout=60, tag="fresh-title")
        d.shot("m01_title")
        print("ERRORS:", len(d.errors()), flush=True)
        print("PHASE_DONE", phase, flush=True)
        return
    d = Drv()
    if phase == "tab_sound":
        d.click_frac(0.350, 0.167)
        time.sleep(1.5)
        d.wait_stable(timeout=20, tag="sound")
        d.shot("m03_settings_sound")
    elif phase == "tab_screen":
        d.click_frac(0.469, 0.167)
        time.sleep(1.5)
        d.wait_stable(timeout=20, tag="screen")
        d.shot("m04_settings_screen")
    elif phase == "tab_system":
        d.click_frac(0.586, 0.167)
        time.sleep(1.5)
        d.wait_stable(timeout=20, tag="system")
        d.shot("m05_settings_system")
    elif phase == "tabx":
        fx = float(sys.argv[2])
        d.click_frac(0.5, 0.93)   # priming click on empty panel area
        time.sleep(1.0)
        d.click_frac(fx, 0.167)
        time.sleep(1.5)
        d.wait_stable(timeout=20, tag="tabx")
        d.shot(sys.argv[3])
    elif phase == "xl_screen":
        d.click_frac(0.5, 0.93)
        time.sleep(0.8)
        d.click_frac(0.571, 0.167)   # screen tab
        time.sleep(1.5)
        d.click_frac(0.662, 0.521)   # text size value: standard -> large
        time.sleep(1.2)
        d.shot("m07_screen_large")
        d.click_frac(0.662, 0.521)   # large -> extra-large
        time.sleep(1.2)
        d.wait_stable(timeout=20, tag="xl")
        d.shot("m08_screen_xl")
    elif phase == "xl_game":
        d.click_frac(0.5, 0.93)
        time.sleep(0.8)
        d.click_frac(0.289, 0.167)   # game tab
        time.sleep(1.5)
        d.wait_stable(timeout=20, tag="xl-game")
        d.shot("m09_game_xl")
    elif phase == "reset_start_s1":
        # back to standard text size (cycle wraps xlarge -> standard)
        d.click_frac(0.662, 0.521)
        time.sleep(1.2)
        d.shot("m10_screen_standard")
        # back to title
        d.click_frac(0.070, 0.055)
        time.sleep(2.0)
        d.wait_stable(timeout=25, tag="title2")
        d.shot("m11_title2")
        # Start -> hub
        d.click_frac(0.5, 0.93)
        time.sleep(0.8)
        d.click_logical(291, 939)
        time.sleep(2.5)
        d.wait_stable(timeout=30, tag="hub")
        d.shot("m12_hub")
    elif phase == "open_s1":
        d.click_frac(0.5, 0.93)
        time.sleep(0.8)
        d.click_frac(0.086, 0.651)   # S1 node
        time.sleep(2.0)
        d.wait_stable(timeout=25, tag="s1detail")
        d.shot("m13_s1_detail")
    elif phase == "click_frac":
        d.click_frac(0.5, 0.93)
        time.sleep(0.8)
        d.click_frac(float(sys.argv[2]), float(sys.argv[3]))
        time.sleep(2.0)
        d.wait_stable(timeout=25, tag="cf")
        d.shot(sys.argv[4])
    elif phase == "raw_click":
        d.click_frac(float(sys.argv[2]), float(sys.argv[3]))
        time.sleep(2.0)
        d.wait_stable(timeout=25, tag="rc")
        d.shot(sys.argv[4])
    elif phase == "burst_dest":
        # re-select the demo piece first, then burst-shoot the
        # destination tap
        d.click_frac(0.088, 0.805)
        time.sleep(1.5)
        d.shot("b0_selected")
        d.click_frac(0.088, 0.598)
        for i in range(6):
            time.sleep(0.35)
            d.shot(f"b{i+1}_dest")
    elif phase == "demo_attack":
        d.click_frac(0.088, 0.598)   # select the captain at (2,0)
        time.sleep(1.5)
        d.shot("c0_atk_selected")
        d.click_frac(0.088, 0.391)   # tap the warg rider at (1,0)
        time.sleep(1.2)
        d.shot("c1_atk_forecast")
        time.sleep(2.5)
        d.wait_stable(timeout=25, tag="atk")
        d.shot("c2_atk_after")
    elif phase == "move2":
        # generic two-tap move: select (fx1,fy1) then tap (fx2,fy2)
        d.click_frac(float(sys.argv[2]), float(sys.argv[3]))
        time.sleep(1.5)
        d.shot(sys.argv[6] + "_sel")
        d.click_frac(float(sys.argv[4]), float(sys.argv[5]))
        time.sleep(2.0)
        d.shot(sys.argv[6] + "_mid")
        time.sleep(3.0)
        d.wait_stable(timeout=30, tag="mv")
        d.shot(sys.argv[6] + "_after")
    elif phase == "arm_forecast":
        d.click_frac(0.417, 0.801)   # select the hero at (3,2)
        time.sleep(1.5)
        d.shot("e0_hero_sel")
        d.click_frac(0.088, 0.184)   # tap the demon king at (0,0), far out of range
        time.sleep(0.4)
        d.shot("e1_armed_a")
        time.sleep(0.5)
        d.shot("e2_armed_b")
    elif phase == "s2_approach":
        d.click_frac(0.253, 0.638)   # select the captain at (3,1)
        time.sleep(1.5)
        d.shot("h5_s2_sel")
        d.click_frac(0.253, 0.462)   # move to (2,1)
        time.sleep(2.0)
        d.shot("h6_s2_moved")
        time.sleep(3.0)
        d.wait_stable(timeout=30, tag="s2app")
        d.shot("h7_s2_after_cpu")
    elif phase == "s2_gate":
        d.click_frac(0.253, 0.462)   # select the captain at (2,1)
        time.sleep(1.5)
        d.shot("h8_s2_atk_sel")
        d.click_frac(0.253, 0.293)   # tap the shadow at (1,1) -> confirm gate
        time.sleep(1.8)
        d.shot("h9_gate_state")
        # unrelated board tap during the gate -> boost pulse
        d.click_frac(0.582, 0.814)
        time.sleep(0.25)
        d.shot("h10_gate_boost")
        time.sleep(1.5)
        d.shot("h11_gate_after")
    elif phase == "p_s1_start":
        d.click_frac(0.5, 0.93)
        time.sleep(0.8)
        d.click_logical(291, 939)    # Start -> hub
        time.sleep(2.5)
        d.wait_stable(timeout=30, tag="hub")
        d.shot("n01_hub")
        d.click_frac(0.086, 0.651)   # S1 node
        time.sleep(2.0)
        d.wait_stable(timeout=25, tag="s1detail")
        d.shot("n02_s1_detail")
        d.click_frac(0.838, 0.805)   # Start button on the detail panel
        time.sleep(2.5)
        d.wait_stable(timeout=25, tag="convo")
        d.shot("n03_convo")
        d.click_frac(0.918, 0.062)   # skip
        time.sleep(2.5)
        d.wait_stable(timeout=30, tag="match")
        d.shot("n04_s1_match")
    elif phase == "p_s1_play":
        # demo move: captain (3,0) -> (2,0)
        d.click_frac(0.088, 0.805)
        time.sleep(1.5)
        d.click_frac(0.088, 0.598)
        time.sleep(2.5)
        d.wait_stable(timeout=30, tag="demomove")
        d.shot("n05_demo_moved")
        # demo attack: captain (2,0) -> warg rider (1,0)
        d.click_frac(0.088, 0.598)
        time.sleep(1.5)
        d.click_frac(0.088, 0.391)
        time.sleep(3.0)
        d.wait_stable(timeout=30, tag="demoatk")
        d.shot("n06_demo_attacked")
        # captain up: (1,0) -> (0,0); the demon king kills it (scripted line as before)
        d.click_frac(0.088, 0.391)
        time.sleep(1.5)
        d.click_frac(0.088, 0.184)
        time.sleep(3.0)
        d.wait_stable(timeout=30, tag="capup")
        d.shot("n07_cap_up")
        # hero up: (3,2) -> (2,2)
        d.click_frac(0.417, 0.801)
        time.sleep(1.5)
        d.click_frac(0.417, 0.598)
        time.sleep(3.0)
        d.wait_stable(timeout=30, tag="heroup")
        d.shot("n08_hero_up")
        # hero up2: (2,2) -> (1,2)
        d.click_frac(0.417, 0.598)
        time.sleep(1.5)
        d.click_frac(0.417, 0.391)
        time.sleep(3.0)
        d.wait_stable(timeout=30, tag="heroup2")
        d.shot("n09_hero_up2")
        # hero attacks the HQ cell (0,2): arm, shoot, confirm
        d.click_frac(0.417, 0.391)
        time.sleep(1.5)
        d.click_frac(0.417, 0.184)
        time.sleep(1.5)
        d.shot("n10_hero_armed")
        d.click_frac(0.417, 0.184)
        time.sleep(3.5)
        d.wait_stable(timeout=30, tag="clear")
        d.shot("n11_s1_clear")
    elif phase == "p_s2_start":
        d.click_frac(0.652, 0.806)   # next stage
        time.sleep(2.5)
        d.wait_stable(timeout=25, tag="s2convo")
        d.shot("n12_s2_convo")
        d.click_frac(0.918, 0.062)   # skip
        time.sleep(2.5)
        d.wait_stable(timeout=30, tag="s2match")
        d.shot("n13_s2_match")
    elif phase == "p_s2_gate":
        d.click_frac(0.253, 0.293)   # demo: tap the framed shadow (1,1)
        time.sleep(2.0)
        d.shot("n14_s2_shadow")
        d.click_frac(0.253, 0.638)   # select the captain (3,1)
        time.sleep(1.5)
        d.click_frac(0.253, 0.462)   # approach to (2,1)
        time.sleep(3.0)
        d.wait_stable(timeout=30, tag="s2app")
        d.shot("n15_s2_approach")
        d.click_frac(0.253, 0.462)   # select the captain (2,1)
        time.sleep(1.5)
        d.click_frac(0.253, 0.293)   # tap the shadow (1,1) -> gate
        time.sleep(1.8)
        d.shot("n16_gate_state")
        d.click_frac(0.582, 0.814)   # unrelated tap -> boost
        time.sleep(0.25)
        d.shot("n17_gate_boost")
        time.sleep(1.5)
        d.shot("n18_gate_after")
    elif phase == "p_reload":
        d.cdp.call("Page.reload", {"ignoreCache": True})
        time.sleep(10)
        d.wait_stable(timeout=90, tag="reload-title")
        d.shot("n00_title3")
    elif phase == "p_next2":
        d.click_frac(0.681, 0.807)
        time.sleep(1.2)
        d.click_frac(0.681, 0.807)
        time.sleep(2.5)
        d.wait_stable(timeout=25, tag="next2")
        d.shot("n17_next")
    elif phase == "p_reload_title":
        d.cdp.call("Page.reload", {"ignoreCache": False})
        time.sleep(10)
        d.wait_stable(timeout=90, tag="rl")
        d.shot("n20_reloaded")
    elif phase == "p_hub_s2":
        d.click_frac(0.5, 0.93)
        time.sleep(0.8)
        d.click_logical(291, 939)    # Start -> hub
        time.sleep(2.5)
        d.wait_stable(timeout=30, tag="hub2")
        d.shot("n21_hub")
    elif phase == "back_title":
        d.click_frac(0.070, 0.055)
        time.sleep(2.0)
        d.wait_stable(timeout=25, tag="back-title")
        d.shot("m06_title_again")
    if phase == "probe_click":
        d.ev("""window.__probe = [];
            ['mousedown','mouseup','click','pointerdown'].forEach(t =>
              window.addEventListener(t, e => window.__probe.push(
                t + ' ' + e.clientX + ',' + e.clientY), true)); 'armed'""")
        d.click_frac(0.848, 0.869)
        time.sleep(1.0)
        print("PROBE:", d.ev("JSON.stringify(window.__probe)"), flush=True)
        print("CANVAS:", d.ev("""(() => { const c = document.querySelector('canvas');
            const r = c.getBoundingClientRect();
            return JSON.stringify({x: r.x, y: r.y, w: r.width, h: r.height,
              iw: window.innerWidth, ih: window.innerHeight}); })()"""), flush=True)
    elif phase == "shotonly":
        d.shot(sys.argv[2])
    elif phase == "title":
        d.wait_stable(timeout=30, tag="title")
        d.shot("m01_title")
    elif phase == "settings":
        d.wait_stable(timeout=25, tag="pre-settings")
        # priming click on an empty area (absorbs any resize /
        # fullscreen transition, per the CV batch lesson)
        d.click_logical(960, 120)
        time.sleep(1.5)
        # Settings button: logical (1629, 939)
        d.click_logical(1629, 939)
        time.sleep(2.5)
        d.wait_stable(timeout=25, tag="settings")
        d.shot("m02_settings_game")
    print("ERRORS:", len(d.errors()), flush=True)
    for e in d.errors()[:5]:
        print("ERR:", e, flush=True)
    print("PHASE_DONE", phase, flush=True)

if __name__ == "__main__":
    main()
