import os, json, urllib.parse, random, subprocess, collections

D = "/app/data/tasks/29/i29cq9s"
TREE = os.path.join(D, "tree")
refs = json.load(open(os.path.join(D, "refs.json")))

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

def disk(u):
    p = os.path.join(TREE, key(u))
    return os.path.exists(p) and os.path.getsize(p) > 0

rows = []
full = 0
for code, lst in sorted(refs.items()):
    dedup = sorted(set(lst))
    have = [u for u in dedup if disk(u)]
    miss = [u for u in dedup if not disk(u)]
    r = len(have) / len(dedup)
    if not miss:
        full += 1
    rows.append((code, len(dedup), len(have), r, miss))
with open(os.path.join(D, "cover.tsv"), "w") as f:
    for c, n, h, r, miss in rows:
        f.write("%s\t%d\t%d\t%.3f\t%s\n" % (c, n, h, r, ";".join(miss)))
print("codes", len(rows), "disk==refs codes", full)
print("refs total", sum(r[1] for r in rows), "have", sum(r[2] for r in rows))

MAG = {".js": "function", ".png": "89504e47", ".json": "{", ".wav": "RIFF", ".css": None}
def magic(path):
    ext = os.path.splitext(path)[1].lower()
    with open(path, "rb") as f:
        head = f.read(4096)
    if ext == ".js":
        return b"function" in head, head[:16].hex()
    if ext == ".png":
        return head.startswith(bytes.fromhex("89504e47")), head[:16].hex()
    if ext == ".json":
        return head.lstrip()[:1] == b"{", head[:16].hex()
    if ext == ".wav":
        return head.startswith(b"RIFF"), head[:16].hex()
    if ext == ".css":
        return not head.lstrip().startswith(b"<!DOCTYPE"), head[:16].hex()
    return True, head[:16].hex()

# pick 5 codes with most disk files
cand = sorted(rows, key=lambda r: -r[2])[:5]
tot = good = 0
lines = []
for c, n, h, r, miss in cand:
    files = [os.path.join(TREE, key(u)) for u in sorted(set(refs[c])) if disk(u)]
    pick = random.Random(7).sample(files, min(8, len(files)))
    for p in pick:
        ok, hd = magic(p)
        tot += 1; good += ok
        lines.append("%s\t%s\t%s\t%s" % (c, os.path.relpath(p, TREE), "OK" if ok else "BAD", hd[:16]))
with open(os.path.join(D, "magic.tsv"), "w") as f:
    f.write("\n".join(lines))
print("magic", good, "/", tot, "bad:", [l for l in lines if "\tBAD\t" in l][:5])

allf = [os.path.join(dp, fn) for dp, _, fns in os.walk(TREE) for fn in fns]
random.Random(11).shuffle(allf)
doct = [p for p in allf if os.path.getsize(p) > 0 and open(p, "rb").read(9).lstrip()[:9].startswith(b"<!DOCTYPE")]
print("files", len(allf), "doctype", len(doct), "sample10 doctype:",
      sum(1 for p in allf if open(p, "rb").read(16).lstrip().startswith(b"<!DOCTYPE")) if False else "")
s10 = allf[:10]
print("random10 heads:", [(os.path.basename(p), open(p, "rb").read(16)[:12]) for p in s10])
print("doctype files sample:", doct[:5])
