import sys, os, time, urllib.request, urllib.error, concurrent.futures

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"
OUT = os.path.dirname(os.path.abspath(__file__))
SHELLS = os.path.join(OUT, "shells")
os.makedirs(SHELLS, exist_ok=True)

codes = [l.strip() for l in open("/app/data/tasks/29/i29cq9u/ids.tsv") if l.strip()]

def fetch(code):
    url = "%s/h5/%s/index.html" % (BASE, code)
    for attempt in range(2):
        try:
            req = urllib.request.Request(url, headers={"User-Agent": UA})
            with urllib.request.urlopen(req, timeout=25) as r:
                body = r.read()
                st = r.status
            if st == 200 and b"data-ta" in body:
                open(os.path.join(SHELLS, code + ".html"), "wb").write(body)
                return code, st, len(body), "ok"
            return code, st, len(body), "no-data-ta" if st == 200 else "http"
        except urllib.error.HTTPError as e:
            st = e.code
            if attempt == 1:
                return code, st, 0, "http"
        except Exception as e:
            if attempt == 1:
                return code, 0, 0, type(e).__name__
        time.sleep(0.5)

res = []
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as ex:
    for r in ex.map(fetch, codes):
        res.append(r)
with open(os.path.join(OUT, "status.tsv"), "w") as f:
    for c, st, ln, note in res:
        f.write("%s\t%s\t%s\t%s\n" % (c, st, ln, note))
ok = sum(1 for r in res if r[3] == "ok")
print("OK", ok, "of", len(res))
from collections import Counter
print(Counter(r[3] for r in res).most_common())
print("fail codes:", [r[0] for r in res if r[3] != "ok"][:40])
