import os, sys, time, urllib.request, urllib.error, urllib.parse, json, re, concurrent.futures, hashlib

D = "/app/data/tasks/29/i29cq9s"
TREE = os.path.join(D, "tree")
BASE = "https://h5cq.cqgame.games"
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36"
CAP = 8000

def key(u):
    p = urllib.parse.urlparse(u)
    return p.path.lstrip("/")

def fetch(u, referer):
    path = os.path.join(TREE, key(u))
    if os.path.exists(path) and os.path.getsize(path) > 0:
        if path.endswith((".js", ".html")):
            return u, "skip", os.path.getsize(path)
        return u, "skip", os.path.getsize(path)
    os.makedirs(os.path.dirname(path), exist_ok=True)
    for attempt in range(2):
        try:
            req = urllib.request.Request(u, headers={"User-Agent": UA, "Referer": referer})
            with urllib.request.urlopen(req, timeout=25) as r:
                st = r.status
                body = r.read()
            if st == 200 and len(body) > 0:
                open(path, "wb").write(body)
                return u, "ok", len(body)
            return u, "http%d" % st, 0
        except urllib.error.HTTPError as e:
            if attempt == 1:
                return u, "http%d" % e.code, 0
        except Exception as e:
            if attempt == 1:
                return u, type(e).__name__, 0
        time.sleep(0.4)

refs = json.load(open(os.path.join(D, "refs.json")))
urls = [l.strip() for l in open(os.path.join(D, "urls.txt")) if l.strip()]
url2ref = {}
for c, lst in refs.items():
    for u in lst:
        url2ref.setdefault(u, "%s/h5/%s/index.html" % (BASE, c))

def run(urls, logname):
    urls = urls[:CAP]
    res = []
    with concurrent.futures.ThreadPoolExecutor(max_workers=10) as ex:
        futs = [ex.submit(fetch, u, url2ref.get(u, "%s/h5/%s/index.html" % (BASE, urllib.parse.urlparse(u).path.split("/")[2] if len(urllib.parse.urlparse(u).path.split("/"))>2 else ""))) for u in urls]
        for f in concurrent.futures.as_completed(futs):
            res.append(f.result())
    with open(os.path.join(D, logname), "a") as f:
        for u, note, ln in res:
            f.write("%s\t%s\t%s\n" % (u, note, ln))
    from collections import Counter
    print(logname, Counter(r[1] for r in res).most_common(8), flush=True)
    return res

res = run(urls, "fetch1.log")
if "--expand" in sys.argv:
    newurls = set()
    for u, note, ln in res:
        if note != "ok" or not u.endswith(".js"):
            continue
        try:
            txt = open(os.path.join(TREE, key(u)), "rb").read().decode("utf-8", "replace")
        except Exception:
            continue
        for m in set(re.findall(r'["\']([^"\'\\ ]+\.(?:png|jpg|json|atlas|mp3|ogg|wav|mp4|webp|css|js|fnt|cconb|bin))', txt)):
            nu = urllib.parse.urljoin(u, m)
            if nu.startswith(BASE) and "?" not in nu:
                newurls.add(nu)
    newurls -= set(urls)
    print("expanded", len(newurls), flush=True)
    open(os.path.join(D, "urls2.txt"), "w").write("\n".join(sorted(newurls)))
    run(sorted(newurls), "fetch2.log")
