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 = ["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]
    return subprocess.run(cmd,capture_output=True,text=True).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: return None
done=set()
try:
    for ln in open(os.path.join(OUT,"matrix.tsv")):
        c=ln.rstrip("\n").split("\t")
        if len(c)>3 and "/" in c[3]:
            a,b=c[3].split("/")
            if a==b and a!="0": done.add(c[0])
except FileNotFoundError: pass
CODES=[c for c in CODES if c not in done] or CODES
print("TODO",CODES,flush=True)
usr=login()
for code in CODES:
    d=os.path.join(OUT,code); os.makedirs(d,exist_ok=True)
    def gl(tk):
        r=subprocess.run(["curl","-s","-m","30","-H",f"Authorization: {AGENT}","-d",f"usertoken={tk}&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); return j["status"]["code"], j.get("data",{}).get("url","")
        except: return "ERR",""
    st,url=gl(usr)
    if st!="0" or not url:
        usr=login() or usr; st,url=gl(usr)
    if st!="0" or not url:
        print(f"{code}\tGL:{st}",flush=True)
        open(os.path.join(OUT,"matrix.tsv"),"a").write(f"{code}\tgamelink:{st}\t0\t0/0\n"); continue
    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); 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 a in range(2):
            rc,rs=curl(full,["-e",url],os.path.join(d,name)).split()
            if rc=="200" and int(rs)>0: ok=True; break
            time.sleep(0.3)
        if ok: got+=1
    print(f"{code}\tidx:{hcode}({hsize})\tjs:{got}/{tot}",flush=True)
    open(os.path.join(OUT,"matrix.tsv"),"a").write(f"{code}\t{hcode}\t{hsize}\t{got}/{tot}\n")
