"""Redirect-chain study: every hop for 4 URL variants of each sampled domain.

Sample: Tranco list 94GG2 (tranco-list.eu), ranks 1-100 000, random.Random(20261004),
1 000 domains. Each hop is fetched with curl without following redirects, so the
status code of every hop (301/302/307/308) is recorded. Max 15 hops, 10 s per hop.
"""
import csv, json, random, subprocess, sys, time
from concurrent.futures import ThreadPoolExecutor
from urllib.parse import urljoin
UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Safari/537.36"
N = int(sys.argv[1]) if len(sys.argv) > 1 else 1000

def hop(url):
    r = subprocess.run(["curl", "-s", "-o", "/dev/null", "--max-time", "10", "-A", UA,
                        "-w", "%{http_code}\t%{redirect_url}\t%{time_total}", url],
                       capture_output=True, text=True)
    code, loc, t = (r.stdout.split("\t") + ["", "", "0"])[:3]
    return int(code or 0), loc, float(t or 0), r.returncode

def chain(start):
    hops, url, seen = [], start, set()
    for _ in range(15):
        code, loc, t, rc = hop(url)
        hops.append({"url": url, "code": code, "t": round(t, 3), "curl_rc": rc})
        if code in (301, 302, 303, 307, 308) and loc:
            nxt = urljoin(url, loc)
            if nxt in seen:
                return {"start": start, "hops": hops, "end": "loop"}
            seen.add(url); url = nxt
            continue
        return {"start": start, "hops": hops, "end": "ok" if 200 <= code < 300 else ("error" if code else "unreachable")}
    return {"start": start, "hops": hops, "end": "too_many"}

def domain(d):
    return {"domain": d, "variants": {v: chain(f"{v}{d}/") for v in
            ("http://", "http://www.", "https://", "https://www.")}}

rows = [r[1] for r in csv.reader(open("top-1m.csv")) if int(r[0]) <= 100_000]
sample = random.Random(20261004).sample(rows, N)
t0 = time.time()
with ThreadPoolExecutor(32) as ex, open("chains.jsonl", "w") as out:
    for i, res in enumerate(ex.map(domain, sample), 1):
        out.write(json.dumps(res) + "\n")
        if i % 100 == 0: print(i, round(time.time() - t0), flush=True)
print("done", N, round(time.time() - t0))
