"""Launch hygiene check on homepages of popular sites, November 2026 run.

Same sample and checks as the October run (../measure.py), with three changes:
  * an honest research User-Agent instead of a desktop Chrome string,
  * 8 parallel workers (one curl each) instead of 10,
  * two launch-leftover checks: rel=canonical (missing, other host, http) and absolute
    links in the homepage HTML that point at localhost, private TLDs or staging/dev hosts.


Sample: Tranco list 94GG2 (tranco-list.eu), ranks 1-100 000, random.Random(20261006).
Domains are processed in sample order, in batches of 20, until 100 of them serve a
homepage (HTTP 200, HTML, not a bot challenge). Every request is one curl call with a
desktop Chrome user agent and a 12 s timeout. No logins, no forms.

For each serving site the script records:
  noindex      meta robots / googlebot noindex in the homepage HTML, or X-Robots-Tag noindex
  robots       robots.txt status, "Disallow: /" for User-agent: * (or Googlebot), Sitemap: lines
  sitemap      the first sitemap from robots.txt, else /sitemap.xml, else /sitemap_index.xml
               counts only when it answers 200 with <urlset> or <sitemapindex> (gzip allowed)
  soft404      a made-up URL (/cw-launch-check-<random>/) followed to the end; 200 = soft 404
  favicon      <link rel=icon> target or /favicon.ico answering 200 with an image or ico body
  title        <title> missing, empty, or a known default ("Home", "React App", ...)
  https        http://<final host>/ followed to the end; still on http:// = no HTTPS redirect

Output: results.jsonl (one line per domain tried, serving or not).
"""
import csv, gzip, html, json, os, random, re, secrets, subprocess, sys, tempfile, time
from concurrent.futures import ThreadPoolExecutor
from urllib.parse import urljoin, urlsplit

UA = "CometWebResearch/1.0 (+https://cometweb.io)"
TARGET = int(sys.argv[1]) if len(sys.argv) > 1 and sys.argv[1].isdigit() else 100
SEED = 20261006
DEFAULT_TITLES = {
    "home", "homepage", "home page", "untitled", "untitled document", "document", "welcome",
    "index", "index.html", "my site", "my website", "site title", "website", "new page",
    "react app", "vite app", "vite + react", "vite + react + ts", "create next app",
    "my wordpress blog", "my blog", "coming soon", "under construction", "test", "default page",
    "apache2 ubuntu default page: it works", "welcome to nginx!", "welcome to openresty!", "it works!", "page title",
}
CHALLENGE = re.compile(r"just a moment|cf-chl|challenge-platform|attention required|access denied|"
                       r"captcha|are you a robot|request unsuccessful|incapsula|perimeterx|ddos-guard",
                       re.I)


def fetch(url, follow=True, max_bytes=3_000_000):
    """One curl call. Returns dict(code, final_url, ctype, headers(last response), body bytes)."""
    with tempfile.NamedTemporaryFile(delete=False) as hf, tempfile.NamedTemporaryFile(delete=False) as bf:
        hpath, bpath = hf.name, bf.name
    args = ["curl", "-s", "--compressed", "--max-time", "12", "-A", UA,
            "-H", "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
            "-H", "Accept-Language: en-US,en;q=0.9",
            "--max-filesize", str(max_bytes), "-D", hpath, "-o", bpath,
            "-w", "%{http_code}\t%{url_effective}\t%{content_type}\t%{num_redirects}"]
    if follow:
        args += ["-L", "--max-redirs", "10"]
    r = subprocess.run(args + [url], capture_output=True, text=True)
    code, final, ctype, nred = (r.stdout.split("\t") + ["0", url, "", "0"])[:4]
    raw_headers = open(hpath, "rb").read().decode("latin-1", "replace")
    body = open(bpath, "rb").read()
    os.unlink(hpath); os.unlink(bpath)
    last = raw_headers.strip().split("\r\n\r\n")[-1] if raw_headers.strip() else ""
    headers = {}
    for line in last.split("\r\n")[1:]:
        if ":" in line:
            k, v = line.split(":", 1)
            headers.setdefault(k.strip().lower(), []).append(v.strip())
    return {"code": int(code or 0), "final": final, "ctype": ctype.lower(), "redirects": int(nred or 0),
            "headers": headers, "body": body, "curl_rc": r.returncode}


def text(body):
    return body.decode("utf-8", "replace")


def meta_robots_noindex(page):
    for m in re.finditer(r"<meta\b[^>]*>", page, re.I):
        tag = m.group(0)
        name = re.search(r"name\s*=\s*[\"']?([^\"'\s>]+)", tag, re.I)
        content = re.search(r"content\s*=\s*[\"']([^\"']*)[\"']", tag, re.I)
        if name and content and name.group(1).lower() in ("robots", "googlebot") and "noindex" in content.group(1).lower():
            return name.group(1).lower() + ": " + content.group(1)
    return None


def title_of(page):
    m = re.search(r"<title\b[^>]*>(.*?)</title>", page, re.I | re.S)
    if not m:
        return None
    return re.sub(r"\s+", " ", html.unescape(m.group(1))).strip()


def icon_hrefs(page):
    out = []
    for m in re.finditer(r"<link\b[^>]*>", page, re.I):
        tag = m.group(0)
        rel = re.search(r"rel\s*=\s*[\"']?([^\"'>]+)", tag, re.I)
        href = re.search(r"href\s*=\s*[\"']?([^\"'\s>]+)", tag, re.I)
        if rel and href and "icon" in rel.group(1).lower().split():
            out.append(html.unescape(href.group(1)))
    return out


def robots_info(body):
    """Groups per RFC 9309: consecutive User-agent lines share the rules that follow.
    disallow_all = the group Googlebot obeys (a googlebot group if one exists, else *)
    has "Disallow: /" and no "Allow: /". star_disallow_all = the same test on the * group."""
    lines = [l.split("#", 1)[0].strip() for l in text(body).splitlines()]
    sitemaps, groups, agents, rules, last_was_agent = [], [], [], [], False
    for l in lines:
        if ":" not in l:
            continue
        k, v = [x.strip() for x in l.split(":", 1)]
        k = k.lower()
        if k == "sitemap":
            sitemaps.append(v)
            continue
        if k == "user-agent":
            if not last_was_agent and agents:
                groups.append((agents, rules)); agents, rules = [], []
            agents.append(v.lower()); last_was_agent = True
            continue
        last_was_agent = False
        if k in ("disallow", "allow"):
            rules.append((k, v))
    if agents:
        groups.append((agents, rules))

    def blocks(name):
        rl = [r for ag, rs in groups if name in ag for r in rs]
        dis = [v for k, v in rl if k == "disallow"]
        alw = [v for k, v in rl if k == "allow" and v in ("/", "/$")]
        return "/" in dis and not alw

    has_google_group = any("googlebot" in ag for ag, _ in groups)
    return {"sitemaps": sitemaps,
            "disallow_all": blocks("googlebot") if has_google_group else blocks("*"),
            "star_disallow_all": blocks("*")}


def is_sitemap(res):
    if res["code"] != 200:
        return False
    b = res["body"]
    if b[:2] == b"\x1f\x8b":
        try:
            b = gzip.decompress(b)
        except Exception:
            return False
    head = b[:5000].decode("utf-8", "replace").lower()
    return "<urlset" in head or "<sitemapindex" in head


STAGING_LABELS = {"staging", "stage", "stg", "dev", "develop", "development", "test", "testing", "uat",
                  "preprod", "pre-prod", "preview", "qa", "sandbox", "beta", "demo", "local"}
PRIVATE_TLDS = {"local", "localhost", "test", "internal", "lan", "invalid", "example"}
ABS_URL = re.compile(r"""(?:href|src|content|action|data-src)\s*=\s*["']\s*((?:https?:)?//([a-z0-9.-]+)(?::\d+)?[^"'\s>]*)""", re.I)


def canonical_of(page):
    for m in re.finditer(r"<link\b[^>]*>", page, re.I):
        tag = m.group(0)
        rel = re.search(r"rel\s*=\s*[\"']?([^\"'>]+)", tag, re.I)
        href = re.search(r"href\s*=\s*[\"']?([^\"'\s>]+)", tag, re.I)
        if rel and href and "canonical" in rel.group(1).lower().split():
            return html.unescape(href.group(1))
    return None


def staging_hosts(page, own_host):
    """Hosts in absolute URLs that look like a dev or staging environment. A label counts only
    below the registrable part (so dev.to or test.com do not count), split on '-' too."""
    own = own_host.lower().split(":")[0]
    out = set()
    for m in ABS_URL.finditer(page):
        h = m.group(2).lower().strip(".")
        if not h or h == own:
            continue
        if h in ("localhost", "127.0.0.1", "0.0.0.0") or h.startswith("192.168.") or h.startswith("10."):
            out.add(h); continue
        labels = h.split(".")
        if labels[-1] in PRIVATE_TLDS:
            out.add(h); continue
        sub = labels[:-2]
        for lab in sub:
            parts = set(lab.split("-")) | {lab}
            if parts & STAGING_LABELS:
                out.add(h); break
    return sorted(out)


def check(domain):
    rec = {"domain": domain}
    home = None
    for start in (f"https://{domain}/", f"https://www.{domain}/"):
        home = fetch(start)
        if home["code"] == 200:
            break
    page = text(home["body"])
    rec["home_code"] = home["code"]
    rec["home_final"] = home["final"]
    if home["code"] != 200 or "html" not in home["ctype"] or len(home["body"]) < 200:
        rec["serving"] = False; rec["why"] = "no 200 html homepage"
        return rec
    if CHALLENGE.search(page[:20000]) and len(page) < 60000:
        rec["serving"] = False; rec["why"] = "bot challenge page"
        return rec
    rec["serving"] = True
    parts = urlsplit(home["final"])
    origin = f"{parts.scheme}://{parts.netloc}"
    host = parts.netloc

    # noindex
    xr = " ".join(home["headers"].get("x-robots-tag", []))
    rec["noindex_meta"] = meta_robots_noindex(page)
    rec["noindex_header"] = xr if "noindex" in xr.lower() else None

    # title
    t = title_of(page)
    rec["title"] = t
    rec["title_missing"] = not t
    rec["title_default"] = bool(t) and (t.lower() in DEFAULT_TITLES or "just another wordpress site" in t.lower())

    # canonical and staging leftovers
    can = canonical_of(page)
    rec["canonical"] = can
    if can:
        cabs = urljoin(home["final"], can)
        cp = urlsplit(cabs)
        strip = lambda x: x.lower().split(":")[0].removeprefix("www.")
        rec["canonical_other_host"] = strip(cp.netloc) != strip(host)
        rec["canonical_www_mismatch"] = (not rec["canonical_other_host"]) and cp.netloc.lower() != host.lower()
        rec["canonical_http"] = cp.scheme == "http" and parts.scheme == "https"
    else:
        rec["canonical_other_host"] = rec["canonical_www_mismatch"] = rec["canonical_http"] = False
    rec["staging_hosts"] = staging_hosts(page, host)[:10]

    # robots.txt
    rb = fetch(origin + "/robots.txt")
    rec["robots_code"] = rb["code"]
    ri = robots_info(rb["body"]) if rb["code"] == 200 and "html" not in rb["ctype"] else {"sitemaps": [], "disallow_all": False}
    rec["robots_disallow_all"] = ri["disallow_all"]
    rec["robots_star_disallow_all"] = ri.get("star_disallow_all", False)
    rec["robots_sitemaps"] = ri["sitemaps"][:5]
    rec["sitemap_in_robots"] = bool(ri["sitemaps"])

    # sitemap
    rec["sitemap_ok"] = False; rec["sitemap_url"] = None
    candidates = ri["sitemaps"][:1] or [origin + "/sitemap.xml", origin + "/sitemap_index.xml"]
    for u in candidates:
        sm = fetch(urljoin(origin + "/", u), max_bytes=20_000_000)
        if is_sitemap(sm):
            rec["sitemap_ok"] = True; rec["sitemap_url"] = u
            break
    rec["sitemap_listed_but_broken"] = rec["sitemap_in_robots"] and not rec["sitemap_ok"]

    # soft 404
    probe = f"{origin}/cw-launch-check-{secrets.token_hex(6)}/"
    p = fetch(probe)
    rec["probe_code"] = p["code"]
    rec["probe_final"] = p["final"]
    rec["soft404"] = p["code"] == 200
    rec["probe_to_home"] = p["code"] == 200 and urlsplit(p["final"]).path in ("", "/")

    # favicon
    hrefs = icon_hrefs(page)
    rec["icon_links"] = hrefs[:3]
    fav_ok = False; fav_src = None
    tried = [urljoin(home["final"], h) for h in hrefs[:1] if not h.startswith("data:")]
    if hrefs and hrefs[0].startswith("data:") and len(hrefs[0]) > 20:
        fav_ok, fav_src = True, "data-uri"
    tried = [urljoin(home["final"], h) for h in hrefs if not h.startswith("data:")][:4]
    for u in list(dict.fromkeys(tried + ([origin + "/favicon.ico"] if not fav_ok else []))):
        if fav_ok:
            break
        f = fetch(u, max_bytes=2_000_000)
        if f["code"] == 200 and len(f["body"]) > 0 and ("image" in f["ctype"] or "icon" in f["ctype"]
                                                          or f["body"][:4] in (b"\x00\x00\x01\x00", b"\x89PNG")
                                                          or b"<svg" in f["body"][:500]):
            fav_ok, fav_src = True, u
    rec["favicon_ok"] = fav_ok
    rec["favicon_src"] = fav_src

    # http -> https
    h = fetch(f"http://{host}/")
    rec["http_code"] = h["code"]
    rec["http_final"] = h["final"]
    rec["http_stays_http"] = h["code"] == 200 and h["final"].startswith("http://")
    rec["http_unreachable"] = h["code"] == 0
    return rec


def main():
    rows = [r[1] for r in csv.reader(open("top-1m.csv")) if int(r[0]) <= 100_000]
    sample = random.Random(SEED).sample(rows, 400)
    out = open("results.jsonl", "w")
    serving, i, t0 = 0, 0, time.time()
    with ThreadPoolExecutor(8) as ex:
        while serving < TARGET and i < len(sample):
            batch = sample[i:i + 20]; i += len(batch)
            for res in ex.map(check, batch):
                res["sample_index"] = sample.index(res["domain"])
                out.write(json.dumps(res) + "\n"); out.flush()
                serving += res["serving"]
            print(i, "tried", serving, "serving", round(time.time() - t0), "s", flush=True)
    print("done", i, serving)


if __name__ == "__main__":
    main()
