#!/usr/bin/env python3
"""ForecastSheet rework: attach driver for adaptive play.
Attaches to the EXISTING game tab (the main phase's Chrome session)
and performs small, caller-specified steps so the operator can read
each screenshot and decide the next taps from the real board.

  phase look            : shot only (fs_state)
  phase tap fx fy [...] : click each fraction pair, shot after each
                          (fs_tap_0, fs_tap_1, ...), wait stable at end
  phase cell r c [...]  : same but Pos(r, c) via cv.cell
"""
import json
import os
import sys
import time
import urllib.request

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import cv_drive as cv

cv.OUT = r"C:\Users\Public\kage_fs_captures"
os.makedirs(cv.OUT, exist_ok=True)


def attach():
    targets = json.loads(urllib.request.urlopen(
        "http://127.0.0.1:9223/json/list", timeout=10).read().decode())
    page = None
    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)
    d = object.__new__(cv.Drv)
    d.cdp = cv.CDP(page["webSocketDebuggerUrl"])
    d.cdp.call("Page.enable")
    d.cdp.call("Runtime.enable")
    d.cdp.call("Log.enable")
    d.cdp.call("Emulation.setDeviceMetricsOverride",
               {"width": 1366, "height": 768, "deviceScaleFactor": 1,
                "mobile": False})
    d.exceptions = []
    return d


def main():
    d = attach()
    mode = sys.argv[1] if len(sys.argv) > 1 else "look"
    if mode == "burst":
        fx, fy = float(sys.argv[2]), float(sys.argv[3])
        d.click_frac(fx, fy)
        for i in range(12):
            d.shot(f"fs_burst_{i}")
            time.sleep(0.55)
    elif mode == "tburst":
        fx, fy = float(sys.argv[2]), float(sys.argv[3])
        d.touch_frac(fx, fy, wait=0)
        for i in range(16):
            d.shot(f"fs_tburst_{i}")
            time.sleep(0.5)
    elif mode == "look":
        d.shot("fs_state")
    elif mode == "touch":
        vals = [float(x) for x in sys.argv[2:]]
        for i, (fx, fy) in enumerate(zip(vals[0::2], vals[1::2])):
            pre = d.fp()
            d.touch_frac(fx, fy, wait=2)
            d.wait_change(pre, 3.0, timeout=45, tag=f"touch{i}")
            d.wait_stable(timeout=20, tag=f"touch{i}-stable")
            d.shot(f"fs_touch_{i}")
            time.sleep(1.0)
    elif mode in ("tap", "cell"):
        args = sys.argv[2:]
        pairs = []
        if mode == "tap":
            vals = [float(x) for x in args]
            pairs = list(zip(vals[0::2], vals[1::2]))
        else:
            vals = [int(x) for x in args]
            pairs = [cv.cell(r, c) for r, c in zip(vals[0::2], vals[1::2])]
        for i, (fx, fy) in enumerate(pairs):
            pre = d.fp()
            d.click_frac(fx, fy)
            d.wait_change(pre, 3.0, timeout=45, tag=f"tap{i}")
            d.wait_stable(timeout=20, tag=f"tap{i}-stable")
            d.shot(f"fs_tap_{i}")
            time.sleep(1.0)
    errs = d.errors()
    print("console errors:", len(errs), flush=True)
    for e in errs[:5]:
        print("ERR:", e, flush=True)
    print("DRIVE2_DONE", flush=True)


if __name__ == "__main__":
    main()
