#!/usr/bin/env python3
"""CV toggle removal batch: regression capture driver (laptop Chrome,
CDP 9223, real GPU). Based on work_sj/reg_drive.py (state-jump batch).
Method per STARTUP_TIME_MEASURE_20261129.md: dedicated profile + CDP,
arrival judged by 48x27 grayscale fingerprint reference match (title/board
refs from refs2.json) or change+stable gates for screens without refs.
Fixed sleeps are never used as arrival evidence.
Phases: REG = R-01..R-12 at standard text size; XL = settings screens
after patching kage.settings.text_size=2 (extra-large), for the
post-removal layout check of the Screen tab.
Outputs PNGs to C:\\Users\\Public\\kage_cv_captures and prints a log.
Abort markers: ABORT_TITLE / ABORT_START (escalate if start does not move).
"""
import base64, io, json, os, sys, time, urllib.request
import websocket
from PIL import Image

HERE = os.path.dirname(os.path.abspath(__file__))
OUT = r"C:\Users\Public\kage_cv_captures"
os.makedirs(OUT, exist_ok=True)
BASE = "https://rankshroud-preview.pages.dev/"
PORT = 9223

REFS = json.load(open(os.path.join(HERE, "refs2.json"), encoding="utf-8"))
TITLE_FP = REFS["title_fp"]
BOARD_FP = REFS["board_fp"]

HOOK = """
window.__cap = [];
(function(){
  const cap = (kind, args) => {
    try {
      const s = Array.from(args).map(a => String(a)).join(' ');
      window.__cap.push(kind + ': ' + s);
      if (window.__cap.length > 800) window.__cap.splice(0, 300);
    } catch(e) {}
  };
  const ol = console.log, ow = console.warn, oe = console.error;
  console.log = function(){ cap('log', arguments); return ol.apply(console, arguments); };
  console.warn = function(){ cap('warn', arguments); return ow.apply(console, arguments); };
  console.error = function(){ cap('error', arguments); return oe.apply(console, arguments); };
})();
"""

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 cell2(irow, col):
    return (0.078 + 0.153 * col, 0.108 + 0.192 * irow)


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):
        # Open a FRESH tab through the browser-level Target API (a previous
        # run may have left a busy WebGL page; /json/new is unreliable in
        # current Chrome). Then connect to the new tab's page WS.
        page = None
        try:
            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)
        except Exception as e:
            print("target create failed:", type(e).__name__, e, flush=True)
        if not page:
            print("NO PAGE TARGET", flush=True)
            sys.exit(2)
        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.cdp.call("Page.addScriptToEvaluateOnNewDocument", {"source": HOOK})
        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 navigate(self, url):
        self.cdp.call("Page.navigate", {"url": url})
        print("nav", url, flush=True)

    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())

    # --- gates ---
    def wait_ref(self, ref, thresh=8.0, timeout=180, poll=0.6, tag="ref"):
        t0 = time.time()
        last = None
        while time.time() - t0 < timeout:
            try:
                cur = self.fp()
                last = fp_diff(cur, ref)
                if last < thresh:
                    print(f"gate {tag}: HIT diff={last:.2f} after {time.time()-t0:.1f}s", flush=True)
                    return cur
            except Exception as e:
                print("gate poll err:", type(e).__name__, flush=True)
            time.sleep(poll)
        print(f"gate {tag}: TIMEOUT last_diff={last}", flush=True)
        return None

    def wait_stable(self, timeout=60, poll=0.6, tag="stable"):
        t0 = time.time()
        prev = None
        while time.time() - t0 < timeout:
            try:
                cur = self.fp()
                if prev is not None and fp_diff(cur, prev) < 1.5:
                    print(f"gate {tag}: stable after {time.time()-t0:.1f}s", flush=True)
                    return cur
                prev = cur
            except Exception as e:
                print("stable poll err:", type(e).__name__, flush=True)
            time.sleep(poll)
        print(f"gate {tag}: stable TIMEOUT", flush=True)
        return prev

    def wait_change(self, prev_fp, min_diff=5.0, timeout=90, tag="change"):
        t0 = time.time()
        while time.time() - t0 < timeout:
            try:
                cur = self.fp()
                d = fp_diff(cur, prev_fp)
                if d >= min_diff:
                    print(f"gate {tag}: changed diff={d:.2f} after {time.time()-t0:.1f}s", flush=True)
                    return self.wait_stable(timeout=45, tag=tag + "-stable")
            except Exception as e:
                print("change poll err:", type(e).__name__, flush=True)
            time.sleep(0.6)
        print(f"gate {tag}: change TIMEOUT", flush=True)
        return None

    # --- input ---
    def canvas_rect(self):
        return self.ev("(()=>{const c=document.querySelector('canvas');"
                       "if(!c) return null; const b=c.getBoundingClientRect();"
                       "return {x:b.x,y:b.y,w:b.width,h:b.height};})()")

    def _xy(self, fx, fy):
        r = self.canvas_rect()
        return r["x"] + fx * r["w"], r["y"] + fy * r["h"]

    def click_frac(self, fx, fy, press_ms=250):
        x, y = self._xy(fx, fy)
        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 touch_frac(self, fx, fy, wait=2):
        x, y = self._xy(fx, fy)
        self.cdp.call("Input.dispatchTouchEvent",
                      {"type": "touchStart", "touchPoints": [{"x": x, "y": y, "id": 1}]})
        time.sleep(0.12)
        self.cdp.call("Input.dispatchTouchEvent",
                      {"type": "touchEnd", "touchPoints": []})
        print(f"touch ({fx:.3f},{fy:.3f})", flush=True)
        time.sleep(wait)

    def ev_async(self, expr, timeout=60):
        r = self.cdp.call("Runtime.evaluate",
                          {"expression": expr, "returnByValue": True,
                           "awaitPromise": True}, timeout=timeout)
        res = r.get("result", {})
        if "exceptionDetails" in r:
            return {"EXC": str(r["exceptionDetails"])[:300]}
        return res.get("value")

    def logs(self):
        v = self.ev("window.__cap ? window.__cap.slice() : []")
        return v if isinstance(v, list) else []

    def errors(self):
        return [l for l in self.logs() if l.startswith("error")]


PREFS_OPEN = """
const db = await new Promise((res, rej) => {
  const rq = indexedDB.open('/idbfs');
  rq.onsuccess = () => res(rq.result);
  rq.onerror = () => rej(rq.error);
});
const pkey = await new Promise((res, rej) => {
  const tx = db.transaction('FILE_DATA', 'readonly');
  const rq = tx.objectStore('FILE_DATA').getAllKeys();
  rq.onsuccess = () => res(rq.result.find(k => String(k).endsWith('/PlayerPrefs')));
  rq.onerror = () => rej(rq.error);
});
"""

PREFS_GET = PREFS_OPEN + """
if (!pkey) { db.close(); return {ok:false, reason:'no prefs file'}; }
const rec = await new Promise((res, rej) => {
  const tx = db.transaction('FILE_DATA', 'readonly');
  const rq = tx.objectStore('FILE_DATA').get(pkey);
  rq.onsuccess = () => res(rq.result);
  rq.onerror = () => rej(rq.error);
});
"""

PREFS_PUT = """
await new Promise((res, rej) => {
  const tx = db.transaction('FILE_DATA', 'readwrite');
  tx.oncomplete = () => res();
  tx.onerror = () => rej(tx.error);
  tx.objectStore('FILE_DATA').put(rec, pkey);
});
"""


def js_prefs_patch_int(d, key_name, value):
    """Set an int entry in the WebGL PlayerPrefs file (modify in place
    if present, else append). Same helper as the CG presubmit batch."""
    expr = "(async () => {\n" + PREFS_GET + """
const bytes = rec.contents;
const name = KEYNAME; const value = VALUE;
const nb = new TextEncoder().encode(name);
let done = 'append';
let out = bytes;
for (let i = 0; i + nb.length + 5 < bytes.length; i++) {
  let hit = true;
  for (let j = 0; j < nb.length; j++) if (bytes[i+1+j] !== nb[j]) { hit = false; break; }
  if (hit && bytes[i] === nb.length && bytes[i + nb.length + 1] === 0xfe) {
    out = new Uint8Array(bytes);
    const o = i + nb.length + 2;
    out[o] = value & 0xff; out[o+1] = (value>>8)&0xff;
    out[o+2] = (value>>16)&0xff; out[o+3] = (value>>24)&0xff;
    done = 'modify';
    break;
  }
}
if (done === 'append') {
  const entry = new Uint8Array(1 + nb.length + 1 + 4);
  entry[0] = nb.length;
  entry.set(nb, 1);
  entry[1 + nb.length] = 0xfe;
  const o = 1 + nb.length + 1;
  entry[o] = value & 0xff; entry[o+1] = (value>>8)&0xff;
  entry[o+2] = (value>>16)&0xff; entry[o+3] = (value>>24)&0xff;
  out = new Uint8Array(bytes.length + entry.length);
  out.set(bytes, 0);
  out.set(entry, bytes.length);
}
rec.contents = out;
""" + PREFS_PUT + """
db.close();
return {ok:true, how: done, len: out.length};
})()"""
    expr = expr.replace("KEYNAME", json.dumps(key_name)).replace("VALUE", str(int(value)))
    return d.ev_async(expr, timeout=60)


def main():
    d = Drv()
    # ---- phase REG: full regression flow (standard text size) ----
    d.navigate(BASE)
    hit = d.wait_ref(TITLE_FP, 8.0, timeout=240, tag="title")
    if not hit:
        print("ABORT_TITLE", flush=True)
        return
    time.sleep(2)
    fp_cur = d.shot("R01_title")
    d.shot("R01_title_retake")
    # title -> hub (operability gate: the frame must actually change)
    d.click_frac(0.128, 0.873)
    nxt = d.wait_change(fp_cur, 5.0, timeout=60, tag="to-hub")
    if not nxt:
        print("ABORT_START", flush=True)
        return
    fp_cur = d.shot("R02_hub")
    # hub -> settings (display tab)
    d.click_frac(0.95, 0.074)
    nxt = d.wait_change(fp_cur, 5.0, timeout=60, tag="to-settings")
    if nxt:
        fp_cur = nxt
    d.click_frac(0.617, 0.186)  # display tab
    d.wait_stable(timeout=30, tag="settings-tab")
    fp_cur = d.shot("R03_settings")
    d.touch_frac(0.069, 0.063, wait=2)  # close settings -> hub
    nxt = d.wait_change(fp_cur, 5.0, timeout=60, tag="settings-close")
    if nxt:
        fp_cur = nxt
    # hub -> S1 panel -> intro
    d.click_frac(0.0615, 0.6225)
    nxt = d.wait_change(fp_cur, 4.0, timeout=60, tag="s1-panel")
    if nxt:
        fp_cur = nxt
    d.click_frac(0.828, 0.800)  # panel start -> intro conversation
    d.wait_change(fp_cur, 4.0, timeout=60, tag="to-intro")
    board = None
    conv_fp = None
    for i in range(24):
        d.click_frac(0.5, 0.78)
        time.sleep(1.3)
        if i + 1 == 3:
            conv_fp = d.shot("R12_conversation")
        if i + 1 >= 6:
            cur = d.fp()
            dd = fp_diff(cur, BOARD_FP)
            cd = fp_diff(cur, conv_fp) if conv_fp else -1
            print(f"tap {i+1}: board diff {dd:.2f} conv diff {cd:.2f}", flush=True)
            if dd < 8.0:
                board = cur
                break
            if cd > 30:
                print("board arrival via change-from-conversation", flush=True)
                board = d.wait_stable(timeout=30, tag="board-arrive") or cur
                break
    if not board:
        print("ABORT_BOARD", flush=True)
        return
    d.shot("R04_s1_board")
    time.sleep(2)
    d.shot("R04_s1_board_retake")
    # demo forecast (R-05)
    d.click_frac(*cell(3, 2)); time.sleep(1.5)
    d.click_frac(*cell(3, 0)); time.sleep(1.5)
    pre = d.fp()
    d.click_frac(*cell(2, 0))
    d.wait_change(pre, 4.0, timeout=60, tag="demo-move")
    pre = d.fp()
    d.click_frac(*cell(2, 0))
    d.wait_change(pre, 3.0, timeout=60, tag="to-forecast")
    d.wait_stable(timeout=30, tag="forecast")
    d.shot("R05_forecast")
    # demo attack -> after battle (R-06)
    pre = d.fp()
    d.click_frac(*cell(1, 0))
    d.wait_change(pre, 4.0, timeout=90, tag="demo-attack")
    d.wait_stable(timeout=45, tag="after-battle")
    d.shot("R06_after_battle")
    # finish S1 -> victory dialog (R-07)
    d.click_frac(*cell(3, 2)); time.sleep(1.5)
    pre = d.fp()
    d.click_frac(*cell(2, 2))
    d.wait_change(pre, 4.0, timeout=90, tag="fin-1")
    d.click_frac(*cell(2, 2)); time.sleep(1.5)
    pre = d.fp()
    d.click_frac(*cell(1, 2))
    d.wait_change(pre, 4.0, timeout=90, tag="fin-2")
    d.click_frac(*cell(1, 2)); time.sleep(1.5)
    pre = d.fp()
    d.click_frac(*cell(0, 2))  # HQ capture -> ending
    d.wait_change(pre, 4.0, timeout=90, tag="fin-3")
    d.shot("aux_ending")
    d.click_frac(0.868, 0.05)  # skip ending
    d.wait_stable(timeout=45, tag="victory")
    d.shot("R07_victory")
    # S2 board (R-08)
    pre = d.fp()
    d.click_frac(0.645, 0.79)  # next stage (measured on the R-07 frame
    # in the state-jump batch; the old (0.69, 0.63) predates the
    # result-card summary layout and does not hit the button)
    d.wait_change(pre, 4.0, timeout=60, tag="to-s2panel")
    d.click_frac(0.828, 0.800)  # panel start
    time.sleep(4)
    d.click_frac(0.877, 0.053)  # skip conversation
    d.wait_stable(timeout=45, tag="s2-board")
    d.shot("R08_s2_board")
    # S2 candidates (R-09) -> gate (R-10)
    pre = d.fp()
    d.touch_frac(*cell2(1, 1), wait=2)
    d.wait_change(pre, 3.0, timeout=60, tag="s2-candidates")
    d.shot("R09_s2_candidates")
    d.click_frac(*cell2(3, 1)); time.sleep(1.5)
    pre = d.fp()
    d.click_frac(*cell2(2, 1))
    d.wait_change(pre, 4.0, timeout=90, tag="s2-approach")
    d.click_frac(*cell2(2, 1)); time.sleep(1.5)
    pre = d.fp()
    d.touch_frac(*cell2(1, 1), wait=2)
    d.wait_change(pre, 3.0, timeout=60, tag="s2-gate")
    d.wait_stable(timeout=30, tag="s2-gate-stable")
    d.shot("R10_s2_gate")
    # clash -> after battle (R-11)
    pre = d.fp()
    d.click_frac(0.885, 0.513, press_ms=450)
    d.wait_change(pre, 4.0, timeout=90, tag="s2-clash")
    d.wait_stable(timeout=45, tag="s2-after")
    d.shot("R11_s2_after")
    print("errors:", len(d.errors()), flush=True)
    print("REG_DONE", flush=True)

    # ---- phase XL: settings screens at extra-large text size ----
    # Patch the stored text-size index to 2 (150%) and reload; the
    # settings screen then opens at XL. Verify visually that the
    # Screen tab shows six rows with no gap where the color-vision
    # row used to be.
    print("text_size patch:", js_prefs_patch_int(
        d, "kage.settings.text_size", 2), flush=True)
    d.navigate(BASE)
    hit = d.wait_ref(TITLE_FP, 8.0, timeout=240, tag="xl-title")
    if not hit:
        print("ABORT_TITLE (xl phase)", flush=True)
        return
    time.sleep(2)
    fp_cur = d.fp()
    d.click_frac(0.95, 0.074)  # title -> settings
    nxt = d.wait_change(fp_cur, 5.0, timeout=60, tag="xl-to-settings")
    if nxt:
        fp_cur = nxt
    d.click_frac(0.617, 0.186)  # Screen tab
    d.wait_stable(timeout=30, tag="xl-settings-tab")
    d.shot("settings_screen_xl")
    # Game tab at XL as well (tab-label fit + six-row layout)
    d.click_frac(0.24, 0.186)
    d.wait_stable(timeout=30, tag="xl-game-tab")
    d.shot("settings_game_xl")
    print("errors:", len(d.errors()), flush=True)
    print("XL_DONE", flush=True)


if __name__ == "__main__":
    main()
