"""Canonical vs redirect: do the two signals agree on popular sites?

Input: the shared November 2026 crawl (.work/research/crawl-500-2026-11/raw/domains.jsonl), which already holds
for every reachable site the four homepage address variants with their redirect hops, the homepage and two
subpages with rel=canonical and the status of the canonical target (fetched without following redirects),
and 20 sampled sitemap URLs.

On top of that this script makes its own follow-up requests (plain HTTP, no JavaScript):
  1. every homepage variant that answered 200 on a different URL than the main homepage (a duplicate the
     redirects left alive) is fetched again and its rel=canonical is read: does it point at the main version?
  2. every canonical target that redirected or failed in the crawl is fetched again, following redirects,
     to confirm the problem is still there and to record where the redirect ends.

Output (private, research/raw/): followup.jsonl, rows.json. Public anonymised files are written by anonymize.py.
Run: ../../research/crawl-500-2026-11/.venv/bin/python scripts/measure.py
"""
import concurrent.futures as cf
import csv, json, pathlib, re, time
from urllib.parse import urljoin, urlsplit

import requests

HERE = pathlib.Path(__file__).resolve().parent.parent
CRAWL = HERE.parent.parent / 'research' / 'crawl-500-2026-11'
RAW = HERE / 'research' / 'raw'
UA = 'CometWebResearch/1.0 (+https://cometweb.io)'
REDIR = (301, 302, 303, 307, 308)


def norm(u):
    p = urlsplit(u or '')
    path = p.path or '/'
    return f"{p.scheme}://{(p.hostname or '').lower()}{path}{('?' + p.query) if p.query else ''}"


def loose(u):
    """same as norm, but a trailing slash does not count"""
    n = norm(u)
    return n[:-1] if n.endswith('/') and n.count('/') > 3 else n


def host(u):
    return (urlsplit(u or '').hostname or '').lower()


def bare(h):
    return re.sub(r'^www\.', '', h or '')


def relation(canon, page):
    """How a canonical URL differs from the URL it sits on."""
    if norm(canon) == norm(page):
        return 'self'
    if loose(canon) == loose(page):
        return 'trailing_slash'
    a, b = urlsplit(canon), urlsplit(page)
    same_path = (a.path or '/') == (b.path or '/') and a.query == b.query
    if bare(host(canon)) != bare(host(page)):
        return 'other_domain' if not (host(canon).endswith('.' + bare(host(page))) or host(page).endswith('.' + bare(host(canon)))) else 'other_subdomain'
    if same_path and a.scheme != b.scheme and host(canon) == host(page):
        return 'scheme_only'
    if same_path and host(canon) != host(page) and a.scheme == b.scheme:
        return 'www_only'
    if same_path:
        return 'scheme_and_www'
    return 'other_path'


SESSION = None


def session():
    s = requests.Session()
    s.headers.update({'User-Agent': UA, 'Accept': 'text/html,application/xhtml+xml;q=0.9,*/*;q=0.8',
                      'Accept-Language': 'en-US,en;q=0.9,pl;q=0.8'})
    s.max_redirects = 10
    return s


def chain(sess, url, read_body=False):
    out = {'url': url, 'hops': [], 'status': None, 'final': None, 'error': None, 'canonical': None}
    cur = url
    try:
        for _ in range(10):
            r = sess.get(cur, allow_redirects=False, timeout=(6, 10), stream=True)
            loc = r.headers.get('location')
            out['hops'].append(r.status_code)
            if r.status_code in REDIR and loc:
                r.close()
                cur = urljoin(cur, loc)
                continue
            out['status'], out['final'] = r.status_code, cur
            if read_body and r.status_code == 200 and 'html' in (r.headers.get('content-type') or ''):
                body = r.raw.read(1_500_000, decode_content=True).decode('utf-8', 'replace')
                hdr = r.headers.get('link') or ''
                m = re.search(r'<([^>]+)>\s*;\s*rel="?canonical"?', hdr, re.I)
                tags = re.findall(r'<link\b[^>]*>', body[:600000], re.I)
                cans = []
                for t in tags:
                    if re.search(r'rel\s*=\s*["\']?[^"\'>]*\bcanonical\b', t, re.I):
                        h = re.search(r'href\s*=\s*["\']([^"\']*)["\']', t, re.I) or re.search(r'href\s*=\s*([^\s>]+)', t, re.I)
                        if h:
                            cans.append(urljoin(cur, h.group(1).strip()))
                out['canonical'] = cans[0] if cans else (urljoin(cur, m.group(1)) if m else None)
                out['canonical_header'] = bool(m)
                t = re.search(r'<title[^>]*>(.*?)</title>', body[:300000], re.I | re.S)
                out['title'] = re.sub(r'\s+', ' ', t.group(1)).strip()[:300] if t else None
                out['bytes'] = len(body)
                out['challenge'] = bool(re.search(r'cf-chl|challenge-platform|captcha|Just a moment', body[:20000], re.I))
            r.close()
            return out
        out['error'] = 'too_many_redirects'
    except Exception as e:  # noqa: BLE001
        out['error'] = type(e).__name__
    return out


def main():
    ids = {r['domain']: r['site_id'] for r in csv.DictReader(open(CRAWL / 'raw' / 'site_ids.csv'))}
    recs = [json.loads(l) for l in open(CRAWL / 'raw' / 'domains.jsonl')]
    recs = [r for r in recs if r.get('outcome') == 'ok' and (r.get('home') or {}).get('html')]
    rows, jobs = [], []
    for r in recs:
        sid = ids[r['domain']]
        home = r['home']
        F = home['final_url']
        row = {'site': sid, 'stratum': r['stratum'], 'domain': r['domain'], 'home_final': F,
               'home_title': (home.get('html') or {}).get('title'), 'home_bytes': home.get('bytes'), 'variants': {}, 'pages': [], 'sitemap': None}
        # 1. what the four address variants do
        for k, c in r['chains'].items():
            row['variants'][k] = {'status': c.get('status'), 'final': c.get('final_url'), 'hops': [h['status'] for h in c.get('hops') or []][:-1] if c.get('status') else [h['status'] for h in c.get('hops') or []]}
        dup_urls = sorted({norm(c['final']) for c in row['variants'].values() if c['status'] == 200 and c['final'] and loose(c['final']) != loose(F)})
        row['duplicate_variant_urls'] = dup_urls
        for u in dup_urls:
            jobs.append(('variant', sid, u))
        # 2. canonical on homepage and subpages
        plist = [('home', home)] + [(f'sub{i + 1}', s) for i, s in enumerate(r.get('subpages') or []) if s.get('html')]
        for name, p in plist:
            h = p.get('html') or {}
            cans = h.get('canonicals') or []
            page = p['final_url']
            pr = {'page': name, 'url': page, 'redirected_here': len(p.get('hops') or []) > 1, 'n_canonicals': len(cans),
                  'distinct_canonicals': len({c.strip() for c in cans})}
            if cans:
                c = p.get('canonical_abs') or urljoin(page, cans[0])
                t = p.get('canonical_target') or {}
                pr.update({'canonical': c, 'relation': relation(c, page), 'relative': p.get('canonical_relative'),
                           'target_status': t.get('status'), 'target_location': t.get('location'),
                           'target_self': bool(t.get('self'))})
                if pr['relation'] != 'self' and (t.get('status') in REDIR or (t.get('status') or 0) >= 400 or t.get('error')):
                    jobs.append(('target', sid, c))
            rows_p = pr
            row['pages'].append(rows_p)
        # 3. sitemap sample
        sm = (r.get('sitemap') or {}).get('sample') or []
        if sm:
            row['sitemap'] = {'n': len(sm), 'redirect': sum(1 for x in sm if (x.get('hops') or 0) > 0),
                              'not_200': sum(1 for x in sm if x.get('status') != 200),
                              'canonical_elsewhere': sum(1 for x in sm if x.get('status') == 200 and x.get('canonical_self') is False)}
        rows.append(row)

    print(f'{len(rows)} sites, {len(jobs)} follow-up requests')
    out = {}
    with cf.ThreadPoolExecutor(8) as ex:
        def run(job):
            kind, sid, url = job
            s = session()
            res = chain(s, url, read_body=(kind == 'variant'))
            time.sleep(0.2)
            return job, res
        for job, res in ex.map(run, jobs):
            out[(job[0], job[1], job[2])] = res
    RAW.mkdir(parents=True, exist_ok=True)
    with open(RAW / 'followup.jsonl', 'w') as f:
        for (kind, sid, url), res in out.items():
            f.write(json.dumps({'kind': kind, 'site': sid, 'checked': time.strftime('%Y-%m-%d'), **res}) + '\n')
    for row in rows:
        row['duplicate_variants'] = [{'url': u, **out[('variant', row['site'], u)]} for u in row['duplicate_variant_urls']]
        for p in row['pages']:
            c = p.get('canonical')
            if c and ('target', row['site'], c) in out:
                p['recheck'] = out[('target', row['site'], c)]
    json.dump(rows, open(RAW / 'rows.json', 'w'), indent=1)


if __name__ == '__main__':
    main()
