#!/usr/bin/env python3
import sys, os, re, subprocess, urllib.parse
UA="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/131.0.0.0 Safari/537.36"
HOST="web-gb-r.cqgame.games"
OUT="/app/data/tasks/29/i29map2/CQ9"
def local(u):
    p=urllib.parse.urlsplit(u).path.lstrip("/")
    if p.endswith("/") or p=="": p+="index.html"
    return os.path.join(OUT,p)
def fetch(u,ref):
    lp=local(u)
    if os.path.exists(lp) and os.path.getsize(lp)>0: return "200",len(open(lp,'rb').read())
    os.makedirs(os.path.dirname(lp),exist_ok=True)
    args=["curl","-s","-m","60","-A",UA]
    if ref: args+=["-e",ref]
    args+=["-o",lp,"-w","%{http_code}",u]
    r=subprocess.run(args,capture_output=True,text=True)
    code=r.stdout.strip()
    if not(code.startswith("2") and os.path.exists(lp) and os.path.getsize(lp)>0):
        if os.path.exists(lp) and os.path.getsize(lp)==0: os.remove(lp)
    sz=os.path.getsize(lp) if os.path.exists(lp) else 0
    return code,sz
REF=re.compile(r"""(?:src|href)\s*=\s*["']([^"'#]+)["']""",re.I)
CSS=re.compile(r"""url\(\s*['"]?([^'")]+)""")
def refs_of(u,text):
    base=u
    out=[]
    for m in list(REF.finditer(text))+list(CSS.finditer(text)):
        ru=urllib.parse.urljoin(base,m.group(1))
        sp=urllib.parse.urlsplit(ru)
        if sp.scheme not in("http","https"): continue
        if sp.netloc!=HOST: continue
        out.append(ru)
    return out
for code in sys.argv[1:]:
    shell=f"https://{HOST}/h5/{code}/index.html"
    sc,sz=fetch(shell,None)
    print(f"== {code} shell {sc} {sz}")
    if not(sc.startswith("2") and sz>0): continue
    txt=open(local(shell),encoding="utf-8",errors="replace").read()
    got=0
    for ru in refs_of(shell,txt):
        c,s=fetch(ru,shell)
        if c.startswith("2") and s>0: got+=1
        else: print(f"   miss {c} {ru}")
    print(f"   refs_ok {got}")
