#!/usr/bin/env python3
import json, re, subprocess, sys, os, time

AGENT = open('/app/data/tasks/29/i26663/uat.jwt').read().strip()
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
CODES = ["3","16","20","42","24","33","52","58","201","105","19","72","5","7","29","31","69","8","10","202","9","17"]
BASE_H5 = "https://h5cq.cqgame.games"
OUT = "/app/data/tasks/29/i29cq9full"

def curl(url, extra, out=None):
    cmd = ["curl","-s","-m","40","-A",UA] + extra + ["-o", out if out else "/dev/null", "-w","%{http_code} %{size_download}", url]
    r = subprocess.run(cmd, capture_output=True, text=True)
    return r.stdout.strip()

def login():
    r = subprocess.run(["curl","-s","-m","30","-H",f"Authorization: {AGENT}","-d","account=opk17178&password=Ga1B-m06Jze08Lo_","https://api.cqgame.games/gameboy/player/login"], capture_output=True, text=True)
    try:
        return json.loads(r.stdout)["data"]["usertoken"]
    except Exception:
        return None

usertoken = login()
if not usertoken:
    print("LOGIN FAIL"); sys.exit(1)

rows = []
for code in CODES:
    d = os.path.join(OUT, code); os.makedirs(d, exist_ok=True)
    r = subprocess.run(["curl","-s","-m","30","-H",f"Authorization: {AGENT}","-d",f"usertoken={usertoken}&gamehall=cq9&gamecode={code}&gameplat=web&lang=en","https://api.cqgame.games/gameboy/player/gamelink"], capture_output=True, text=True)
    try:
        j = json.loads(r.stdout); st = j["status"]["code"]; url = j.get("data",{}).get("url","")
    except Exception:
        st, url = "ERR", ""
    # refresh usertoken if expired/failed
    if st not in ("0",) or not url:
        # retry once after relogin
        usertoken = login() or usertoken
        r = subprocess.run(["curl","-s","-m","30","-H",f"Authorization: {AGENT}","-d",f"usertoken={usertoken}&gamehall=cq9&gamecode={code}&gameplat=web&lang=en","https://api.cqgame.games/gameboy/player/gamelink"], capture_output=True, text=True)
        try:
            j = json.loads(r.stdout); st = j["status"]["code"]; url = j.get("data",{}).get("url","")
        except Exception:
            st, url = "ERR", ""
    if st != "0" or not url:
        rows.append((code, "gamelink:"+str(st), 0, 0, "0/0"))
        print(f"{code}\tGL:{st}"); continue
    # get index.html (no referer)
    hi = curl(url, [], os.path.join(d,"index.html"))
    hcode, hsize = hi.split()
    html = open(os.path.join(d,"index.html"), errors="ignore").read() if hcode=="200" else ""
    srcs = re.findall(r'(?:src|href)="([^"]+)"', html)
    # resolve all src/href relative to base /h5/<code>/
    got = 0; tot = 0
    for s in srcs:
        s = s.strip()
        if s.startswith("http"):
            full = s
        elif s.startswith("/"):
            full = BASE_H5 + s
        else:
            full = f"{BASE_H5}/h5/{code}/{s}"
        name = s.split("?")[0].split("/")[-1]
        tot += 1
        ok = False
        for attempt in range(2):
            res = curl(full, ["-e", url], os.path.join(d,name))
            rc, rs = res.split()
            if rc == "200" and int(rs) > 0:
                ok = True; break
            time.sleep(0.3)
        if ok: got += 1
    rows.append((code, hcode, hsize, tot, f"{got}/{tot}"))
    print(f"{code}\tidx:{hcode}({hsize})\tjs:{got}/{tot}")
    with open(os.path.join(OUT,"matrix.tsv"),"a") as f:
        f.write(f"{code}\t{hcode}\t{hsize}\t{got}/{tot}\n")
