#!/usr/bin/env python3
"""Visual sweep driver (2026-12-03). Laptop Chrome via SSH tunnel, CDP 9235,
own profile kage_sweep_profile. Shots saved on the VM.
Phases:
  open NAME          fresh target, navigate, wait title, shot
  shot NAME          wait stable, shot
  shotfast NAME      shot immediately
  click FX FY NAME [fast]   click; wait stable (or 1.2s if fast), shot
  setint KEY VAL     patch PlayerPrefs int, reload, wait title
  ev EXPR            evaluate JS (awaitPromise), print result
  buildid            print Build/ resource URLs
  errors             print captured console errors
  mean               print mean luminance of current frame
"""
import base64
import io
import json
import os
import sys
import time
import urllib.request
import websocket
from PIL import Image

HERE = os.path.dirname(os.path.abspath(__file__))
OUT = r"C:\Users\Public\kage_sweep_captures"
os.makedirs(OUT, exist_ok=True)
BASE = "https://rankshroud-preview.pages.dev/"
PORT = 9235
W, H = 1920, 1080

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


def mean_of(png_bytes):
    im = Image.open(io.BytesIO(png_bytes)).convert("L").resize((96, 54))
    d = list(im.getdata())
    return sum(d) / len(d)


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, create=False):
        page = None
        ver = json.loads(urllib.request.urlopen(
            f"http://127.0.0.1:{PORT}/json/version", timeout=10).read().decode())
        if create:
            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)
        else:
            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 not page:
                for t in targets:
                    if t.get("type") == "page":
                        page = t
                        break
        if not page:
            print("NO PAGE TARGET", flush=True)
            sys.exit(2)
        self.cdp = CDP(page["webSocketDebuggerUrl"])
        self.cdp.call("Page.enable")
        try:
            self.cdp.call("Page.bringToFront")
        except Exception:
            pass
        self.cdp.call("Runtime.enable")
        self.cdp.call("Log.enable")
        self.cdp.call("Page.addScriptToEvaluateOnNewDocument", {"source": HOOK})

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

    def navigate(self, url):
        self.cdp.call("Page.navigate", {"url": url})
        print("nav", url, flush=True)
        time.sleep(3)

    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), "mean=%.1f" % mean_of(raw), flush=True)
        return raw

    def fp(self):
        return fp_of(self.shot_bytes())

    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_title(self, timeout=300, tag="title"):
        t0 = time.time()
        while time.time() - t0 < timeout:
            try:
                raw = self.shot_bytes()
                m = mean_of(raw)
                if m > 55:
                    # confirm stability
                    time.sleep(1.5)
                    raw2 = self.shot_bytes()
                    if fp_diff(fp_of(raw), fp_of(raw2)) < 6.0:
                        print(f"gate {tag}: title mean={m:.1f} after {time.time()-t0:.1f}s", flush=True)
                        return raw2
            except Exception as e:
                print("title poll err:", type(e).__name__, flush=True)
            time.sleep(2)
        print(f"gate {tag}: title TIMEOUT", flush=True)
        return None

    def touch(self, fx, fy):
        r = 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};})()")
        if not r:
            print("touch: no canvas rect", flush=True)
            return
        x, y = r["x"] + fx * r["w"], r["y"] + fy * r["h"]
        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},{fy}) -> ({x:.0f},{y:.0f})", flush=True)

    def click(self, fx, fy):
        r = 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};})()")
        if not r:
            print("click: no canvas rect", flush=True)
            return
        x, y = r["x"] + fx * r["w"], r["y"] + fy * r["h"]
        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(0.25)
        self.cdp.call("Input.dispatchMouseEvent",
                      {"type": "mouseReleased", "x": x, "y": y, "button": "left",
                       "buttons": 0, "clickCount": 1})
        print(f"click ({fx},{fy}) -> ({x:.0f},{y:.0f})", flush=True)


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):
    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(expr, timeout=60, await_promise=True)


def main():
    phase = sys.argv[1]
    if phase == "open":
        d = Drv(create=True)
        d.navigate(BASE)
        d.wait_title()
        d.shot(sys.argv[2])
    elif phase == "reload":
        d = Drv()
        d.navigate(BASE)
        d.wait_title()
        d.shot(sys.argv[2])
    elif phase == "shot":
        d = Drv()
        d.wait_stable()
        d.shot(sys.argv[2])
    elif phase == "shotfast":
        d = Drv()
        d.shot(sys.argv[2])
    elif phase == "click":
        d = Drv()
        fx, fy, name = float(sys.argv[2]), float(sys.argv[3]), sys.argv[4]
        mode = sys.argv[5] if len(sys.argv) > 5 else "stable"
        d.click(fx, fy)
        if mode == "fast":
            time.sleep(1.2)
        elif mode == "mid":
            time.sleep(4)
            d.wait_stable(timeout=30)
        else:
            time.sleep(1.0)
            d.wait_stable()
        d.shot(name)
    elif phase == "touch":
        d = Drv()
        fx, fy, name = float(sys.argv[2]), float(sys.argv[3]), sys.argv[4]
        mode = sys.argv[5] if len(sys.argv) > 5 else "stable"
        d.touch(fx, fy)
        if mode == "fast":
            time.sleep(1.2)
        else:
            time.sleep(1.0)
            d.wait_stable()
        d.shot(name)
    elif phase == "setint":
        d = Drv()
        print("prefs patch:", sys.argv[2], "=", sys.argv[3],
              js_prefs_patch_int(d, sys.argv[2], int(sys.argv[3])), flush=True)
        d.navigate(BASE)
        d.wait_title()
        print("SETINT_DONE", flush=True)
    elif phase == "evfile":
        d = Drv()
        expr = open(r"C:\Users\Public\ev_expr.js", encoding="utf-8").read()
        print(json.dumps(d.ev(expr, timeout=60, await_promise=True),
                         ensure_ascii=False, default=str)[:3000], flush=True)
    elif phase == "ev":
        d = Drv()
        print(json.dumps(d.ev(sys.argv[2], timeout=60, await_promise=True),
                         ensure_ascii=False, default=str)[:2000], flush=True)
    elif phase == "buildid":
        d = Drv()
        v = d.ev("performance.getEntriesByType('resource').map(e=>e.name).filter(n=>n.includes('/Build/'))")
        print(json.dumps(v, ensure_ascii=False, indent=1), flush=True)
    elif phase == "errors":
        d = Drv()
        v = d.ev("window.__cap ? window.__cap.filter(s=>s.startsWith('error')||s.startsWith('warn')) : []")
        print(json.dumps(v, ensure_ascii=False, indent=1)[:4000] if v else "no cap", flush=True)
    elif phase == "mean":
        d = Drv()
        print("mean=%.1f" % mean_of(d.shot_bytes()), flush=True)
    print("DONE", phase, flush=True)


if __name__ == "__main__":
    main()
