"""titus_scraper: study a hashtag, topic or public account across public posts and news.

It collects through official APIs, publisher feeds and sitemaps from the sources approved in the
study's sources.csv, keeps a request log (raw responses only with --keep-raw), cleans the text, audits data quality, runs the analysis with intervals and robustness
checks, supports two-coder validation, and builds one PDF that holds the blog post and the report.

Commands (run `python titus_scraper.py <command> -h` for options):
  init        write the protocol and source registry templates for a new study
  check       which sources your keys unlock
  collect     search a hashtag, topic or account on the sources you name
  fetch-text  fill in article text for the news domains approved in sources.csv (robots.txt, paywall and terms checks)
  audit       clean the data and write the data-quality report, before any model runs
  analyze     clean, filter, and run every analysis
  digest      write the reading packet: news and posts to read before the numbers
  sample      draw a validation sample for two coders (sentiment, stance, emotion, relevance)
  agree       measure agreement between the two coders and write the adjudication sheet
  score       compare the model with the settled labels and correct the shares
  purge       delete stored items (YouTube's 30-day rule, or a deletion request)
  compare     compare two to four topics, each analysed in its own run folder
  report      build the PDF (blog post plus analysis report, or a comparison)
  selftest    offline test on synthetic data, ends with a sample PDF
"""
from __future__ import annotations

import argparse
import csv
import gzip
import hashlib
import html
import ipaddress
import itertools
import json
import logging
import math
import os
import platform as _platform
import random
import re
import socket
import time
import sys
import threading
import unicodedata
import urllib.parse
import zlib
from collections import Counter
from dataclasses import asdict, dataclass, field
from datetime import datetime, timedelta, timezone
from pathlib import Path

import pandas as pd

log = logging.getLogger("titus_scraper")
VERSION = "2.4.0"
CONTACT_ENV = "TITUS_SCRAPER_CONTACT"


def user_agent() -> str:
    """An honest User-Agent. Sites can reach you when TITUS_SCRAPER_CONTACT holds an email or URL."""
    contact = os.environ.get(CONTACT_ENV, "").strip()
    return f"titus-scraper/{VERSION} (public-data research" + (f"; contact: {contact}" if contact else "") + ")"


# --------------------------------------------------------------------------- schema and storage

COLUMNS = ["platform", "post_id", "url", "author_handle", "author_id", "author_name", "created_at", "text", "kind",
           "parent_id", "like_count", "reply_count", "share_count", "view_count", "query_type",
           "query_value", "source_endpoint", "media_urls", "fulltext_status", "collected_at"]


@dataclass
class Post:
    platform: str             # bluesky, mastodon, youtube, reddit, threads, instagram, news, nytimes, web ...
    post_id: str
    text: str
    created_at: str           # ISO 8601 UTC
    url: str = ""
    author_handle: str = ""   # can change over time
    author_id: str = ""       # the platform's permanent id (Bluesky DID, YouTube channel id, Mastodon acct URI)
    author_name: str = ""
    kind: str = "post"        # post, comment (a reply), repost, headline, summary, article
    parent_id: str = ""       # the post replied to, or the original of a repost
    like_count: int | None = None
    reply_count: int | None = None
    share_count: int | None = None
    view_count: int | None = None
    query_type: str = ""      # hashtag, topic, user
    query_value: str = ""
    source_endpoint: str = ""
    media_urls: list = field(default_factory=list)
    fulltext_status: str = ""  # news only: api, feed, summary, metadata-only, fetched, blocked:<reason>
    collected_at: str = field(default_factory=lambda: datetime.now(timezone.utc).isoformat())

    def row(self) -> dict:
        d = asdict(self)
        d["media_urls"] = json.dumps(self.media_urls)
        return d


def to_utc_iso(value) -> str:
    if value is None or value == "":
        return ""
    if isinstance(value, (int, float)):
        return datetime.fromtimestamp(value, tz=timezone.utc).isoformat()
    dt = value if isinstance(value, datetime) else datetime.fromisoformat(str(value).replace("Z", "+00:00"))
    if dt.tzinfo is None:
        dt = dt.replace(tzinfo=timezone.utc)
    return dt.astimezone(timezone.utc).isoformat()


def stable_id(*parts: str) -> str:
    return hashlib.sha1("|".join(parts).encode("utf-8")).hexdigest()[:16]


def in_window(p: Post, since: str | None, until: str | None) -> bool:
    return (not since or p.created_at >= since) and (not until or p.created_at < until)


def save_posts(posts: list[Post], data_dir, tag: str) -> Path | None:
    if not posts:
        return None
    out = Path(data_dir) / "raw"
    out.mkdir(parents=True, exist_ok=True)
    path = out / f"{tag}_{datetime.now(timezone.utc):%Y%m%dT%H%M%S}.parquet"
    pd.DataFrame([p.row() for p in posts], columns=COLUMNS).to_parquet(path, index=False)
    return path


def load_posts(data_dir) -> pd.DataFrame:
    expire_youtube(data_dir)
    enforce_retention(data_dir)
    files = sorted((Path(data_dir) / "raw").glob("*.parquet"))
    if not files:
        return pd.DataFrame(columns=COLUMNS)
    df = pd.concat([pd.read_parquet(f) for f in files], ignore_index=True)
    df = df.reindex(columns=list(dict.fromkeys(COLUMNS + list(df.columns))))   # files from older versions
    for c in ("author_id", "fulltext_status", "parent_id", "author_name", "author_handle", "url"):
        df[c] = df[c].astype("object").fillna("")
    # the same post collected twice (a rerun, or fetch-text filling in an article): keep the newest copy
    df = df.sort_values("collected_at", kind="stable").drop_duplicates(["platform", "post_id"], keep="last")
    df = df.reset_index(drop=True)
    df["created_at"] = pd.to_datetime(df["created_at"], utc=True, errors="coerce", format="ISO8601")
    return df

# --------------------------------------------------------------------------- query expansion and matching


def split_camel(tag: str) -> list[str]:
    tag = tag.lstrip("#")
    return re.findall(r"[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+|\d+", tag) or [tag]


@dataclass
class Query:
    """The query dictionary. Exact hashtags, textual phrases and counter-tags are kept apart, so each
    post records how it matched (match_type) and results can be reported for each kind of match."""
    kind: str                                   # hashtag, topic, user
    value: str                                   # for hashtags, several spellings may be given: "#MAGA,#MakeAmericaGreatAgain"
    aliases: list = field(default_factory=list)  # extra '#tags' or phrases the user chose
    exclude: list = field(default_factory=list)  # phrases that mark a false match
    counter: list = field(default_factory=list)  # opposing '#tags' or phrases, reported separately

    def given_tags(self) -> list[str]:
        """Every hashtag spelling the user gave, as typed: the --value list (for a hashtag query) and '#' aliases."""
        vals = [v.strip() for v in re.split(r"[,\s]+", self.value) if v.strip()] if self.kind == "hashtag" else []
        return [v if v.startswith("#") else f"#{v}" for v in vals] + [a for a in self.aliases if a.startswith("#")]

    def hashtags(self) -> list[str]:
        """Search tags, lower case. Hashtag search and matching ignore case on every source, so #MAGA,
        #maga and #Maga are one tag. A misspelling such as #MakeAmericanGreatAgain is its own tag."""
        if self.kind == "topic":
            base = {"".join(w.capitalize() for w in re.findall(r"\w+", self.value)).lower()}
        elif self.kind == "hashtag":
            base = set()
        else:
            return []
        return sorted(base | {t.lstrip("#").lower() for t in self.given_tags()})

    def spellings(self) -> dict:
        """Search tag -> the spellings the user gave for it (shows which ones were merged)."""
        out: dict = {}
        for t in self.given_tags():
            out.setdefault(t.lstrip("#").lower(), [])
            if t not in out[t.lstrip("#").lower()]:
                out[t.lstrip("#").lower()].append(t)
        return out

    def phrases(self) -> list[str]:
        """Phrases for text without the tag: each CamelCase tag split into words (#MakeAmericaGreatAgain
        gives 'make america great again'), the topic sentence, and phrase aliases. An all-lower or
        all-capital tag can't be split, so give one CamelCase spelling for the phrase to exist."""
        if self.kind == "hashtag":
            out = set()
            for t in self.given_tags():
                words = split_camel(t)
                if len(words) > 1:
                    out.add(" ".join(w.lower() for w in words))
        elif self.kind == "topic":
            out = {" ".join(re.findall(r"\w+", self.value.lower()))}
        else:
            return []
        return sorted(out | {a.lower() for a in self.aliases if not a.startswith("#")})

    def label(self) -> str:
        """A short name for titles: the first tag as typed, or the topic sentence."""
        if self.kind == "hashtag" and self.given_tags():
            return self.given_tags()[0]
        return self.value

    def counter_tags(self) -> list[str]:
        return sorted({c.lstrip("#").lower() for c in self.counter if c.startswith("#")})

    def counter_phrases(self) -> list[str]:
        return sorted({c.lower() for c in self.counter if not c.startswith("#")})

    def search_strings(self, with_counter=True) -> list[str]:
        out = [f"#{t}" for t in self.hashtags()] + [f'"{p}"' for p in self.phrases()]
        if with_counter:
            out += [f"#{t}" for t in self.counter_tags()] + [f'"{p}"' for p in self.counter_phrases()]
        return out

    def variant_table(self) -> list[dict]:
        sp = self.spellings()
        rows = [{"variant": f"#{t}" + (f" (given as {', '.join(sp[t])})" if sp.get(t) and sp[t] != [f"#{t}"] else ""),
                 "match_type": "hashtag", "role": "main"} for t in self.hashtags()]
        rows += [{"variant": p, "match_type": "phrase", "role": "main"} for p in self.phrases()]
        rows += [{"variant": f"#{t}", "match_type": "counter", "role": "counter"} for t in self.counter_tags()]
        rows += [{"variant": p, "match_type": "counter", "role": "counter"} for p in self.counter_phrases()]
        rows += [{"variant": x, "match_type": "exclude", "role": "false match"} for x in self.exclude]
        return rows

    @staticmethod
    def _tag_in(t, low):
        return re.search(rf"(?<![\w#])#{re.escape(t)}(?!\w)", low)

    @staticmethod
    def _phrase_in(p, squashed):
        return re.search(rf"\b{re.escape(p)}\b", squashed)

    def match(self, text: str) -> tuple[str, str]:
        """(match_type, rule): hashtag, phrase or counter, and the variant that matched. ('', '') is off-topic."""
        low = (text or "").lower()
        if any(x.lower() in low for x in self.exclude):
            return "", ""
        squashed = re.sub(r"\s+", " ", re.sub(r"[^a-z0-9 ]+", " ", low))
        for t in self.hashtags():
            if self._tag_in(t, low):
                return "hashtag", f"#{t}"
        for p in self.phrases():
            if self._phrase_in(p, squashed):
                return "phrase", p
        for t in self.counter_tags():
            if self._tag_in(t, low):
                return "counter", f"#{t}"
        for p in self.counter_phrases():
            if self._phrase_in(p, squashed):
                return "counter", p
        return "", ""

    def matches(self, text: str) -> str:
        """The rule that matched ('#tag' or the phrase), or '' when the post is off-topic."""
        return self.match(text)[1]

# --------------------------------------------------------------------------- HTTP and collectors


SECRET_PARAMS = {"key", "api-key", "api_key", "apikey", "access_token", "token", "password", "client_secret"}
RATE_HEADERS = ("retry-after", "x-ratelimit-limit", "x-ratelimit-remaining", "x-ratelimit-reset", "ratelimit-remaining",
                "ratelimit-reset", "x-ratelimit-used")


class HTTPError(Exception):
    def __init__(self, status: int, url: str, body: str = ""):
        super().__init__(f"HTTP {status} from {redact(url)}: {body[:200]}")
        self.status, self.url, self.body = status, url, body


class Blocked(HTTPError):
    """A request the skill refused to send: the site is blocked (SITE_RULES) or robots.txt disallows the URL."""

    def __init__(self, url: str, why: str, kind: str = "policy"):
        Exception.__init__(self, f"refused {redact(url)}: {why}")
        self.status, self.url, self.body, self.why, self.kind = 0, url, why, why, kind


# Sites the skill never reads, or reads only for headlines, whatever the study. Every collector sends its
# requests through Http, and Http checks this table before each request and after each redirect.
# Each entry gives the level, the reason and the date of the review that added it.
#   block      no request at all, not even robots.txt
#   headlines  titles and short summaries from feeds and sitemaps only: never the article page, never full feed text
#   api        the official API host of a blocked site. It stays open under the API's own terms
# Never relax an entry without reading the site's current terms, and record the date you read them.
SITE_RULES = {
    "news.google.com": ("block", "Google News: its robots.txt disallows the /rss/ feeds and Google's terms bar automated queries", "2026-12-03"),
    "reuters.com": ("block", "Reuters' terms restrict automated collection and text and data mining", "2026-12-03"),
    "apnews.com": ("block", "AP's terms restrict automated collection and text and data mining", "2026-12-03"),
    "bbc.co.uk": ("block", "The BBC's terms restrict automated collection and text and data mining", "2026-12-03"),
    "bbc.com": ("block", "The BBC's terms restrict automated collection and text and data mining", "2026-12-03"),
    "bbci.co.uk": ("block", "BBC feeds: the BBC's terms restrict automated collection and text and data mining", "2026-12-03"),
    "aljazeera.com": ("block", "Al Jazeera's terms restrict automated collection and reuse of its content", "2026-12-03"),
    "nytimes.com": ("block", "NYT's terms bar collecting its pages and feeds by automated means. Use the NYT APIs instead", "2026-12-03"),
    "api.nytimes.com": ("api", "NYT's official APIs, used under the NYT API terms", "2026-12-03"),
    "theguardian.com": ("block", "The Guardian's terms restrict text and data mining of its site and feeds", "2026-12-03"),
    "medium.com": ("headlines", "Medium's terms restrict scraping and text mining of stories", "2026-12-03"),
    "ghanaweb.com": ("headlines", "GhanaWeb's terms restrict copying its content", "2026-12-03"),
    "myjoyonline.com": ("headlines", "MyJoyOnline's terms forbid reproducing or copying its content", "2026-12-03"),
}
SUMMARY_WORDS = 50          # most words kept from a feed item of a headlines-only site
ROBOTS_SOURCES = {"feeds", "sitemaps", "news", "blogs", "fetch-text", "transcribe"}   # sources that read websites, not APIs
REDIRECTS = (301, 302, 303, 307, 308)
MAX_REDIRECTS = 5


def site_rule(url_or_domain: str):
    """The SITE_RULES entry for a URL or domain as (domain, level, reason, date), or None. The most specific
    entry wins, so api.nytimes.com stays open while nytimes.com is blocked."""
    d = domain_of(url_or_domain) if "://" in (url_or_domain or "") else (url_or_domain or "").lower().removeprefix("www.")
    best = None
    for key, (level, why, when) in SITE_RULES.items():
        if (d == key or d.endswith("." + key)) and (best is None or len(key) > len(best[0])):
            best = (key, level, why, when)
    return best


def policy_refusal(url: str, source: str = "") -> str:
    """Why the skill must not request this URL for this source, or '' when SITE_RULES allows it."""
    rule = site_rule(url)
    if not rule or rule[1] == "api":
        return ""
    if rule[1] == "block":
        return f"{rule[0]} is blocked: {rule[2]}"
    if rule[1] == "headlines" and source in ("fetch-text", "transcribe"):
        return f"{rule[0]} is headlines only: {rule[2]}"
    return ""


def redact(url: str) -> str:
    """The URL with API keys and tokens replaced, so logs and the PDF never hold a secret."""
    parts = urllib.parse.urlsplit(url)
    q = [(k, "REDACTED" if k.lower() in SECRET_PARAMS else v) for k, v in urllib.parse.parse_qsl(parts.query, keep_blank_values=True)]
    return urllib.parse.urlunsplit(parts._replace(query=urllib.parse.urlencode(q)))


MAX_RETRY_WAIT = 300        # seconds. A source that asks for a longer wait is left for the rest of the run
SITE_BUDGET = 2000          # most requests to one host in one run, unless --max-requests-per-site says otherwise
# Daily limits that sources state. Http counts each call for the day (UTC) in a usage file shared by every
# run folder, because the limit belongs to the key, and stops the source when the count reaches the limit.
DAILY_LIMITS = {"nytimes": 500, "guardian": 500, "youtube": 10000, "youtube-search": 100}
USAGE_ENV = "TITUS_SCRAPER_USAGE"


def retry_after_seconds(value, now: datetime | None = None) -> float | None:
    """Retry-After in seconds. RFC 9110 allows a number of seconds or an HTTP date. None when absent or unreadable."""
    v = str(value or "").strip()
    if not v:
        return None
    try:
        return max(0.0, float(v))
    except ValueError:
        pass
    from email.utils import parsedate_to_datetime
    try:
        when = parsedate_to_datetime(v)
    except (TypeError, ValueError, IndexError):
        return None
    if when is None:
        return None
    if when.tzinfo is None:
        when = when.replace(tzinfo=timezone.utc)
    return max(0.0, (when - (now or datetime.now(timezone.utc))).total_seconds())


def private_address(host: str, resolve: bool = True) -> str:
    """The private, loopback, link-local or reserved address this host is or resolves to, or ''. The skill
    reads public material only, so it never sends a request to a local network or to this computer."""
    h = (host or "").split("@")[-1]
    h = h[1:].split("]")[0] if h.startswith("[") else h.rsplit(":", 1)[0] if h.count(":") == 1 else h
    if not h:
        return ""
    if h.lower() in ("localhost", "localhost.localdomain") or h.lower().endswith((".localhost", ".local", ".internal")):
        return h
    try:
        addrs = [ipaddress.ip_address(h)]
    except ValueError:
        if not resolve:
            return ""
        try:
            addrs = [ipaddress.ip_address(i[4][0].split("%")[0]) for i in socket.getaddrinfo(h, None)]
        except (socket.gaierror, UnicodeError, OSError, ValueError):
            return ""            # unknown host: the request fails on its own
    for ip in addrs:
        if ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved or ip.is_multicast or ip.is_unspecified:
            return str(ip)
    return ""


class Usage:
    """Calls per source per UTC day, kept in ~/.titus_scraper/usage.json (or the file TITUS_SCRAPER_USAGE
    names) so that runs in different folders share the count, as they share the key."""

    def __init__(self):
        self._lock = threading.Lock()

    def path(self) -> Path:
        return Path(os.environ.get(USAGE_ENV) or Path.home() / ".titus_scraper" / "usage.json")

    def _read(self) -> dict:
        try:
            return json.loads(self.path().read_text())
        except (OSError, ValueError):
            return {}

    def used(self, key: str) -> int:
        return int(self._read().get(f"{datetime.now(timezone.utc):%Y-%m-%d}", {}).get(key, 0))

    def take(self, key: str, limit: int) -> None:
        """Counts one call, or raises DailyLimit when the day's limit is already used."""
        day = f"{datetime.now(timezone.utc):%Y-%m-%d}"
        with self._lock:
            data = self._read()
            today = data.get(day, {})
            if today.get(key, 0) >= limit:
                raise DailyLimit(key, limit)
            today[key] = today.get(key, 0) + 1
            data = {day: today}          # keep today only
            p = self.path()
            try:
                p.parent.mkdir(parents=True, exist_ok=True)
                p.write_text(json.dumps(data))
            except OSError as e:
                log.warning("could not save the daily call count to %s (%s)", p, e)


class DailyLimit(HTTPError):
    """A source's daily call limit is used up. Run collect again tomorrow (UTC) into the same folder."""

    def __init__(self, key: str, limit: int):
        Exception.__init__(self, f"{key}: the daily limit of {limit} calls is used up. Run collect again after midnight UTC "
                                 "into the same folder.")
        self.status, self.url, self.body, self.key, self.limit = 0, "", str(self), key, limit


USAGE = Usage()


class Http:
    """A polite HTTP client that keeps evidence.

    - waits at least `min_interval` seconds between calls to one host (more where a source asks). Threads
      share the wait, so parallel workers never call one host faster than that
    - retries 429 and 5xx with backoff and honours Retry-After, in seconds or as a date. The wait it
      asks for applies to every thread calling that host. When a host asks for more than 5 minutes,
      the run leaves it alone for the rest of the run. Never retries 401, 402, 403, 404 or 451
    - stops calling a host for the rest of the run after two network failures in a row
    - sends at most `site_budget` requests to one host in a run
    - counts calls against the daily limits sources state (DAILY_LIMITS) and stops at them
    - never calls a private, loopback or link-local address
    - sends an honest User-Agent (see TITUS_SCRAPER_CONTACT)
    - refuses every request to a blocked site (SITE_RULES), and for sources that read websites
      (ROBOTS_SOURCES) every URL that robots.txt disallows. Both checks run again on each redirect,
      and it follows at most 5 redirects. A refusal raises Blocked and is logged
    - when bound to a run folder, writes one line per request to requests.jsonl: time, source, URL
      with secrets removed, status, bytes, SHA-256, rate-limit headers, attempt and records returned.
      Response bodies are kept (gzipped, unchanged, in raw_responses/<source>/) only when keep_raw
      is on, which collect --keep-raw does. The SHA-256 in the log still identifies each body.
    Tests replace `transport` with a function that returns canned responses.
    """

    def __init__(self, transport=None, min_interval: float = 1.0, timeout: float = 60.0):
        self.transport, self.min_interval, self.timeout = transport, min_interval, timeout
        self.host_interval: dict = {}
        self._last: dict = {}
        self.down: dict = {}
        self.run_dir: Path | None = None
        self.source = ""
        self.n = 0
        self.keep_raw = False
        self.site_budget = SITE_BUDGET
        self.sent: Counter = Counter()          # requests per host in this run
        self.cooldown: dict = {}                # host -> monotonic time before which nobody may call it
        self._private: dict = {}
        self._local = threading.local()
        self._lock = threading.Lock()

    def bind(self, run_dir, source: str):
        self.run_dir, self.source = (Path(run_dir) if run_dir else None), source

    def _wait(self, host):
        """Reserves the next free slot for this host under a lock, so threads never call one host faster
        than its interval, and every thread honours a cooldown the host asked for."""
        gap = self.host_interval.get(host, self.min_interval)
        with self._lock:
            now = time.monotonic()
            slot = max(now, self._last.get(host, -1e18) + gap, self.cooldown.get(host, 0.0))
            self._last[host] = slot
        if slot > now:
            time.sleep(slot - now)

    def _send(self, method, url, headers, json_body):
        if self.transport:
            return self.transport(method, url, headers, json_body)
        import requests
        if getattr(self._local, "session", None) is None:
            self._local.session = requests.Session()
        try:
            r = self._local.session.request(method, url, headers=headers, json=json_body, timeout=self.timeout,
                                            allow_redirects=False)      # each redirect is checked in request()
        except requests.RequestException as e:
            return 599, {}, f"network error: {type(e).__name__}".encode()
        return r.status_code, dict(r.headers), r.content

    def _log(self, entry: dict):
        if self.run_dir is None:
            return
        self.run_dir.mkdir(parents=True, exist_ok=True)
        with self._lock, (self.run_dir / "requests.jsonl").open("a", encoding="utf-8") as fh:
            fh.write(json.dumps(entry) + "\n")

    def _keep_raw(self, body: bytes, ctype: str) -> str:
        if self.run_dir is None or not body:
            return ""
        ext = "json" if "json" in ctype else "xml" if "xml" in ctype or "rss" in ctype else "html" if "html" in ctype else "txt"
        folder = self.run_dir / "raw_responses" / (self.source or "misc")
        folder.mkdir(parents=True, exist_ok=True)
        with self._lock:
            self.n += 1
            n = self.n
        path = folder / f"{datetime.now(timezone.utc):%Y%m%dT%H%M%S}_{n:05d}.{ext}.gz"
        path.write_bytes(gzip.compress(body))
        return str(path.relative_to(self.run_dir))

    def _guard(self, url: str):
        """Raises Blocked when the address is private, the host's request budget is spent, or SITE_RULES or
        robots.txt forbids this URL for the current source."""
        parts = urllib.parse.urlsplit(url)
        why, kind = "", "policy"
        if parts.scheme not in ("http", "https"):
            why = f"only http and https are allowed, not {parts.scheme or 'a bare path'}"
        else:
            host = parts.netloc
            if host not in self._private:
                self._private[host] = private_address(host, resolve=self.transport is None)
            if self._private[host]:
                why, kind = f"{host} is a private or local address ({self._private[host]}). The skill reads public sites only", "private"
            elif self.sent[host] >= self.site_budget:
                why, kind = f"the budget of {self.site_budget} requests to {host} in one run is spent", "budget"
        if why:
            self._log({"time": datetime.now(timezone.utc).isoformat(), "source": self.source, "method": "-",
                       "url": redact(url), "status": "refused", "why": why})
            raise Blocked(url, why, kind)
        why, kind = policy_refusal(url, self.source), "policy"
        if not why and self.source in ROBOTS_SOURCES and urllib.parse.urlsplit(url).path not in ("/robots.txt", TDM_PATH):
            ok, delay = ROBOTS.check(url)
            host = urllib.parse.urlsplit(url).netloc
            if not ok:
                why, kind = "robots.txt disallows this URL for titus-scraper, or robots.txt could not be read", "robots"
            else:
                if delay:
                    self.host_interval[host] = max(self.host_interval.get(host, self.min_interval), delay)
                tdm = TDM.reserved(url)
                if tdm:
                    why, kind = f"{host} {tdm}", "tdm"
        if why:
            self._log({"time": datetime.now(timezone.utc).isoformat(), "source": self.source, "method": "-",
                       "url": redact(url), "status": "refused", "why": why})
            raise Blocked(url, why, kind)

    def request(self, method: str, url: str, params: dict | None = None, headers: dict | None = None,
                json_body=None, tries: int = 5, records=None, keep_raw: bool = True) -> tuple[int, dict, bytes]:
        if params:
            q = urllib.parse.urlencode([(k, v) for k, v in params.items() if v is not None and v != ""], doseq=True)
            url = url + ("&" if "?" in url else "?") + q
        hdrs = {"User-Agent": user_agent(), **(headers or {})}
        for hop in range(MAX_REDIRECTS + 1):
            self._guard(url)
            status, rh, body = self._attempts(method, url, hdrs, json_body, tries, records, keep_raw and self.keep_raw, hop)
            if (status not in REDIRECTS and self.source in ROBOTS_SOURCES and str(rh.get("tdm-reservation", "")).strip() == "1"
                    and urllib.parse.urlsplit(url).path not in ("/robots.txt", TDM_PATH)):
                why = f"{urllib.parse.urlsplit(url).netloc} reserves text and data mining rights for this page (tdm-reservation header)"
                self._log({"time": datetime.now(timezone.utc).isoformat(), "source": self.source, "method": "-",
                           "url": redact(url), "status": "refused", "why": why})
                raise Blocked(url, why, "tdm")
            if status not in REDIRECTS:
                return status, rh, body
            if not rh.get("location"):
                raise HTTPError(status, url, "redirect without a Location header")
            nxt = urllib.parse.urljoin(url, rh["location"])
            if urllib.parse.urlsplit(nxt).netloc != urllib.parse.urlsplit(url).netloc:   # never carry credentials to another host
                hdrs = {k: v for k, v in hdrs.items() if k.lower() not in ("authorization", "cookie")}
            if status in (301, 302, 303) and method == "POST":
                method, json_body = "GET", None
            url = nxt
        raise HTTPError(310, url, f"more than {MAX_REDIRECTS} redirects")

    def _attempts(self, method, url, hdrs, json_body, tries, records, keep_raw, hop) -> tuple[int, dict, bytes]:
        host = urllib.parse.urlsplit(url).netloc
        if host in self.down:
            raise HTTPError(599, url, f"skipped: {host} was unreachable earlier in this run")
        for attempt in range(tries):
            if self.source in DAILY_LIMITS and urllib.parse.urlsplit(url).path != "/robots.txt":
                USAGE.take(self.source, DAILY_LIMITS[self.source])
            self._wait(host)
            with self._lock:
                self.sent[host] += 1
            status, rh, body = self._send(method, url, hdrs, json_body)
            rh = {k.lower(): v for k, v in (rh or {}).items()}
            entry = {"time": datetime.now(timezone.utc).isoformat(), "source": self.source, "method": method,
                     "url": redact(url), "status": status, "bytes": len(body or b""),
                     "sha256": hashlib.sha256(body or b"").hexdigest(), "attempt": attempt + 1,
                     "rate_limit": {k: rh[k] for k in RATE_HEADERS if k in rh}}
            if hop:
                entry["redirect_hop"] = hop
            if status in REDIRECTS:
                entry["redirect_to"] = redact(urllib.parse.urljoin(url, rh.get("location", "")))
                self._log(entry)
                return status, rh, body
            if status < 400:
                n = records(body) if records else None
                entry["records"] = n
                entry["raw_file"] = self._keep_raw(body, rh.get("content-type", "")) if keep_raw else ""
                self._log(entry)
                return status, rh, body
            self._log(entry)
            if status == 599 and attempt >= 1:
                self.down[host] = body.decode("utf-8", "replace")
                raise HTTPError(status, url, self.down[host])
            if not (status == 429 or status >= 500) or attempt == tries - 1:
                raise HTTPError(status, url, (body or b"").decode("utf-8", "replace"))
            asked = retry_after_seconds(rh.get("retry-after"))
            if asked is not None and asked > MAX_RETRY_WAIT:
                with self._lock:
                    self.cooldown[host] = time.monotonic() + asked
                    self.down[host] = f"{host} asked to wait {asked / 60:.0f} minutes (Retry-After). Left alone for the rest of the run"
                raise HTTPError(status, url, self.down[host])
            wait = (asked if asked is not None else 3 if status == 599 else 2 ** attempt * 5) + random.random()
            with self._lock:                  # every thread waits, not only this one
                self.cooldown[host] = max(self.cooldown.get(host, 0.0), time.monotonic() + wait)
            log.warning("HTTP %s from %s, waiting %.0fs", status, host, wait)
        raise HTTPError(599, url, "no attempts left")

    def get_json(self, url, params=None, headers=None, tries=5):
        _, _, body = self.request("GET", url, params, headers, tries=tries, records=_count_records)
        try:
            return json.loads(body)
        except ValueError as e:
            raise NotJSON(200, url, body.decode("utf-8", "replace")[:300]) from e

    def get_text(self, url, params=None, headers=None, tries=5, keep_raw=True) -> str:
        return self.get_page(url, params, headers, tries, keep_raw)[0]

    def get_page(self, url, params=None, headers=None, tries=5, keep_raw=True) -> tuple[str, dict]:
        """The decoded body and the response headers (lower-case names)."""
        _, rh, body = self.request("GET", url, params, headers, tries=tries, keep_raw=keep_raw)
        enc = re.search(r"charset=([\w-]+)", rh.get("content-type", ""))
        try:
            return body.decode(enc.group(1) if enc else "utf-8", "replace"), rh
        except LookupError:
            return body.decode("utf-8", "replace"), rh

    def post_json(self, url, body, headers=None):
        _, _, out = self.request("POST", url, headers=headers, json_body=body, tries=2, keep_raw=False)
        return json.loads(out)


class NotJSON(HTTPError):
    pass


def _count_records(body: bytes):
    try:
        d = json.loads(body)
    except ValueError:
        return None
    if isinstance(d, list):
        return len(d)
    for k in ("posts", "feed", "items", "articles", "results", "docs", "data", "statuses"):
        v = d.get(k) if isinstance(d, dict) else None
        v = v if v is not None else ((d.get("response") or {}).get(k) if isinstance(d, dict) and isinstance(d.get("response"), dict) else None)
        if isinstance(v, list):
            return len(v)
    return None


HTTP = Http()


def get_json(url: str, params: dict | None = None, headers: dict | None = None, tries: int = 5) -> dict:
    return HTTP.get_json(url, params, headers, tries)


class Collector:
    platform = "base"
    needs: tuple = ()

    def hashtag(self, tags, since, until, limit):
        raise NotImplementedError(f"{self.platform}: no free official hashtag search")

    def topic(self, phrases, since, until, limit):
        raise NotImplementedError(f"{self.platform}: no free official keyword search")

    def user(self, handle, since, until, limit):
        raise NotImplementedError(f"{self.platform}: no free official way to read this account")


class Bluesky(Collector):
    """app.bsky.feed.searchPosts and getAuthorFeed, through your own PDS with an app password."""
    platform, needs = "bluesky", ("BSKY_HANDLE", "BSKY_APP_PASSWORD")
    PDS = "https://bsky.social/xrpc"

    def __init__(self):
        r = HTTP.post_json(f"{self.PDS}/com.atproto.server.createSession",
                           {"identifier": os.environ["BSKY_HANDLE"], "password": os.environ["BSKY_APP_PASSWORD"]})
        self.auth = {"Authorization": f"Bearer {r['accessJwt']}"}

    def _post(self, p, qtype, qval, endpoint) -> Post:
        rec, embed = p.get("record", {}), p.get("embed") or {}
        handle, text = p["author"]["handle"], rec.get("text", "")
        alts = [i.get("alt", "") for i in embed.get("images", []) if i.get("alt")]
        if alts:
            text += "\n[alt] " + " | ".join(alts)
        reply = rec.get("reply", {})
        return Post(platform="bluesky", post_id=p["uri"], text=text,
                    created_at=to_utc_iso(rec.get("createdAt") or p.get("indexedAt")),
                    url=f"https://bsky.app/profile/{handle}/post/{p['uri'].rsplit('/', 1)[-1]}",
                    author_handle=handle, author_id=p["author"].get("did", ""), author_name=p["author"].get("displayName", ""),
                    kind="comment" if reply else "post", parent_id=(reply.get("parent") or {}).get("uri", ""),
                    like_count=p.get("likeCount"), reply_count=p.get("replyCount"),
                    share_count=(p.get("repostCount") or 0) + (p.get("quoteCount") or 0),
                    query_type=qtype, query_value=qval, source_endpoint=endpoint,
                    media_urls=[i.get("fullsize", "") for i in embed.get("images", [])] +
                    [e.get("playlist") for e in (embed, embed.get("media") or {}) if "video" in str(e.get("$type", "")) and e.get("playlist")])

    def _search(self, params, qtype, qval, limit):
        out, cursor = [], None
        while len(out) < limit:
            q = {**params, "limit": 100, "sort": "latest", **({"cursor": cursor} if cursor else {})}
            data = get_json(f"{self.PDS}/app.bsky.feed.searchPosts", q, self.auth)
            out += [self._post(p, qtype, qval, "app.bsky.feed.searchPosts") for p in data.get("posts", [])]
            cursor = data.get("cursor")
            if not cursor or not data.get("posts"):
                break
        return out[:limit]

    def hashtag(self, tags, since, until, limit):
        return [p for t in tags for p in self._search({"q": f"#{t}", "since": since, "until": until}, "hashtag", t, limit)]

    def topic(self, phrases, since, until, limit):
        return [p for ph in phrases for p in self._search({"q": f'"{ph}"', "since": since, "until": until}, "topic", ph, limit)]

    def user(self, handle, since, until, limit):
        out, cursor = [], None
        while len(out) < limit:
            q = {"actor": handle, "limit": 100, "filter": "posts_with_replies", **({"cursor": cursor} if cursor else {})}
            data = get_json(f"{self.PDS}/app.bsky.feed.getAuthorFeed", q, self.auth)
            for i in data.get("feed", []):
                p = self._post(i["post"], "user", handle, "app.bsky.feed.getAuthorFeed")
                reason = i.get("reason") or {}
                if reason:          # a repost: kept apart from the account's own words
                    by = reason.get("by") or {}
                    p = Post(**{**asdict(p), "kind": "repost", "parent_id": p.post_id,
                                "post_id": f"repost:{by.get('did', handle)}:{p.post_id}",
                                "author_handle": by.get("handle", handle), "author_id": by.get("did", ""),
                                "created_at": to_utc_iso(reason.get("indexedAt")) or p.created_at})
                out.append(p)
            cursor = data.get("cursor")
            if not cursor or (since and out and out[-1].created_at < since):
                break
        return [p for p in out if in_window(p, since, until)][:limit]


class YouTube(Collector):
    """Data API v3. Default quota: 100 search.list calls a day, plus 10,000 units for everything else."""
    platform, needs = "youtube", ("YOUTUBE_API_KEY",)
    API = "https://www.googleapis.com/youtube/v3"

    def __init__(self, comments_per_video: int = 200, max_videos: int = 100):
        self.key, self.comments_per_video, self.max_videos = os.environ["YOUTUBE_API_KEY"], comments_per_video, max_videos
        self.units, self.search_calls = 0, 0

    def _get(self, path, **params):
        if path == "search":
            if self.search_calls >= 100:
                raise RuntimeError("Daily limit of 100 search.list calls reached. Run again tomorrow.")
            USAGE.take("youtube-search", DAILY_LIMITS["youtube-search"])     # counts runs in every folder
            self.search_calls += 1
        else:
            self.units += 1
        return get_json(f"{self.API}/{path}", {**params, "key": self.key})

    def _video(self, vid, sn, qtype, qval, endpoint) -> Post:
        return Post(platform="youtube", post_id=vid, text=f"{sn['title']}\n{sn.get('description', '')}".strip(),
                    created_at=to_utc_iso(sn["publishedAt"]), url=f"https://www.youtube.com/watch?v={vid}",
                    author_handle=sn.get("channelTitle", ""), author_id=sn.get("channelId", ""),
                    query_type=qtype, query_value=qval, source_endpoint=endpoint)

    def comments(self, vid, qtype, qval) -> list[Post]:
        out, token = [], None
        while len(out) < self.comments_per_video:
            params = {"part": "snippet", "videoId": vid, "maxResults": 100, "textFormat": "plainText",
                      "order": "relevance", **({"pageToken": token} if token else {})}
            try:
                data = self._get("commentThreads", **params)
            except Exception:          # comments turned off on this video
                break
            for it in data.get("items", []):
                c = it["snippet"]["topLevelComment"]["snippet"]
                out.append(Post(platform="youtube", post_id=it["id"], text=c["textDisplay"],
                                created_at=to_utc_iso(c["publishedAt"]), kind="comment", parent_id=vid,
                                url=f"https://www.youtube.com/watch?v={vid}&lc={it['id']}",
                                author_handle=c.get("authorDisplayName", ""), like_count=c.get("likeCount"),
                                author_id=(c.get("authorChannelId") or {}).get("value", ""),
                                query_type=qtype, query_value=qval, source_endpoint="commentThreads.list"))
            token = data.get("nextPageToken")
            if not token:
                break
        return out

    def _search(self, q, qtype, qval, since, until):
        out, token, n = [], None, 0
        while n < self.max_videos:
            params = {"part": "snippet", "q": q, "type": "video", "maxResults": 50, "order": "date",
                      "relevanceLanguage": "en", "publishedAfter": since, "publishedBefore": until,
                      **({"pageToken": token} if token else {})}
            data = self._get("search", **{k: v for k, v in params.items() if v})
            for it in data.get("items", []):
                vid = it["id"]["videoId"]
                out.append(self._video(vid, it["snippet"], qtype, qval, "search.list"))
                out += self.comments(vid, qtype, qval)
                n += 1
            token = data.get("nextPageToken")
            if not token:
                break
        return out

    def hashtag(self, tags, since, until, limit):
        return [p for t in tags for p in self._search(f"#{t}", "hashtag", t, since, until)]

    def topic(self, phrases, since, until, limit):
        return [p for ph in phrases for p in self._search(f'"{ph}"', "topic", ph, since, until)]

    def user(self, handle, since, until, limit):
        ch = self._get("channels", part="contentDetails", forHandle=handle.lstrip("@"))
        uploads = ch["items"][0]["contentDetails"]["relatedPlaylists"]["uploads"]
        out, token = [], None
        while sum(p.kind == "post" for p in out) < min(limit, self.max_videos):
            data = self._get("playlistItems", part="snippet", playlistId=uploads, maxResults=50,
                             **({"pageToken": token} if token else {}))
            stop = False
            for it in data.get("items", []):
                sn = it["snippet"]
                p = self._video(sn["resourceId"]["videoId"], sn, "user", handle, "playlistItems.list")
                if until and p.created_at >= until:
                    continue
                if since and p.created_at < since:
                    stop = True
                    break
                out.append(p)
                out += self.comments(p.post_id, "user", handle)
            token = data.get("nextPageToken")
            if stop or not token:
                break
        return out


class Reddit(Collector):
    """Official Data API through PRAW. New apps need Reddit's approval, and its terms and access rules
    have changed several times, so read the current Data API terms before each study."""
    platform, needs = "reddit", ("REDDIT_CLIENT_ID", "REDDIT_CLIENT_SECRET")

    def __init__(self, subreddits: list[str] | None = None, comments_per_post: int = 50):
        import praw
        self.r = praw.Reddit(client_id=os.environ["REDDIT_CLIENT_ID"], client_secret=os.environ["REDDIT_CLIENT_SECRET"],
                             user_agent=os.environ.get("REDDIT_USER_AGENT", user_agent()))
        self.subreddits = subreddits or os.environ.get("REDDIT_SUBREDDITS", "all").split(",")
        self.comments_per_post = comments_per_post

    def _sub(self, s, qtype, qval, endpoint) -> Post:
        return Post(platform="reddit", post_id=s.id, text=f"{s.title}\n{s.selftext or ''}".strip(),
                    created_at=to_utc_iso(s.created_utc), url=f"https://www.reddit.com{s.permalink}",
                    author_handle=str(s.author or "[deleted]"), author_id=getattr(s, "author_fullname", "") or "",
                    like_count=s.score, reply_count=s.num_comments,
                    query_type=qtype, query_value=qval, source_endpoint=endpoint)

    def _comment(self, c, parent, qtype, qval, endpoint) -> Post:
        return Post(platform="reddit", post_id=c.id, text=c.body, created_at=to_utc_iso(c.created_utc),
                    url=f"https://www.reddit.com{c.permalink}", author_handle=str(c.author or "[deleted]"),
                    kind="comment", parent_id=parent, like_count=c.score, query_type=qtype, query_value=qval,
                    source_endpoint=endpoint)

    def _search(self, q, qtype, qval, since, until, limit):
        out = []
        for name in self.subreddits:
            for s in self.r.subreddit(name.strip()).search(q, sort="new", time_filter="year", limit=limit):
                p = self._sub(s, qtype, qval, f"r/{name}/search")
                if not in_window(p, since, until):
                    continue
                out.append(p)
                if self.comments_per_post:
                    s.comment_sort = "top"
                    s.comments.replace_more(limit=0)
                    out += [self._comment(c, s.id, qtype, qval, "submission.comments")
                            for c in s.comments.list()[: self.comments_per_post]]
        return out

    def hashtag(self, tags, since, until, limit):
        return [p for t in tags for p in self._search(t, "hashtag", t, since, until, limit)]

    def topic(self, phrases, since, until, limit):
        return [p for ph in phrases for p in self._search(f'"{ph}"', "topic", ph, since, until, limit)]

    def user(self, handle, since, until, limit):
        u = self.r.redditor(handle)
        out = [self._sub(s, "user", handle, "redditor.submissions") for s in u.submissions.new(limit=limit)]
        out += [self._comment(c, c.link_id, "user", handle, "redditor.comments") for c in u.comments.new(limit=limit)]
        return [p for p in out if in_window(p, since, until)]


class Threads(Collector):
    """keyword_search: 2,200 queries per rolling 24 h, posts since 5 Jul 2023.
    Until Meta approves threads_keyword_search, it searches only your own posts."""
    platform, needs = "threads", ("THREADS_ACCESS_TOKEN",)
    API = "https://graph.threads.com/v1.0"
    FIELDS = "id,text,media_type,media_url,permalink,timestamp,username,has_replies,is_quote_post,is_reply"

    def __init__(self):
        self.token = os.environ["THREADS_ACCESS_TOKEN"]

    @staticmethod
    def _epoch(iso):
        return int(datetime.fromisoformat(iso.replace("Z", "+00:00")).timestamp()) if iso else None

    def _page(self, path, params, qtype, qval, limit):
        out, url, q = [], f"{self.API}/{path}", {**params, "fields": self.FIELDS, "access_token": self.token}
        while url and len(out) < limit:
            data = get_json(url, q)
            for m in data.get("data", []):
                if m.get("text"):
                    out.append(Post(platform="threads", post_id=m["id"], text=m["text"],
                                    created_at=to_utc_iso(m["timestamp"]), url=m.get("permalink", ""),
                                    author_handle=m.get("username", ""), kind="comment" if m.get("is_reply") else "post",
                                    query_type=qtype, query_value=qval, source_endpoint=path,
                                    media_urls=[m["media_url"]] if m.get("media_url") else []))
            url, q = (data.get("paging") or {}).get("next"), None
        return out[:limit]

    def _search(self, q, mode, qtype, qval, since, until, limit, author=None):
        params = {"q": q, "search_mode": mode, "search_type": "RECENT", "limit": 100,
                  "since": self._epoch(since), "until": self._epoch(until), "author_username": author}
        return self._page("keyword_search", {k: v for k, v in params.items() if v}, qtype, qval, limit)

    def hashtag(self, tags, since, until, limit):
        return [p for t in tags for p in self._search(t, "TAG", "hashtag", t, since, until, limit)]

    def topic(self, phrases, since, until, limit):
        return [p for ph in phrases for p in self._search(ph, "KEYWORD", "topic", ph, since, until, limit)]

    def user(self, handle, since, until, limit):
        """'me' reads your own threads. For another account, pass 'handle:keyword'."""
        if handle in ("me", ""):
            params = {"since": self._epoch(since), "until": self._epoch(until), "limit": 100}
            return self._page("me/threads", {k: v for k, v in params.items() if v}, "user", "me", limit)
        name, _, kw = handle.partition(":")
        if not kw:
            raise NotImplementedError("Threads needs a keyword to read another account. Use --value 'handle:keyword'.")
        return self._search(kw, "KEYWORD", "user", handle, since, until, limit, author=name.lstrip("@"))


class Instagram(Collector):
    """Graph API. Hashtags: last 24 h only, 30 unique tags per 7 days, after Public Content Access review.
    Accounts: Business Discovery, for Business or Creator accounts."""
    platform, needs = "instagram", ("IG_USER_ID", "IG_ACCESS_TOKEN")
    API = "https://graph.facebook.com/v21.0"
    FIELDS = "id,caption,media_type,media_url,permalink,timestamp,like_count,comments_count"

    def __init__(self):
        self.uid, self.token = os.environ["IG_USER_ID"], os.environ["IG_ACCESS_TOKEN"]

    def _media(self, items, qtype, qval, endpoint, handle=""):
        return [Post(platform="instagram", post_id=m["id"], text=m["caption"], created_at=to_utc_iso(m["timestamp"]),
                     url=m.get("permalink", ""), author_handle=handle, like_count=m.get("like_count"),
                     reply_count=m.get("comments_count"), query_type=qtype, query_value=qval, source_endpoint=endpoint,
                     media_urls=[m["media_url"]] if m.get("media_url") else [])
                for m in items if m.get("caption")]

    def hashtag(self, tags, since, until, limit):
        out = []
        for t in tags:
            hid = get_json(f"{self.API}/ig_hashtag_search", {"user_id": self.uid, "q": t, "access_token": self.token})["data"][0]["id"]
            for edge in ("recent_media", "top_media"):
                url, params, got = f"{self.API}/{hid}/{edge}", {"user_id": self.uid, "fields": self.FIELDS, "limit": 50,
                                                               "access_token": self.token}, []
                while url and len(got) < limit:
                    data = get_json(url, params)
                    got += self._media(data.get("data", []), "hashtag", t, f"ig_hashtag/{edge}")
                    url, params = (data.get("paging") or {}).get("next"), None
                out += got
        return out

    def user(self, handle, since, until, limit):
        def fetch(after=None):
            page = f".after({after})" if after else ""
            f = f"business_discovery.username({handle}){{media{page}.limit(50){{{self.FIELDS}}}}}"
            return get_json(f"{self.API}/{self.uid}", {"fields": f, "access_token": self.token})["business_discovery"]["media"]
        media = fetch()
        out = self._media(media.get("data", []), "user", handle, "business_discovery", handle)
        while len(out) < limit and media.get("paging", {}).get("cursors", {}).get("after"):
            media = fetch(media["paging"]["cursors"]["after"])
            out += self._media(media.get("data", []), "user", handle, "business_discovery", handle)
            if since and out and out[-1].created_at < since:
                break
        return [p for p in out if in_window(p, since, until)][:limit]


class Gdelt(Collector):
    """GDELT DOC 2.0: no key, last 3 months, up to 250 headlines per call, no body text."""
    platform = "gdelt"
    URL = "https://api.gdeltproject.org/api/v2/doc/doc"

    def _run(self, q, qtype, qval, since, until, limit):
        start = max(datetime.fromisoformat(since.replace("Z", "+00:00")), datetime.now(timezone.utc) - timedelta(days=89))
        end, out = datetime.fromisoformat(until.replace("Z", "+00:00")), []
        while start < end and len(out) < limit:
            nxt = min(start + timedelta(days=1), end)
            params = {"query": f"{q} sourcelang:english", "mode": "ArtList", "format": "json", "maxrecords": 250,
                      "sort": "DateAsc", "startdatetime": f"{start:%Y%m%d%H%M%S}", "enddatetime": f"{nxt:%Y%m%d%H%M%S}"}
            HTTP.host_interval["api.gdeltproject.org"] = 6.0     # GDELT asks for one request every 5 seconds
            try:
                data = get_json(self.URL, params)
            except NotJSON:             # plain-text reply when nothing matches
                data = {}
            for a in data.get("articles", []):
                seen = datetime.strptime(a["seendate"], "%Y%m%dT%H%M%SZ").replace(tzinfo=timezone.utc)
                out.append(Post(platform="news", post_id=stable_id(a["url"]), text=a.get("title", ""),
                                created_at=seen.isoformat(), url=a["url"], author_handle=a.get("domain", ""),
                                kind="headline", query_type=qtype, query_value=qval, source_endpoint="gdelt doc ArtList",
                                fulltext_status="metadata-only"))
            start = nxt
        return out[:limit]

    def hashtag(self, tags, since, until, limit):
        return [p for t in tags for p in self._run(t, "hashtag", t, since, until, limit)]

    def topic(self, phrases, since, until, limit):
        return [p for ph in phrases for p in self._run(f'"{ph}"', "topic", ph, since, until, limit)]

    def user(self, handle, since, until, limit):
        domain, _, kw = handle.partition(":")
        return self._run(f"domain:{domain} {kw}".strip(), "user", handle, since, until, limit)


class Guardian(Collector):
    """Guardian Open Platform: free non-commercial developer key, full body text, archive back to 1999."""
    platform, needs = "guardian", ("GUARDIAN_API_KEY",)
    URL = "https://content.guardianapis.com/search"

    def __init__(self):
        self.key = os.environ["GUARDIAN_API_KEY"]

    def _run(self, q, qtype, qval, since, until, limit):
        out, page = [], 1
        while len(out) < limit:
            if USAGE.used("guardian") >= DAILY_LIMITS["guardian"]:
                log.warning("guardian: 500 calls used today. Run collect again tomorrow (UTC) into the same folder.")
                break
            data = get_json(self.URL, {"q": q, "from-date": since[:10], "to-date": until[:10], "page": page,
                                       "show-fields": "bodyText,headline,byline", "page-size": 50,
                                       "order-by": "oldest", "api-key": self.key})["response"]
            for r in data.get("results", []):
                f = r.get("fields", {})
                out.append(Post(platform="news", post_id=r["id"], text=f"{f.get('headline', '')}\n{f.get('bodyText', '')}",
                                created_at=to_utc_iso(r["webPublicationDate"]), url=r["webUrl"],
                                author_handle="theguardian.com", author_name=f.get("byline", ""), kind="article",
                                query_type=qtype, query_value=qval, source_endpoint="guardian search",
                                fulltext_status="api" if f.get("bodyText") else "metadata-only"))
            if page >= data.get("pages", 1):
                break
            page += 1
        return out[:limit]

    def hashtag(self, tags, since, until, limit):
        return [p for t in tags for p in self._run(t, "hashtag", t, since, until, limit)]

    def topic(self, phrases, since, until, limit):
        return [p for ph in phrases for p in self._run(f'"{ph}"', "topic", ph, since, until, limit)]


class NYTimes(Collector):
    """NYT APIs: free key from developer.nytimes.com, archive back to 1851. Both return the headline,
    abstract and lead paragraph, not the full article, and NYT's terms bar collecting its pages by
    automated means, so this skill never fetches nytimes.com pages.
      search mode   Article Search, the query sent to NYT, monthly slices, 10 results a page
      archive mode  Archive API, every article of each month in one call, matched here with the query
                    dictionary. Fewer calls for long windows, and the match rule is fully under your control.
    NYT's FAQ has stated limits of 5 calls a minute and 500 a day, so calls are 12 seconds apart and
    the collector stops at 500. Run collect again the next day into the same folder for more."""
    platform, needs = "nytimes", ("NYT_API_KEY",)
    URL = "https://api.nytimes.com/svc/search/v2/articlesearch.json"
    ARCHIVE = "https://api.nytimes.com/svc/archive/v1/{y}/{m}.json"

    def __init__(self, mode: str = "search", query: Query | None = None):
        self.key, self.calls, self.mode, self.query = os.environ["NYT_API_KEY"], 0, mode, query
        HTTP.host_interval["api.nytimes.com"] = 12.5

    @staticmethod
    def to_post(d, qtype, qval, endpoint="nyt article search") -> Post:
        parts = []
        head = d.get("headline") or {}
        for x in ((head.get("main") if isinstance(head, dict) else str(head)), d.get("abstract"), d.get("lead_paragraph")):
            if x and x not in parts:
                parts.append(x)
        when = re.sub(r"([+-]\d\d)(\d\d)$", r"\1:\2", str(d.get("pub_date", "")))
        byline = d.get("byline") or {}
        return Post(platform="nytimes", post_id=d.get("_id") or stable_id(d.get("web_url", "")), text="\n".join(parts),
                    created_at=to_utc_iso(when), url=d.get("web_url", ""), author_handle="nytimes.com",
                    author_name=(byline.get("original") if isinstance(byline, dict) else "") or "", kind="summary",
                    query_type=qtype, query_value=qval, source_endpoint=endpoint, fulltext_status="summary")

    def _budget(self) -> bool:
        if self.calls >= 500 or USAGE.used("nytimes") >= DAILY_LIMITS["nytimes"]:
            log.warning("nytimes: 500 calls used today, counting earlier runs. Run collect again tomorrow (UTC) into the same folder.")
            return False
        self.calls += 1
        return True

    def _run(self, q, qtype, qval, since, until, limit):
        start = datetime.fromisoformat(since.replace("Z", "+00:00"))
        end, out = datetime.fromisoformat(until.replace("Z", "+00:00")), []
        while start < end and len(out) < limit:
            nxt = min(start + timedelta(days=31), end)      # monthly slices stay under the paging cap
            for page in range(100):
                if not self._budget():
                    return out[:limit]
                try:
                    data = get_json(self.URL, {"q": q, "begin_date": f"{start:%Y%m%d}", "sort": "oldest", "page": page,
                                               "end_date": f"{nxt - timedelta(days=1):%Y%m%d}", "api-key": self.key})
                except HTTPError as e:                     # past the last page NYT serves, or the daily limit
                    log.warning("nytimes: %s", e)
                    break
                docs = (data.get("response") or {}).get("docs") or []
                out += [self.to_post(d, qtype, qval) for d in docs]
                if len(docs) < 10 or len(out) >= limit:
                    break
            start = nxt
        return out[:limit]

    def archive(self, since, until, limit, qtype, qval):
        """One call per month. Keeps the articles whose headline, abstract or lead paragraph match."""
        start = datetime.fromisoformat(since.replace("Z", "+00:00"))
        end = datetime.fromisoformat(until.replace("Z", "+00:00"))
        y, m, out = start.year, start.month, []
        while datetime(y, m, 1, tzinfo=timezone.utc) < end and len(out) < limit:
            if not self._budget():
                break
            data = get_json(self.ARCHIVE.format(y=y, m=m), {"api-key": self.key})
            for d in (data.get("response") or {}).get("docs") or []:
                p = self.to_post(d, qtype, qval, "nyt archive")
                if in_window(p, since, until) and (self.query is None or self.query.matches(p.text)):
                    out.append(p)
            y, m = (y + 1, 1) if m == 12 else (y, m + 1)
        return out[:limit]

    def hashtag(self, tags, since, until, limit):
        if self.mode == "archive":
            return self.archive(since, until, limit, "hashtag", ",".join(tags))
        return [p for t in tags for p in self._run(f'"{t}"', "hashtag", t, since, until, limit)]

    def topic(self, phrases, since, until, limit):
        if self.mode == "archive":
            return []                        # the archive pass in hashtag() already applied every rule
        return [p for ph in phrases for p in self._run(f'"{ph}"', "topic", ph, since, until, limit)]


def _strip_html(s: str) -> str:
    s = re.sub(r"(?is)<(script|style)\b.*?</\1>", " ", s or "")
    s = re.sub(r"(?i)<br\s*/?>|</p>|</h\d>|</li>|</blockquote>", "\n", s)
    s = html.unescape(re.sub(r"<[^>]+>", " ", s))
    return re.sub(r"\n\s*\n+", "\n", re.sub(r"[ \t\u00a0]+", " ", s)).strip()


def _feed_time(v: str) -> str:
    from email.utils import parsedate_to_datetime
    v = (v or "").strip()
    if not v:
        return ""
    try:
        return to_utc_iso(parsedate_to_datetime(v))       # RSS: 'Tue, 03 Jun 2025 10:00:00 GMT'
    except (TypeError, ValueError):
        pass
    try:
        return to_utc_iso(v)                                # Atom: ISO 8601
    except ValueError:
        return ""


def parse_feed(raw: bytes, feed_url: str, label: str) -> list[Post]:
    """Reads an RSS 2.0 or Atom feed into posts. Keeps the longest body the feed offers. Items from
    Google News name their outlet in <source>, and their links point to Google, so they stay headlines."""
    import xml.etree.ElementTree as ET
    local = lambda el: el.tag.rsplit("}", 1)[-1] if isinstance(el.tag, str) else ""

    def txt(el, *names):
        for c in el:
            if local(c) in names and (c.text or "").strip():
                return c.text.strip()
        return ""

    host, out = domain_of(feed_url), []
    gnews = "news.google.com" in host
    for it in (e for e in ET.fromstring(raw).iter() if local(e) in ("item", "entry")):
        link = txt(it, "link") or next((c.get("href") for c in it if local(c) == "link" and c.get("href")
                                        and c.get("rel", "alternate") == "alternate"), "")
        body = max((_strip_html(txt(it, n)) for n in ("encoded", "content", "description", "summary")), key=len)
        title = _strip_html(txt(it, "title"))
        author = txt(it, "creator") or txt(it, "author") or next(
            (txt(c, "name") for c in it if local(c) == "author" and txt(c, "name")), "")
        src = next((c for c in it if local(c) == "source"), None)
        outlet = host
        if src is not None:
            name = (src.text or "").strip()
            if name and title.endswith(" - " + name):
                title = title[: -len(name) - 3].rstrip()
            outlet = domain_of(src.get("url", "")) or name or host
        when = _feed_time(txt(it, "pubDate", "published", "date", "updated"))
        if not (title or body) or not when:
            continue
        if gnews:
            body = ""                       # the description repeats the headline and links to Google
        rule = site_rule(link or feed_url) or site_rule(feed_url)
        if rule and rule[1] == "headlines":  # SITE_RULES: title and a short summary, never the full text
            body = " ".join(_strip_html(txt(it, "description", "summary")).split()[:SUMMARY_WORDS])
        words = len(body.split())
        if label == "news" or gnews:
            kind = "article" if words > 120 else "summary" if words else "headline"
        else:
            kind = "article" if words > 120 else "post"
        status = "metadata-only" if gnews else ("feed" if words > 120 else "summary" if words else "metadata-only")
        out.append(Post(platform="news" if gnews else label, post_id=txt(it, "guid", "id") or stable_id(link or title, when),
                        text=f"{title}\n{body}".strip(), created_at=when, url=link, author_handle=outlet,
                        author_name=author, kind=kind, query_type="", query_value="", source_endpoint=f"feed {redact(feed_url)}",
                        fulltext_status=status if label in ("news",) or gnews else ""))
    return out


# Feeds that outlets publish. Feed addresses change; when one fails, find the outlet's current feed on its site.
# The BBC, Guardian, NYT and Al Jazeera feeds were removed: SITE_RULES blocks those sites.
OUTLET_FEEDS = {
    "npr": "https://feeds.npr.org/1001/rss.xml",
    "pbs": "https://www.pbs.org/newshour/feeds/rss/headlines",
}

class Feeds(Collector):
    """RSS and Atom feeds that sites publish for machines to read: personal blogs, Medium authors,
    publications and tags, Substack, WordPress, Ghost, and news section feeds.
      --feed URL or label=URL   any feed
      --outlet NAME             an outlet's own feed (OUTLET_FEEDS)
    Each feed's site needs a site:<domain> row approved in sources.csv, and robots.txt is checked for
    every feed and every redirect. Feeds carry only recent items, so run collect on a schedule to build
    a history. The analyze step keeps only items that match the query."""
    platform = "feeds"
    needs = ()

    @staticmethod
    def resolve(urls=None, outlets=None) -> list[tuple[str, str]]:
        """(label, URL) for each --feed, FEED_URLS entry and --outlet."""
        urls = [u.strip() for u in list(urls or []) + os.environ.get("FEED_URLS", "").split(",") if u.strip()]
        feeds = []
        for u in urls:
            label, sep, rest = u.partition("=")
            if sep and "://" not in label:
                feeds.append((label.strip(), rest.strip()))
            else:
                feeds.append(("medium" if domain_of(u).endswith("medium.com") else "web", u))
        for name in [o.strip().lower() for o in (outlets or []) if o.strip()]:
            if name not in OUTLET_FEEDS:
                raise NotImplementedError(f"feeds: unknown outlet '{name}'. Known: {', '.join(sorted(OUTLET_FEEDS))}. "
                                          "The BBC, Guardian, NYT and Al Jazeera feeds are blocked (SITE_RULES). Or pass --feed URL.")
            feeds.append(("news", OUTLET_FEEDS[name]))
        return feeds

    def __init__(self, urls=None, outlets=None, feeds=None):
        self.feeds = list(feeds) if feeds is not None else self.resolve(urls, outlets)
        if not self.feeds:
            raise NotImplementedError("feeds: pass --feed URL or --outlet NAME, for a site approved in sources.csv")

    def _read(self, feeds, qtype, qval, since, until, limit):
        out, seen = [], set()
        for label, url in feeds:
            try:
                raw = HTTP.get_text(url).encode("utf-8")
                items = parse_feed(raw, url, label)
            except Exception as e:       # one dead feed should not stop the others; a refusal is logged by Http
                log.warning("feed failed: %s (%s)", redact(url), e)
                continue
            for p in items:
                if p.post_id not in seen and in_window(p, since, until):
                    seen.add(p.post_id)
                    p.query_type, p.query_value = qtype, qval
                    out.append(p)
        return out[:limit]

    def hashtag(self, tags, since, until, limit):
        return self._read(self.feeds, "hashtag", ",".join(tags), since, until, limit)

    def topic(self, phrases, since, until, limit):
        return []                  # hashtag() already read every feed, and analyze filters the items

    def user(self, handle, since, until, limit):
        return self._read(self.feeds, "user", handle, since, until, limit)


class Mastodon(Collector):
    """Public hashtag timelines and public accounts on Mastodon servers. No key. There is no single
    Mastodon database: each server sees the posts its users follow, so the collector asks several
    servers and keeps one copy of each post by its URI. Some servers require login for hashtag
    timelines; those are skipped and named in the log. Boosts on hashtag timelines are skipped (the
    original is collected on its own). For an account, boosts are kept as kind 'repost'.
    Authors who opt out are skipped and counted: an account marked noindex or indexable false, or one
    whose bio, profile fields or post carries #nobot, #noindex, #nosearch or #noarchive."""
    platform, needs = "mastodon", ()
    SERVERS = ["mastodon.social", "mastodon.online", "mstdn.social", "fosstodon.org", "journa.host"]
    OPT_OUT_TAGS = ("nobot", "noindex", "nosearch", "noarchive")

    def __init__(self, servers=None):
        self.servers = [x.strip() for x in (servers or os.environ.get("MASTODON_SERVERS", "").split(",")) if x.strip()] or self.SERVERS
        self.opted_out: Counter = Counter()

    @classmethod
    def opt_out(cls, st: dict) -> str:
        """Why this status's author has opted out of collection, or ''."""
        acct = (st or {}).get("account") or {}
        if acct.get("noindex") is True:
            return "noindex"
        if acct.get("indexable") is False:
            return "indexable false"
        words = " ".join([acct.get("note") or ""] + [f"{f.get('name', '')} {f.get('value', '')}" for f in acct.get("fields") or []]
                         + [st.get("content") or ""] + [t.get("name", "") and "#" + t["name"] for t in st.get("tags") or []])
        found = {m.lower() for m in re.findall(r"#(\w+)", _strip_html(words))}
        hit = next((t for t in cls.OPT_OUT_TAGS if t in found), "")
        return f"#{hit}" if hit else ""

    @staticmethod
    def to_post(st: dict, server: str, qtype: str, qval: str, endpoint: str) -> Post | None:
        if not st:
            return None
        boost = st.get("reblog")
        src = boost or st
        acct = src.get("account") or {}
        handle = acct.get("acct", "")
        if handle and "@" not in handle:
            handle = f"{handle}@{server}"
        text = _strip_html(src.get("content", ""))
        if src.get("spoiler_text"):
            text = f"[CW: {src['spoiler_text']}] {text}"
        p = Post(platform="mastodon", post_id=src.get("uri") or f"{server}:{src.get('id')}", text=text,
                 created_at=to_utc_iso(src.get("created_at")), url=src.get("url") or src.get("uri", ""),
                 author_handle=handle, author_id=acct.get("url", ""), author_name=acct.get("display_name", ""),
                 kind="comment" if src.get("in_reply_to_id") else "post", parent_id=str(src.get("in_reply_to_id") or ""),
                 like_count=src.get("favourites_count"), reply_count=src.get("replies_count"),
                 share_count=src.get("reblogs_count"), query_type=qtype, query_value=qval, source_endpoint=endpoint,
                 media_urls=[m.get("url", "") for m in src.get("media_attachments", []) if m.get("url")])
        if boost:
            by = st.get("account") or {}
            p.parent_id, p.kind = p.post_id, "repost"
            p.post_id = st.get("uri") or f"{server}:{st.get('id')}"
            p.author_handle, p.author_id = by.get("acct", ""), by.get("url", "")
            p.created_at = to_utc_iso(st.get("created_at")) or p.created_at
        return p

    def hashtag(self, tags, since, until, limit):
        out: dict = {}
        per = max(40, limit // max(1, len(tags)))
        for server in self.servers:
            for tag in tags:
                max_id, got = None, 0
                while got < per:
                    try:
                        page = get_json(f"https://{server}/api/v1/timelines/tag/{tag}", {"limit": 40, "max_id": max_id})
                    except HTTPError as e:
                        if e.status in (401, 403, 404, 422):
                            log.warning("mastodon: %s answered %s for #%s, skipped", server, e.status, tag)
                            break
                        raise
                    if not page:
                        break
                    for st in page:
                        if st.get("reblog"):
                            continue
                        why = self.opt_out(st)
                        if why:
                            self.opted_out[why] += 1
                            continue
                        p = self.to_post(st, server, "hashtag", tag, f"{server} timelines/tag")
                        if p and in_window(p, since, until):
                            out.setdefault(p.post_id, p)
                    got += len(page)
                    max_id = page[-1]["id"]
                    if since and to_utc_iso(page[-1].get("created_at")) < since:
                        break
        return list(out.values())[: limit * max(1, len(tags))]

    def topic(self, phrases, since, until, limit):
        return []        # full-text search needs login and differs by server; hashtag() covers the tag form

    def user(self, handle, since, until, limit):
        if "@" not in handle.lstrip("@"):
            raise NotImplementedError("mastodon: give the full address, for example user@mastodon.social")
        acct = handle.lstrip("@")
        server = acct.split("@", 1)[1]
        info = get_json(f"https://{server}/api/v1/accounts/lookup", {"acct": acct})
        why = self.opt_out({"account": info})
        if why:
            self.opted_out[why] += 1
            raise NotImplementedError(f"mastodon: {acct} has opted out of collection ({why}), so the skill reads none of its posts")
        out, max_id = [], None
        while len(out) < limit:
            page = get_json(f"https://{server}/api/v1/accounts/{info['id']}/statuses", {"limit": 40, "max_id": max_id})
            if not page:
                break
            for st in page:
                why = self.opt_out(st.get("reblog") or st)
                if why:
                    self.opted_out[why] += 1
                    continue
                p = self.to_post(st, server, "user", handle, f"{server} accounts/statuses")
                if p:
                    p.author_id = p.author_id or info.get("url", "")
                    out.append(p)
            max_id = page[-1]["id"]
            if since and to_utc_iso(page[-1].get("created_at")) < since:
                break
        return [p for p in out if in_window(p, since, until)][:limit]


# --------------------------------------------------------------------------- news websites: sitemaps and full text

ROBOTS_AGENT = "titus-scraper"


def domain_of(url: str) -> str:
    host = urllib.parse.urlsplit(url or "").netloc.lower().split("@")[-1].split(":")[0]
    return host[4:] if host.startswith("www.") else host


def _domain_in(domain: str, domains) -> str | None:
    for d in domains:
        d = d.lower().lstrip(".").removeprefix("www.")
        if domain == d or domain.endswith("." + d):
            return d
    return None


class RobotsCache:
    """robots.txt per site, read as RFC 9309 sets out, with protego: wildcards (* and $), the longest
    matching rule wins, and Allow wins a tie. A 404 or another 4xx answer means the site has no rules. A
    401, 403 or 429 answer, a 5xx answer, a network failure or a refused redirect means the whole site is
    off limits until robots.txt can be read (fail closed). Up to 5 redirects are followed, each one
    checked. Rules are kept for at most 24 hours."""
    TTL = 24 * 3600

    def __init__(self):
        self.cache: dict = {}
        self.licenses: dict = {}

    def clear(self):
        self.cache.clear()
        self.licenses.clear()

    def rules(self, url: str):
        parts = urllib.parse.urlsplit(url)
        base = f"{parts.scheme}://{parts.netloc}"
        hit = self.cache.get(base)
        if hit and time.monotonic() - hit[0] < self.TTL:
            return hit[1]
        try:
            from protego import Protego
        except ImportError as e:
            raise SystemExit("titus-scraper reads robots.txt with protego. Install it: pip install protego") from e
        try:
            text = HTTP.get_text(base + "/robots.txt", tries=2, keep_raw=False)
            rules = Protego.parse(text)
            self.licenses[base] = re.findall(r"(?im)^[ \t]*license[ \t]*:[ \t]*(\S+)", text)
        except HTTPError as e:
            rules = "deny" if e.status in (0, 401, 403, 429) or e.status >= 500 else "allow"
        self.cache[base] = (time.monotonic(), rules)
        return rules

    def license(self, url: str) -> list[str]:
        """The licences a site names in robots.txt with RSL License: lines. A site that names one says how its
        content may be used, and expects users to take that licence first."""
        self.rules(url)
        parts = urllib.parse.urlsplit(url)
        return self.licenses.get(f"{parts.scheme}://{parts.netloc}", [])

    def check(self, url: str) -> tuple[bool, float]:
        """(allowed, crawl delay in seconds) for this URL and the titus-scraper user agent."""
        rules = self.rules(url)
        if isinstance(rules, str):
            return rules == "allow", 0.0
        return bool(rules.can_fetch(url, ROBOTS_AGENT)), float(rules.crawl_delay(ROBOTS_AGENT) or 0)

    def sitemaps(self, url: str) -> list[str]:
        rules = self.rules(url)
        return [] if isinstance(rules, str) else list(rules.sitemaps)


ROBOTS = RobotsCache()
TDM_PATH = "/.well-known/tdmrep.json"


def _tdm_match(location: str, path: str) -> bool:
    """A TDMRep location (a path pattern, * matches anything) against a URL path, as a prefix match."""
    loc = urllib.parse.urlsplit(location).path if "://" in location else location
    if loc in ("", "*", "/", "/*"):
        return True
    return re.match(re.escape(loc).replace(r"\*", ".*"), path) is not None


class TdmCache:
    """TDMRep, the W3C community protocol through which a site reserves its text and data mining rights
    (the opt-out in article 4 of the EU copyright directive). The file /.well-known/tdmrep.json lists path
    patterns with tdm-reservation 1 or 0. A page is reserved when any rule that matches its path reserves
    it. A missing or unreadable file means the site declared nothing there. Pages can also reserve rights
    with a tdm-reservation header or meta tag, which Http and fetch-text check. Files are kept for at most
    24 hours."""
    TTL = 24 * 3600

    def __init__(self):
        self.cache: dict = {}

    def clear(self):
        self.cache.clear()

    def rules(self, url: str) -> list:
        parts = urllib.parse.urlsplit(url)
        base = f"{parts.scheme}://{parts.netloc}"
        hit = self.cache.get(base)
        if hit and time.monotonic() - hit[0] < self.TTL:
            return hit[1]
        try:
            data = json.loads(HTTP.get_text(base + TDM_PATH, tries=2, keep_raw=False))
            rules = [r for r in data if isinstance(r, dict)] if isinstance(data, list) else []
        except (HTTPError, ValueError):
            rules = []
        self.cache[base] = (time.monotonic(), rules)
        return rules

    def reserved(self, url: str) -> str:
        """Why text and data mining of this URL is reserved, or ''."""
        path = urllib.parse.urlsplit(url).path or "/"
        for r in self.rules(url):
            if str(r.get("tdm-reservation", "0")).strip().lower() in ("1", "true") and _tdm_match(str(r.get("location", "")), path):
                pol = str(r.get("tdm-policy") or "").strip()
                return "reserves its text and data mining rights (TDMRep" + (f", policy {pol}" if pol else "") + ")"
        return ""


TDM = TdmCache()
OPT_OUT_TOKENS = ("noindex", "noarchive", "noai", "none")


def page_opt_out(headers: dict, page: str) -> str:
    """Why a page asks not to be stored or used, or ''. Reads the X-Robots-Tag header and the robots meta
    tags (for every robot, or for titus-scraper by name) for noindex, noarchive, noai or none, and the
    tdm-reservation meta tag."""
    found = []
    agent = None
    for part in str((headers or {}).get("x-robots-tag", "")).split(","):
        part = part.strip().lower()
        m = re.match(r"([\w-]+)\s*:\s*(.*)", part)
        if m and m.group(1) not in OPT_OUT_TOKENS and not m.group(1).startswith(("max-", "unavailable")):
            agent, part = m.group(1), m.group(2)
        if agent in (None, "*", ROBOTS_AGENT.lower()) and part in OPT_OUT_TOKENS:
            found.append(f"X-Robots-Tag: {part}")
    for tag in re.findall(r"<meta\b[^>]*>", page or "", flags=re.I):
        name = re.search(r"""name\s*=\s*["']?([\w-]+)""", tag, re.I)
        content = re.search(r"""content\s*=\s*["']([^"']*)["']""", tag, re.I)
        if not name or not content:
            continue
        n, c = name.group(1).lower(), content.group(1).lower()
        if n in ("robots", ROBOTS_AGENT.lower()):
            found += [f"meta {n}: {t.strip()}" for t in c.split(",") if t.strip() in OPT_OUT_TOKENS]
        elif n == "tdm-reservation" and c.strip() == "1":
            found.append("meta tdm-reservation: 1")
    return "the page asks not to be stored or mined (" + ", ".join(dict.fromkeys(found)) + ")" if found else ""


TERMS_REGISTER = Path(__file__).resolve().parent.parent / "references" / "terms_register.csv"
_TERMS: dict | None = None


def terms_register() -> dict:
    """references/terms_register.csv by domain: each outlet's terms page, the date they were read, the
    clause behind the verdict, and whether the terms forbid AI use."""
    global _TERMS
    if _TERMS is None:
        try:
            with TERMS_REGISTER.open(encoding="utf-8", newline="") as fh:
                _TERMS = {r["domain"]: r for r in csv.DictReader(fh)}
        except OSError:
            log.warning("No terms register at %s. Outlets whose terms forbid AI use can't be kept out of the reading packet.", TERMS_REGISTER)
            _TERMS = {}
    return _TERMS


def terms_entry(domain: str) -> dict | None:
    hit = _domain_in(domain or "", terms_register())
    return terms_register()[hit] if hit else None


def ai_barred_mask(df: pd.DataFrame) -> pd.Series:
    """True for items from outlets whose terms forbid AI use (ai_use=forbidden in the terms register). They
    stay in the counts, and out of everything Claude reads."""
    if not len(df):
        return pd.Series(False, index=df.index)
    doms = df["url"].fillna("").astype(str).map(domain_of)
    if "author_handle" in df:
        doms = doms.where(doms != "", df["author_handle"].fillna("").astype(str).str.lower())
    barred = {d: (terms_entry(d) or {}).get("ai_use") == "forbidden" for d in doms.unique()}
    return doms.map(barred).astype(bool)


def _slug_title(url: str) -> str:
    """'https://site/news/police-reform-bill-passes-1234.html' -> 'police reform bill passes'."""
    seg = [x for x in urllib.parse.urlsplit(url).path.split("/") if x]
    best = max(seg, key=lambda x: x.count("-") + x.count("_"), default="")
    best = re.sub(r"\.(s?html?|php|aspx?)$", "", best)
    return " ".join(w for w in re.split(r"[-_]+", best) if w and not w.isdigit()).strip()


def parse_sitemap(raw: bytes) -> tuple[list[dict], list[dict]]:
    """Returns (child sitemaps, pages). Pages carry loc, lastmod, and the news:title and
    news:publication_date of a Google News sitemap when present."""
    import xml.etree.ElementTree as ET
    local = lambda el: el.tag.rsplit("}", 1)[-1] if isinstance(el.tag, str) else ""
    raw = raw.lstrip(b"\xef\xbb\xbf \t\r\n")
    try:
        root = ET.fromstring(raw)
    except ET.ParseError:
        # some sites serve sitemaps that are not well-formed XML: read the <sitemap> and <url> blocks one by one
        text = raw.decode("utf-8", "replace")
        kids, pages = [], []
        for kind, block in re.findall(r"<(sitemap|url)\b[^>]*>(.*?)</\1>", text, flags=re.S | re.I):
            d = {}
            for name in ("loc", "lastmod", "title", "publication_date", "name"):
                m = re.search(rf"<(?:\w+:)?{name}\b[^>]*>\s*(?:<!\[CDATA\[)?(.*?)(?:\]\]>)?\s*</(?:\w+:)?{name}>", block, flags=re.S | re.I)
                if m and m.group(1).strip():
                    d[name] = html.unescape(m.group(1).strip())
            if d.get("loc"):
                (kids if kind.lower() == "sitemap" else pages).append(d)
        return kids, pages
    kids, pages = [], []
    for el in root:
        d = {}
        for c in el.iter():
            name = local(c)
            if name in ("loc", "lastmod", "title", "publication_date", "name") and (c.text or "").strip() and name not in d:
                d[name] = c.text.strip()
        if not d.get("loc"):
            continue
        (kids if local(el) == "sitemap" else pages).append(d)
    return kids, pages


class Sitemaps(Collector):
    """Sitemaps that news sites publish for search engines (GhanaWeb, most news sites). Pass --site
    DOMAIN to read the sitemaps its robots.txt lists, or --sitemap URL. Google News sitemaps carry the
    headline and publication date. Plain sitemaps carry the URL and a date, and the headline is read
    from the URL. Items are headlines (metadata-only) until fetch-text fills in the article text for
    domains you allow. Every sitemap URL is checked against robots.txt first."""
    platform, needs = "sitemaps", ()

    def __init__(self, sites=None, sitemaps=None, query: Query | None = None, max_sitemaps: int = 60):
        self.sites = [x.strip().lower().removeprefix("www.") for x in (sites or []) if x.strip()]
        self.urls = [u.strip() for u in (sitemaps or []) if u.strip()]
        if not (self.sites or self.urls):
            raise NotImplementedError("sitemaps: pass --site DOMAIN (for example ghanaweb.com) or --sitemap URL")
        self.query, self.max_sitemaps, self.robots = query, max_sitemaps, ROBOTS

    def _pages(self, start_urls, since, until):
        queue, seen, pages, n = list(start_urls), set(), [], 0
        since_d, until_d = since[:10], until[:10]
        while queue and n < self.max_sitemaps:
            url = queue.pop(0)
            if url in seen:
                continue
            seen.add(url)
            ok, delay = self.robots.check(url)
            if not ok:
                log.warning("sitemaps: robots.txt disallows %s, skipped", url)
                continue
            HTTP.host_interval[urllib.parse.urlsplit(url).netloc] = max(2.0, delay)
            try:
                body = HTTP.get_text(url, tries=3).encode("utf-8")
                if url.endswith(".gz") and body[:2] == b"\x1f\x8b":
                    body = gzip.decompress(body)
                kids, got = parse_sitemap(body)
            except Exception as e:
                log.warning("sitemaps: %s (%s)", url, e)
                continue
            n += 1
            # newest child sitemaps first; skip those last changed before the window starts
            kids = sorted(kids, key=lambda k: k.get("lastmod", ""), reverse=True)
            queue += [k["loc"] for k in kids if not k.get("lastmod") or k["lastmod"][:10] >= since_d]
            pages += got
        return [p for p in pages if since_d <= (p.get("publication_date") or p.get("lastmod") or "")[:10] < until_d or
                not (p.get("publication_date") or p.get("lastmod"))]

    def _collect(self, qtype, qval, since, until, limit, filter_query=True):
        starts = list(self.urls)
        for site in self.sites:
            found = self.robots.sitemaps(f"https://{site}/")
            found = sorted(found, key=lambda u: (0 if "news" in u.lower() else 1, u))
            starts += found or [f"https://{site}/sitemap.xml"]
        out = {}
        for d in self._pages(starts, since, until):
            title = d.get("title") or _slug_title(d["loc"])
            when = to_utc_iso(d.get("publication_date") or d.get("lastmod") or "") if (d.get("publication_date") or d.get("lastmod")) else ""
            if not title or not when:
                continue
            if filter_query and self.query is not None and not self.query.matches(title):
                continue
            out.setdefault(d["loc"], Post(platform="news", post_id=stable_id(d["loc"]), text=title, created_at=when,
                                          url=d["loc"], author_handle=domain_of(d["loc"]), author_name=d.get("name", ""),
                                          kind="headline", query_type=qtype, query_value=qval,
                                          source_endpoint="sitemap", fulltext_status="metadata-only"))
        return list(out.values())[:limit]

    def hashtag(self, tags, since, until, limit):
        return self._collect("hashtag", ",".join(tags), since, until, limit)

    def topic(self, phrases, since, until, limit):
        return []        # hashtag() applied the whole query dictionary to each headline

    def user(self, handle, since, until, limit):
        return self._collect("user", handle, since, until, limit, filter_query=False)


# English-language news outlets by country. The `news` source reads each one's public sitemaps and
# RSS feeds (no key, no login). Sites change their addresses, block automated readers or go behind a
# paywall, so some will fail in any run, and access_report.md lists them with the reason. Add any
# other site with --site DOMAIN.
WORLD_NEWS = [
    # Africa
    ("ghanaweb.com", "GhanaWeb", "Ghana"), ("3news.com", "TV3 News (3news)", "Ghana"), ("myjoyonline.com", "MyJoyOnline", "Ghana"),
    ("citinewsroom.com", "Citi Newsroom", "Ghana"), ("graphic.com.gh", "Graphic Online", "Ghana"),
    ("modernghana.com", "Modern Ghana", "Ghana"), ("gna.org.gh", "Ghana News Agency", "Ghana"),
    ("punchng.com", "Punch", "Nigeria"), ("premiumtimesng.com", "Premium Times", "Nigeria"), ("vanguardngr.com", "Vanguard", "Nigeria"),
    ("guardian.ng", "The Guardian Nigeria", "Nigeria"), ("channelstv.com", "Channels TV", "Nigeria"), ("thecable.ng", "TheCable", "Nigeria"),
    ("dailytrust.com", "Daily Trust", "Nigeria"), ("nation.africa", "Nation", "Kenya"), ("standardmedia.co.ke", "The Standard", "Kenya"),
    ("the-star.co.ke", "The Star", "Kenya"), ("monitor.co.ug", "Daily Monitor", "Uganda"), ("newvision.co.ug", "New Vision", "Uganda"),
    ("thecitizen.co.tz", "The Citizen", "Tanzania"), ("newtimes.co.rw", "The New Times", "Rwanda"),
    ("news24.com", "News24", "South Africa"), ("dailymaverick.co.za", "Daily Maverick", "South Africa"), ("iol.co.za", "IOL", "South Africa"),
    ("timeslive.co.za", "TimesLIVE", "South Africa"), ("mg.co.za", "Mail & Guardian", "South Africa"),
    ("herald.co.zw", "The Herald", "Zimbabwe"), ("newsday.co.zw", "NewsDay", "Zimbabwe"), ("lusakatimes.com", "Lusaka Times", "Zambia"),
    ("nyasatimes.com", "Nyasa Times", "Malawi"), ("mmegi.bw", "Mmegi", "Botswana"), ("namibian.com.na", "The Namibian", "Namibia"),
    ("observer.gm", "The Point / Observer", "Gambia"), ("awokonewspaper.sl", "Awoko", "Sierra Leone"),
    ("frontpageafricaonline.com", "FrontPage Africa", "Liberia"), ("addisstandard.com", "Addis Standard", "Ethiopia"),
    ("egyptindependent.com", "Egypt Independent", "Egypt"), ("english.ahram.org.eg", "Ahram Online", "Egypt"),
    ("moroccoworldnews.com", "Morocco World News", "Morocco"), ("libyaobserver.ly", "Libya Observer", "Libya"),
    ("sudantribune.com", "Sudan Tribune", "Sudan"), ("allafrica.com", "AllAfrica", "Africa (regional)"),
    ("theafricareport.com", "The Africa Report", "Africa (regional)"),
    # Americas
    ("apnews.com", "Associated Press", "United States"), ("nytimes.com", "The New York Times", "United States"),
    ("washingtonpost.com", "The Washington Post", "United States"), ("usatoday.com", "USA Today", "United States"),
    ("latimes.com", "Los Angeles Times", "United States"), ("cnn.com", "CNN", "United States"), ("foxnews.com", "Fox News", "United States"),
    ("nbcnews.com", "NBC News", "United States"), ("cbsnews.com", "CBS News", "United States"), ("abcnews.go.com", "ABC News", "United States"),
    ("npr.org", "NPR", "United States"), ("pbs.org", "PBS NewsHour", "United States"), ("politico.com", "Politico", "United States"),
    ("thehill.com", "The Hill", "United States"), ("axios.com", "Axios", "United States"), ("newsweek.com", "Newsweek", "United States"),
    ("time.com", "TIME", "United States"), ("theatlantic.com", "The Atlantic", "United States"), ("propublica.org", "ProPublica", "United States"),
    ("nationalreview.com", "National Review", "United States"), ("motherjones.com", "Mother Jones", "United States"),
    ("theroot.com", "The Root", "United States"), ("thegrio.com", "theGrio", "United States"), ("washingtontimes.com", "The Washington Times", "United States"),
    ("nypost.com", "New York Post", "United States"), ("vox.com", "Vox", "United States"), ("reuters.com", "Reuters", "International"),
    ("cbc.ca", "CBC News", "Canada"), ("globalnews.ca", "Global News", "Canada"), ("ctvnews.ca", "CTV News", "Canada"),
    ("theglobeandmail.com", "The Globe and Mail", "Canada"), ("nationalpost.com", "National Post", "Canada"),
    ("jamaica-gleaner.com", "The Gleaner", "Jamaica"), ("jamaicaobserver.com", "Jamaica Observer", "Jamaica"),
    ("guardian.co.tt", "Trinidad Guardian", "Trinidad and Tobago"), ("newsday.co.tt", "Newsday", "Trinidad and Tobago"),
    ("nationnews.com", "Nation News", "Barbados"), ("tribune242.com", "The Tribune", "Bahamas"), ("stabroeknews.com", "Stabroek News", "Guyana"),
    ("batimes.com.ar", "Buenos Aires Times", "Argentina"), ("mexiconewsdaily.com", "Mexico News Daily", "Mexico"),
    ("ticotimes.net", "The Tico Times", "Costa Rica"), ("riotimesonline.com", "The Rio Times", "Brazil"),
    # Europe
    ("bbc.co.uk", "BBC News", "United Kingdom"), ("bbc.com", "BBC News", "United Kingdom"), ("theguardian.com", "The Guardian", "United Kingdom"),
    ("independent.co.uk", "The Independent", "United Kingdom"), ("news.sky.com", "Sky News", "United Kingdom"),
    ("telegraph.co.uk", "The Telegraph", "United Kingdom"), ("thetimes.co.uk", "The Times", "United Kingdom"),
    ("ft.com", "Financial Times", "United Kingdom"), ("economist.com", "The Economist", "United Kingdom"),
    ("irishtimes.com", "The Irish Times", "Ireland"), ("rte.ie", "RTE News", "Ireland"), ("thejournal.ie", "TheJournal.ie", "Ireland"),
    ("dw.com", "DW", "Germany"), ("france24.com", "France 24", "France"), ("rfi.fr", "RFI", "France"), ("euronews.com", "Euronews", "Europe (regional)"),
    ("politico.eu", "Politico Europe", "Europe (regional)"), ("thelocal.se", "The Local", "Sweden"), ("swissinfo.ch", "Swissinfo", "Switzerland"),
    ("dutchnews.nl", "DutchNews", "Netherlands"), ("brusselstimes.com", "The Brussels Times", "Belgium"),
    ("ansa.it", "ANSA English", "Italy"), ("english.elpais.com", "El Pais English", "Spain"), ("theportugalnews.com", "The Portugal News", "Portugal"),
    ("ekathimerini.com", "Kathimerini", "Greece"), ("notesfrompoland.com", "Notes from Poland", "Poland"),
    ("kyivindependent.com", "The Kyiv Independent", "Ukraine"), ("themoscowtimes.com", "The Moscow Times", "Russia"),
    ("dailysabah.com", "Daily Sabah", "Turkey"), ("hurriyetdailynews.com", "Hurriyet Daily News", "Turkey"),
    ("yle.fi", "Yle News", "Finland"), ("icelandreview.com", "Iceland Review", "Iceland"),
    # Middle East
    ("aljazeera.com", "Al Jazeera", "Qatar"), ("thenationalnews.com", "The National", "United Arab Emirates"),
    ("gulfnews.com", "Gulf News", "United Arab Emirates"), ("khaleejtimes.com", "Khaleej Times", "United Arab Emirates"),
    ("arabnews.com", "Arab News", "Saudi Arabia"), ("timesofisrael.com", "The Times of Israel", "Israel"), ("haaretz.com", "Haaretz", "Israel"),
    ("jpost.com", "The Jerusalem Post", "Israel"), ("jordantimes.com", "The Jordan Times", "Jordan"), ("lorientlejour.com", "L'Orient Today", "Lebanon"),
    ("middleeasteye.net", "Middle East Eye", "Middle East (regional)"), ("tehrantimes.com", "Tehran Times", "Iran"),
    # Asia and Pacific
    ("thehindu.com", "The Hindu", "India"), ("indianexpress.com", "The Indian Express", "India"), ("hindustantimes.com", "Hindustan Times", "India"),
    ("timesofindia.indiatimes.com", "The Times of India", "India"), ("ndtv.com", "NDTV", "India"), ("scroll.in", "Scroll", "India"),
    ("dawn.com", "Dawn", "Pakistan"), ("tribune.com.pk", "The Express Tribune", "Pakistan"), ("thedailystar.net", "The Daily Star", "Bangladesh"),
    ("kathmandupost.com", "The Kathmandu Post", "Nepal"), ("dailymirror.lk", "Daily Mirror", "Sri Lanka"),
    ("straitstimes.com", "The Straits Times", "Singapore"), ("channelnewsasia.com", "CNA", "Singapore"), ("thestar.com.my", "The Star", "Malaysia"),
    ("malaymail.com", "Malay Mail", "Malaysia"), ("inquirer.net", "Philippine Daily Inquirer", "Philippines"), ("rappler.com", "Rappler", "Philippines"),
    ("thejakartapost.com", "The Jakarta Post", "Indonesia"), ("bangkokpost.com", "Bangkok Post", "Thailand"),
    ("vnexpress.net", "VnExpress International", "Vietnam"), ("japantimes.co.jp", "The Japan Times", "Japan"), ("japantoday.com", "Japan Today", "Japan"),
    ("koreaherald.com", "The Korea Herald", "South Korea"), ("koreatimes.co.kr", "The Korea Times", "South Korea"),
    ("scmp.com", "South China Morning Post", "Hong Kong"), ("hongkongfp.com", "Hong Kong Free Press", "Hong Kong"),
    ("chinadaily.com.cn", "China Daily", "China"), ("globaltimes.cn", "Global Times", "China"), ("taipeitimes.com", "Taipei Times", "Taiwan"),
    ("abc.net.au", "ABC News", "Australia"), ("smh.com.au", "The Sydney Morning Herald", "Australia"), ("theage.com.au", "The Age", "Australia"),
    ("rnz.co.nz", "RNZ", "New Zealand"), ("nzherald.co.nz", "NZ Herald", "New Zealand"), ("stuff.co.nz", "Stuff", "New Zealand"),
    ("fijitimes.com.fj", "The Fiji Times", "Fiji"), ("postcourier.com.pg", "Post-Courier", "Papua New Guinea"),
]
NEWS_INFO = {d: {"name": n, "country": c} for d, n, c in WORLD_NEWS}


def outlet_name(domain: str) -> str:
    hit = _domain_in(domain, NEWS_INFO)
    return NEWS_INFO[hit]["name"] if hit else domain


def outlet_country(domain: str) -> str:
    hit = _domain_in(domain, NEWS_INFO)
    return NEWS_INFO[hit]["country"] if hit else ""


def discover_feeds(page: str, base: str) -> list[str]:
    """RSS and Atom feeds a page announces with <link rel="alternate" type="application/rss+xml">."""
    out = []
    for tag in re.findall(r"<link\b[^>]*>", page or "", flags=re.I):
        if re.search(r"""type=["']application/(rss|atom)\+xml["']""", tag, re.I):
            m = re.search(r"""href=["']([^"']+)["']""", tag, re.I)
            if m:
                out.append(urllib.parse.urljoin(base, html.unescape(m.group(1))))
    return list(dict.fromkeys(out))


def news_candidates(countries=None, sites=None, registry: list | None = None) -> list[tuple[str, str, str]]:
    """(domain, outlet, country) for the outlets of the named countries plus each named site. With no
    country and no site, the list is empty: the skill never reads every outlet by default."""
    reg = list(registry) if registry is not None else WORLD_NEWS
    want = {c.strip().lower() for c in (countries or []) if c.strip()}
    if want:
        reg = [r for r in reg if "all" in want or r[2].lower() in want or any(w in r[2].lower() for w in want)]
    elif registry is None:
        reg = []
    extra = [x.strip().lower().removeprefix("www.") for x in (sites or []) if x.strip()]
    out = {r[0]: tuple(r) for r in reg}
    for d in extra:
        out.setdefault(d, (d, outlet_name(d), outlet_country(d)))
    return list(out.values())


class News(Collector):
    """English-language news sites worldwide (WORLD_NEWS, filtered with --country), plus any site given
    with --site. For each site it reads the sitemaps that robots.txt lists (news sitemaps first) and the
    RSS or Atom feeds its home page announces, and keeps the headlines and summaries that match the
    query. No key and no login. robots.txt is checked before every file. Sites are read in parallel,
    one thread per site, so each site still sees at most one request every few seconds. Sites that
    refuse, fail or have nothing readable are listed in access_report.md with the reason."""
    platform, needs = "news", ()

    def __init__(self, query: Query | None, countries=None, sites=None, sitemaps_per_site: int = 6, workers: int = 8,
                 registry: list | None = None):
        reg = news_candidates(countries, sites, registry)
        blocked = [r[0] for r in reg if (site_rule(r[0]) or ("", ""))[1] == "block"]
        if blocked:
            log.warning("news: %s blocked by SITE_RULES, skipped", ", ".join(blocked))
        reg = [r for r in reg if r[0] not in blocked]
        self.sites = [r[0] for r in reg]
        self.names = {r[0]: (r[1], r[2]) for r in reg}
        if not self.sites:
            raise NotImplementedError("news: no outlet to read. Name countries with --country or sites with --site. "
                                      f"Countries known: {', '.join(sorted({r[2] for r in WORLD_NEWS}))}")
        self.query, self.per_site, self.workers, self.robots = query, sitemaps_per_site, workers, ROBOTS
        self.site_report: dict = {}

    def _feeds(self, site, since, until):
        home = f"https://{site}/"
        ok, delay = self.robots.check(home)
        if not ok:
            return [], "robots.txt disallows the home page"
        HTTP.host_interval[urllib.parse.urlsplit(home).netloc] = max(2.0, delay)
        try:
            feeds = discover_feeds(HTTP.get_text(home, headers={"Accept": "text/html"}, tries=2, keep_raw=False), home)
        except Blocked as e:
            return [], e.why
        except HTTPError as e:
            return [], ("could not connect (network error or the site is down)" if e.status == 599 else f"home page answered HTTP {e.status}")
        feeds = [f for f in feeds if "comments" not in f.lower()][:3] or [home + "feed", home + "rss"]
        out = []
        for f in feeds:
            if not self.robots.check(f)[0]:
                continue
            try:
                items = parse_feed(HTTP.get_text(f, tries=2).encode("utf-8"), f, "news")
            except Exception:
                continue
            out += [p for p in items if in_window(p, since, until)]
            if out and f.endswith(("/feed", "/rss")):
                break
        return out, ""

    def _site(self, site, qtype, qval, since, until, limit):
        name, country = self.names.get(site, (outlet_name(site), outlet_country(site)))
        rep = {"outlet": name, "country": country, "sitemap_items": 0, "feed_items": 0,
               "matched": 0, "status": "ok", "why": ""}
        posts = []
        try:
            sm = Sitemaps([site], query=None, max_sitemaps=self.per_site)
            sm.robots = self.robots
            got = sm._collect(qtype, qval, since, until, 10 ** 6, filter_query=False)
            rep["sitemap_items"] = len(got)
            posts += got
        except Exception as e:
            rep["why"] = f"sitemaps: {e}"[:200]
        try:
            got, why = self._feeds(site, since, until)
            rep["feed_items"] = len(got)
            posts += got
            rep["why"] = (rep["why"] + " " + why).strip()
        except Exception as e:
            rep["why"] = (rep["why"] + f" feeds: {e}").strip()[:300]
        keep = {}
        for p in posts:
            if self.query is not None and qtype != "user" and not self.query.matches(p.text):
                continue
            p.platform, p.author_handle = "news", domain_of(p.url) or site
            p.author_name = p.author_name if p.source_endpoint == "sitemap" and p.author_name else name
            p.query_type, p.query_value = qtype, qval
            keep.setdefault(p.url or p.post_id, p)
        rep["matched"] = len(keep)
        if not posts:
            rep["status"] = "nothing readable"
            rep["why"] = rep["why"] or "no sitemap or feed was found or allowed"
        self.site_report[site] = rep
        return list(keep.values())[:limit]

    def _collect(self, qtype, qval, since, until, limit):
        from concurrent.futures import ThreadPoolExecutor
        with ThreadPoolExecutor(max_workers=self.workers) as ex:
            parts = list(ex.map(lambda s: self._site(s, qtype, qval, since, until, limit), self.sites))
        return [p for part in parts for p in part]

    def hashtag(self, tags, since, until, limit):
        return self._collect("hashtag", ",".join(tags), since, until, limit)

    def topic(self, phrases, since, until, limit):
        return []        # hashtag() applied the whole query dictionary to every headline

    def user(self, handle, since, until, limit):
        raise NotImplementedError("news: reads outlets, not accounts. Use --site to read one site in full.")


class Blogs(Collector):
    """Public tag feeds of blog platforms, built from the query: Medium (medium.com/feed/tag/<tag>)
    and WordPress.com (wordpress.com/tag/<tag>/feed/). No key. Add any other blog with --feed URL."""
    platform, needs = "blogs", ()

    @staticmethod
    def slugs(tags, phrases=()):
        out = [re.sub(r"[^a-z0-9]+", "-", t.lstrip("#").lower()).strip("-") for t in list(tags) + list(phrases)]
        return list(dict.fromkeys(x for x in out if x))

    def _read(self, slugs, qtype, qval, since, until, limit):
        robots, out, seen = ROBOTS, [], set()
        for slug in slugs:
            for label, url in (("medium", f"https://medium.com/feed/tag/{slug}"), ("blog", f"https://wordpress.com/tag/{slug}/feed/")):
                if not robots.check(url)[0]:
                    continue
                try:
                    items = parse_feed(HTTP.get_text(url, tries=2).encode("utf-8"), url, label)
                except Exception as e:
                    log.warning("blogs: %s (%s)", url, e)
                    continue
                for p in items:
                    if p.post_id in seen or not in_window(p, since, until):
                        continue
                    seen.add(p.post_id)
                    p.platform = "blogs"
                    p.author_handle = p.author_handle if label == "medium" else domain_of(p.url)
                    p.kind = "article" if len(p.text.split()) > 120 else "post"
                    p.query_type, p.query_value = qtype, qval
                    out.append(p)
        return out[:limit]

    def hashtag(self, tags, since, until, limit):
        return self._read(self.slugs(tags, getattr(self, "phrases", [])), "hashtag", ",".join(tags), since, until, limit)

    def topic(self, phrases, since, until, limit):
        return []

    def user(self, handle, since, until, limit):
        raise NotImplementedError("blogs: use --feed URL for one blog, such as medium.com/feed/@author")


# How to give the skill access to each source that needs a key or an approval. Shown when a source is skipped.
ACCESS_HELP = {
    "bluesky": {"vars": ["BSKY_HANDLE", "BSKY_APP_PASSWORD"],
                "get": "In the Bluesky app, open Settings, then Privacy and security, then App passwords, and create one. Use your handle (name.bsky.social) and that app password, never your main password.",
                "url": "https://bsky.app/settings/app-passwords"},
    "youtube": {"vars": ["YOUTUBE_API_KEY"],
                "get": "In Google Cloud Console, create a project, enable the YouTube Data API v3, then create an API key under Credentials.",
                "url": "https://console.cloud.google.com/apis/library/youtube.googleapis.com"},
    "guardian": {"vars": ["GUARDIAN_API_KEY"], "get": "Register for a free developer key on the Guardian Open Platform.",
                 "url": "https://open-platform.theguardian.com/access/"},
    "nytimes": {"vars": ["NYT_API_KEY"],
                "get": "Create a free account on the NYT Developer Network, add an app, and enable the Article Search and Archive APIs.",
                "url": "https://developer.nytimes.com/get-started"},
    "reddit": {"vars": ["REDDIT_CLIENT_ID", "REDDIT_CLIENT_SECRET", "REDDIT_USER_AGENT"],
               "get": "Create a script app at reddit.com/prefs/apps. New apps also need Reddit's approval for the Data API.",
               "url": "https://www.reddit.com/prefs/apps"},
    "threads": {"vars": ["THREADS_ACCESS_TOKEN"],
                "get": "Create a Meta app with the Threads API, and request the threads_keyword_search permission to search other people's posts.",
                "url": "https://developers.facebook.com/docs/threads"},
    "instagram": {"vars": ["IG_USER_ID", "IG_ACCESS_TOKEN"],
                  "get": "You need an Instagram Business or Creator account linked to a Meta app with Public Content Access approval.",
                  "url": "https://developers.facebook.com/docs/instagram-platform"},
}
SET_KEYS_HOWTO = ("On a Mac or Linux computer, run `export NAME=value` in the terminal before the commands, or add that line to "
                  "~/.zshrc (or ~/.bashrc) and open a new terminal. On Windows, run `setx NAME value` and open a new terminal. "
                  "When Claude runs the skill in a cloud environment, add the variables in that environment's settings. "
                  "Never paste a key into a chat or a report. Then run `python titus_scraper.py check` to confirm the source is ready.")


def access_report(data: Path) -> str:
    """access_report.md: every source the run could not use, why, and how to give access where that is possible."""
    rows = [json.loads(l) for l in (data / "manifest.jsonl").read_text().splitlines()] if (data / "manifest.jsonl").exists() else []
    last = {}
    for r in rows:
        last[r.get("platform")] = r
    L = ["# Sources the run could not use", "",
         "titus-scraper reads only what is public and offered to machines. When a source needs a key, a login or an "
         "approval the run doesn't have, it is skipped and the run carries on with the open sources.", ""]
    keyed = [r for r in last.values() if r.get("status") == "no key"]
    if keyed:
        L += ["## Need a key or login", ""]
        for r in keyed:
            h = ACCESS_HELP.get(r["platform"], {})
            L += [f"### {r['platform']}", "", f"Why it was skipped: {r.get('error', '')}.", "",
                  f"How to get access: {h.get('get', 'See the source documentation.')} ({h.get('url', '')})", "",
                  "Set these environment variables: " + ", ".join(f"`{v}`" for v in h.get("vars", [])) + ".", ""]
        L += [SET_KEYS_HOWTO, ""]
    unapproved = [r for r in last.values() if r.get("status") == "not approved"]
    if unapproved:
        L += ["## Not approved in sources.csv", "",
              "collect reads only the sources approved in the run folder's sources.csv. To add one, read its terms, then set "
              "decision=approve, date_checked and reviewer on its row (restricted sources also need approval_ref).", "",
              "| Source | Why |", "|---|---|"]
        L += [f"| {r['platform']} | {str(r.get('error', '')).replace('|', '/')[:220]} |" for r in unapproved]
        L.append("")
    closed = [r for r in last.values() if r.get("status") in ("not available", "error")]
    if closed:
        L += ["## Not reachable or failed", "", "| Source | Status | Why |", "|---|---|---|"]
        L += [f"| {r['platform']} | {r['status']} | {str(r.get('error', '')).replace('|', '/')[:220]} |" for r in closed]
        L.append("")
    sites = {}
    for r in rows:
        for d, v in (r.get("sites") or {}).items():
            sites[d] = v
    bad = {d: v for d, v in sites.items() if v.get("status") != "ok"}
    if sites:
        L += ["## News sites", "", f"{len(sites) - len(bad)} of {len(sites)} sites could be read. "
              f"{sum(v.get('matched', 0) for v in sites.values()):,} items matched the query.", ""]
        if bad:
            L += ["| Site | Country | Why |", "|---|---|---|"]
            L += [f"| {d} | {v.get('country', '')} | {v.get('why', '')[:200]} |" for d, v in sorted(bad.items())]
            L.append("")
    fr = data / "fetch_report.json"
    if fr.exists():
        rep = json.loads(fr.read_text())
        blocked = {d: v for d, v in rep.items() if any(k != "not-allowed" for k in v.get("skipped", {}))}
        if blocked:
            L += ["## Article pages that were not read", "",
                  "These sites refused automated reading, asked robots not to read the page, or put the article behind a paywall "
                  "or login. The skill never gets around any of these, so these items stay headlines.", "",
                  "| Site | Pages read | Skipped, by reason |", "|---|---|---|"]
            L += [f"| {d} | {v.get('fetched', 0)} | {', '.join(f'{k} {n}' for k, n in v.get('skipped', {}).items())} {v.get('why', '')} |"
                  for d, v in sorted(blocked.items())]
            L.append("")
    if len(L) <= 4:
        L += ["Every source in this run was read.", ""]
    for name, why in CLOSED.items():
        if name not in last:
            L.append(f"- {name}: not attempted. {why}")
    return "\n".join(L) + "\n"


PAYWALL_MARKERS = ["subscribe to continue", "subscribe to read", "to continue reading", "already a subscriber",
                   "create a free account to continue", "sign in to continue", "this content is for subscribers",
                   "you have reached your limit", "please enable js and disable any ad blocker", "access denied",
                   "verify you are human", "are you a robot", "captcha"]


def extract_text(page: str, url: str = "") -> tuple[str, bool]:
    """(article text, paywalled). trafilatura when installed, else the <p> text inside <article> or <main>."""
    from html.parser import HTMLParser

    class P(HTMLParser):
        SKIP = ("script", "style", "noscript", "nav", "footer", "aside", "form")

        def __init__(self):
            super().__init__()
            self.art = self.skip = 0
            self.in_p = self.in_ld = False
            self.buf, self.paras_art, self.paras_all, self.jsonld = [], [], [], []

        def handle_starttag(self, tag, attrs):
            if tag in self.SKIP:
                if tag == "script" and dict(attrs).get("type") == "application/ld+json":
                    self.in_ld, self.buf = True, []
                self.skip += 1
            elif tag in ("article", "main"):
                self.art += 1
            elif tag == "p" and not self.skip:
                self.in_p, self.buf = True, []

        def handle_endtag(self, tag):
            if tag in self.SKIP:
                if tag == "script" and self.in_ld:
                    self.jsonld.append("".join(self.buf))
                    self.in_ld = False
                self.skip = max(0, self.skip - 1)
            elif tag in ("article", "main"):
                self.art = max(0, self.art - 1)
            elif tag == "p" and self.in_p:
                t = re.sub(r"\s+", " ", "".join(self.buf)).strip()
                if len(t) > 30:
                    (self.paras_art if self.art else self.paras_all).append(t)
                self.in_p = False

        def handle_data(self, data):
            if self.in_p or self.in_ld:
                self.buf.append(data)

    p = P()
    try:
        p.feed(page)
    except Exception:
        pass
    paywalled = any(re.search(r'"isAccessibleForFree"\s*:\s*("?false"?|"False")', b) for b in p.jsonld)
    text = ""
    try:
        import trafilatura
        text = trafilatura.extract(page, url=url, include_comments=False, include_tables=False) or ""
    except ImportError:
        pass
    text = text or "\n".join(p.paras_art or p.paras_all)
    if any(m in text.lower()[:3000] for m in PAYWALL_MARKERS):
        paywalled = True
    return text, paywalled


def fetch_fulltext(df: pd.DataFrame, allowed: list[str], cache_dir: Path, min_interval=10.0, max_per_domain=200,
                   workers: int = 8):
    """Fills in article text for news and blog rows from the domains in `allowed` (fetch-text passes the
    fulltext: rows approved in sources.csv). A page is fetched only when its site is neither blocked nor
    headlines-only (SITE_RULES), robots.txt allows the URL and every redirect, TITUS_SCRAPER_CONTACT is
    set, the site names no RSL licence in robots.txt and reserves no text and data mining rights (TDMRep),
    the page carries no noindex, noarchive, noai or none signal (X-Robots-Tag or meta robots), and the page
    is not a paywall or login wall. Text cached by an earlier run is reused only after the site-level
    checks pass again. It never logs in, sends cookies, runs JavaScript or changes identity to get
    around a block. A 401, 402, 403, 429 or 451 answer stops all fetches from that domain for the run.
    Domains are read in parallel, each one slowly. Returns (updated rows, per-domain report)."""
    if not os.environ.get(CONTACT_ENV, "").strip():
        raise SystemExit(f"Set {CONTACT_ENV} to your email or website first, so each request says who is asking.")
    if not allowed:
        raise SystemExit("fetch-text reads only the domains approved in sources.csv (rows fulltext:<domain>).")
    robots = ROBOTS
    cache_dir.mkdir(parents=True, exist_ok=True)
    news = df[df["kind"].isin(["headline", "summary", "article", "post"]) & df["url"].str.startswith("http")
              & ~df["fulltext_status"].isin(["api", "fetched", "feed"])
              & ~df["platform"].isin(["bluesky", "mastodon", "youtube", "reddit", "threads", "instagram"])]
    groups: dict = {}
    for r in news.itertuples():
        groups.setdefault(domain_of(r.url), []).append(r)

    def run(dom, items):
        rep, rows, fetched = {"fetched": 0, "skipped": Counter()}, [], 0
        stopped = None
        for r in items:
            status = None
            refusal = policy_refusal(r.url, "fetch-text")
            if refusal:
                status, rep["why"] = "blocked:site-policy", refusal
            elif not _domain_in(dom, allowed):
                rep["skipped"]["not-allowed"] += 1
                continue
            elif stopped:
                rep["skipped"]["stopped-after-block"] += 1
                continue
            elif fetched >= max_per_domain:
                status = "blocked:per-domain-cap"
            if status is None:
                cached = cache_dir / f"{stable_id(r.url)}.txt"
                ok, delay = robots.check(r.url)
                lic = robots.license(r.url) if ok else []
                tdm = TDM.reserved(r.url) if ok and not lic else ""
                if not ok:
                    status = "blocked:robots.txt"
                elif lic:
                    status, rep["why"] = "blocked:rsl-licence", (f"{dom} names a licence for its content in robots.txt ({lic[0]}). "
                                                                 "Read it and take the licence it asks for before reading its pages")
                elif tdm:
                    status, rep["why"] = "blocked:tdm-reservation", f"{dom} {tdm}"
                elif cached.exists():
                    text = cached.read_text(encoding="utf-8")
                else:
                    HTTP.host_interval[urllib.parse.urlsplit(r.url).netloc] = max(min_interval, delay)
                    try:
                        page, rh = HTTP.get_page(r.url, headers={"Accept": "text/html"}, tries=2)
                    except Blocked as e:       # a redirect led to a blocked site or a disallowed URL
                        status = {"robots": "blocked:robots.txt", "tdm": "blocked:tdm-reservation"}.get(e.kind, "blocked:site-policy")
                    except HTTPError as e:
                        status = f"blocked:http-{e.status}"
                        if e.status in (401, 402, 403, 429, 451):
                            stopped = e.status
                            log.warning("%s answered %s. No more fetches from it this run.", dom, e.status)
                    else:
                        opt = page_opt_out(rh, page)
                        text, paywalled = extract_text(page, r.url)
                        if opt:
                            status, rep["why"] = "blocked:opt-out", opt
                        elif paywalled or len(text.split()) < 80:
                            status = "blocked:paywall-or-too-short"
                        else:
                            cached.write_text(text, encoding="utf-8")
                if status is None:
                    title = str(r.text).split("\n", 1)[0]
                    row = df.loc[r.Index].to_dict()
                    row.update(text=f"{title}\n{text}", kind="article", fulltext_status="fetched",
                               collected_at=datetime.now(timezone.utc).isoformat())
                    rows.append(row)
                    fetched += 1
                    rep["fetched"] += 1
                    continue
            rep["skipped"][status.split(":", 1)[1]] += 1
            row = df.loc[r.Index].to_dict()
            row.update(fulltext_status=status, collected_at=datetime.now(timezone.utc).isoformat())
            rows.append(row)
        return dom, rows, rep

    from concurrent.futures import ThreadPoolExecutor
    with ThreadPoolExecutor(max_workers=max(1, workers)) as ex:
        results = list(ex.map(lambda kv: run(*kv), groups.items()))
    rows, report = [], {}
    for dom, rws, rp in results:
        rows += rws
        report[dom] = {"fetched": rp["fetched"], "skipped": dict(rp["skipped"]), **({"why": rp["why"]} if "why" in rp else {})}
    return rows, report


class Closed(Collector):
    """X, LinkedIn, Facebook and TikTok: no free official route to public posts for general use."""
    needs = ()

    def __init__(self, name):
        self.platform = name


COLLECTORS = {"bluesky": Bluesky, "mastodon": Mastodon, "youtube": YouTube, "reddit": Reddit, "threads": Threads,
              "instagram": Instagram, "gdelt": Gdelt, "guardian": Guardian, "nytimes": NYTimes, "feeds": Feeds,
              "sitemaps": Sitemaps, "news": News, "blogs": Blogs}
# What collect tries when --platforms is not given. Each source still needs an approved row in sources.csv,
# news needs --country or --site, and sources without a key are skipped and reported.
DEFAULT_PLATFORMS = "news,blogs,gdelt,mastodon,bluesky,nytimes,threads"
# Sources that need more than an ordinary approval: approval_ref in sources.csv must name the approval or
# licence. None of them is in DEFAULT_PLATFORMS.
RESTRICTED = {
    "reddit": "Reddit's Responsible Builder Policy says research use needs approval through Reddit for Researchers. "
              "Put that approval's reference in approval_ref.",
    "youtube": "The YouTube API Services terms limit how long API data is stored, so the skill deletes YouTube items "
               "30 days after collection. Put the name of whoever approved this use (an ethics board or a supervisor) in approval_ref.",
    "guardian": "The Guardian Open Platform terms (clause 6(g)) forbid text and data mining and require deleting content "
                "within 24 hours. Use it only under a written licence from the Guardian that allows this study, named in approval_ref.",
}
# Ready-made approvals that init --approve can write, each with the conditions that come with it.
PRESET_APPROVALS = {
    "gdelt": "Preset approval: GDELT DOC 2.0 headlines, links and dates only (no article text), one request every 6 seconds.",
    "mastodon": "Preset approval: public hashtag timelines and public accounts on the named servers. Honour each author's "
                "opt-out and deletion requests (purge --author).",
    "bluesky": "Preset approval: public posts through the official API with your own app password. Remove deleted posts and "
               "honour deletion requests (purge --author).",
}
API_HOSTS = {"bluesky": ["bsky.social"], "youtube": ["www.googleapis.com"], "reddit": ["www.reddit.com", "oauth.reddit.com"],
             "threads": ["graph.threads.com"], "instagram": ["graph.facebook.com"], "gdelt": ["api.gdeltproject.org"],
             "guardian": ["content.guardianapis.com"], "nytimes": ["api.nytimes.com"], "blogs": ["medium.com", "wordpress.com"]}
CLOSED = {"x": "X's API search is paid, and the free tier does not cover research search.",
          "linkedin": "LinkedIn restricts reading member posts to approved partners.",
          "facebook": "Meta offers public-post access only through approved research programs.",
          "tiktok": "TikTok's Research API is open only to approved researchers at eligible organisations."}

# --------------------------------------------------------------------------- cleaning

NEWS_KINDS = {"headline", "article", "summary"}
URL_RE = re.compile(r"https?://\S+|www\.\S+")
MENTION_RE = re.compile(r"(?<!\w)@[\w.]+")
INVISIBLE_RE = re.compile("[\u200b-\u200f\u202a-\u202e\u2060-\u2064\ufeff\u00ad]")
_LANG = None


def normalise(text: str) -> str:
    t = unicodedata.normalize("NFKC", html.unescape(text or ""))
    t = MENTION_RE.sub("@user", URL_RE.sub("http", INVISIBLE_RE.sub("", t)))   # the cardiffnlp convention
    return re.sub(r"\s+", " ", t).strip()


def dedup_key(text: str) -> str:
    t = re.sub(r"http|@user|#", " ", normalise(text).lower())
    return hashlib.md5(re.sub(r"\s+", " ", re.sub(r"[^a-z0-9 ]+", " ", t)).strip().encode()).hexdigest()


def is_english(texts: list[str], min_conf=0.5) -> list[bool]:
    """Offline language ID with lingua. Posts under 3 words are kept, since ID is unreliable there."""
    global _LANG
    from lingua import Language, LanguageDetectorBuilder
    _LANG = _LANG or LanguageDetectorBuilder.from_all_languages().with_preloaded_language_models().build()
    keep = []
    for t in texts:
        clean = URL_RE.sub(" ", MENTION_RE.sub(" ", t or ""))
        # Confidence is spread across related languages, so short English posts can score under 0.5
        # while English is still the top guess. Keep a post when either test says English.
        keep.append(len(clean.split()) < 3 or _LANG.detect_language_of(clean) == Language.ENGLISH
                    or _LANG.compute_language_confidence(clean, Language.ENGLISH) >= min_conf)
    return keep


HASHTAG_RE = re.compile(r"(?<![\w#])#(\w+)")


def _shingles(t: str, k: int = 5) -> set:
    t = re.sub(r"\s+", " ", URL_RE.sub("", MENTION_RE.sub("", (t or "").lower()))).strip()
    return {t[i:i + k] for i in range(len(t) - k + 1)} if len(t) > k else ({t} if t else set())


def near_duplicates(texts: list[str], threshold=0.85, num_perm=64, bands=16, seed=7) -> list[int]:
    """MinHash with banding (no extra packages). For each text, the index of an earlier text it nearly
    copies (Jaccard similarity of 5-character shingles >= threshold), or -1. Catches syndicated
    articles and lightly edited copy-paste posts that exact matching misses."""
    import numpy as np
    rng = np.random.default_rng(seed)
    prime = np.uint64((1 << 61) - 1)
    a = rng.integers(1, (1 << 61) - 1, size=num_perm, dtype=np.uint64)
    b = rng.integers(0, (1 << 61) - 1, size=num_perm, dtype=np.uint64)
    rows = num_perm // bands
    sets = [_shingles(t) for t in texts]
    buckets, dup = {}, [-1] * len(texts)
    for i, sh in enumerate(sets):
        if len(sh) < 8:
            continue
        h = np.array([zlib.crc32(x.encode("utf-8")) for x in sh], dtype=np.uint64)
        with np.errstate(over="ignore"):
            sig = ((np.outer(h, a) + b) % prime).min(axis=0)
        keys = [(j, sig[j * rows:(j + 1) * rows].tobytes()) for j in range(bands)]
        for j in sorted({c for k in keys for c in buckets.get(k, ())}):
            if len(sh & sets[j]) / len(sh | sets[j]) >= threshold:
                dup[i] = j if dup[j] == -1 else dup[j]
                break
        if dup[i] == -1:
            for k in keys:
                buckets.setdefault(k, []).append(i)
    return dup


def prepare(df, query: Query | None, start=None, end=None, english_only=True, near_dup=0.85):
    """Returns (analysis table, step log, details). The step log counts rows left after each step and
    goes in the report. Details hold the per-source exclusion table and the reposts, which are set
    aside from text analysis (a repost repeats someone else's words) but counted in the descriptives.
    Text versions: text (raw, unchanged), text_norm (Unicode and spacing fixed), text_clean (for models:
    links and handles replaced with tokens)."""
    steps = {"collected": len(df)}
    excl = pd.DataFrame(0, index=sorted(df["platform"].unique()) if len(df) else [],
                        columns=["collected", "empty", "outside_window", "off_topic", "reposts", "exact_duplicates",
                                 "near_duplicates", "not_english", "kept"])
    excl["collected"] = df["platform"].value_counts()

    def drop(mask, col):
        excl[col] = excl[col].add(df.loc[mask, "platform"].value_counts(), fill_value=0)
        return df[~mask]

    df = drop(df["text"].fillna("").str.strip() == "", "empty").copy()
    steps["after_empty_removed"] = len(df)
    if start or end:
        mask = pd.Series(False, index=df.index)
        if start:
            mask |= df["created_at"] < pd.Timestamp(start, tz="UTC")
        if end:
            mask |= df["created_at"] >= pd.Timestamp(end, tz="UTC")
        df = drop(mask, "outside_window")
        steps["after_date_window"] = len(df)
    df = df.copy()
    if query is not None and query.kind != "user":
        m = df["text"].map(query.match)
        df["match_type"], df["matched_rule"] = m.str[0], m.str[1]
        parents = set(df.loc[df["match_type"] != "", "post_id"])
        ride = (df["match_type"] == "") & df["parent_id"].isin(parents)        # comments ride with their post
        df.loc[ride, "match_type"] = "reply-to-match"
        df = drop(df["match_type"] == "", "off_topic")
        steps["after_relevance_filter"] = len(df)
    else:
        df["match_type"], df["matched_rule"] = "account", ""
    reposts = df[df["kind"] == "repost"].copy()
    df = drop(df["kind"] == "repost", "reposts")
    if len(reposts):
        steps["after_reposts_set_aside"] = len(df)
    df = df.copy()
    df["text_norm"] = df["text"].map(lambda t: re.sub(r"\s+", " ", INVISIBLE_RE.sub("", unicodedata.normalize("NFKC", html.unescape(t or "")))).strip())
    df["text_clean"] = df["text"].map(normalise)
    df["dedup_key"] = df["text_clean"].map(dedup_key)
    df = df.sort_values("created_at", kind="stable")
    df["copies"] = df.groupby("dedup_key")["post_id"].transform("size")
    df = drop(df.duplicated("dedup_key", keep="first"), "exact_duplicates")
    steps["after_exact_dedup"] = len(df)
    if near_dup and len(df) > 1:
        dups = near_duplicates(df["text_clean"].tolist(), threshold=near_dup)
        df = df.reset_index(drop=True)
        extra = Counter()
        for i, j in enumerate(dups):
            if j >= 0:
                extra[j] += int(df.at[i, "copies"])
        df["copies"] = df["copies"] + pd.Series(extra, dtype="int64").reindex(df.index, fill_value=0)
        df = drop(pd.Series([d >= 0 for d in dups], index=df.index), "near_duplicates")
        steps["after_near_dedup"] = len(df)
    if english_only and len(df):
        keep = pd.Series(is_english(df["text"].tolist()), index=df.index)
        df = drop(~keep, "not_english")
        steps["after_english_filter"] = len(df)
    df = df.reset_index(drop=True)
    df["uid"] = df["platform"] + ":" + df["post_id"].astype(str)
    df["hashtags"] = df["text"].map(lambda t: sorted({h.lower() for h in HASHTAG_RE.findall(t or "")}))
    df["n_words"] = df["text_norm"].str.split().map(len)
    df["author_key"] = df["author_id"].where(df["author_id"] != "", df["author_handle"])
    flags = pd.Series("", index=df.index)
    if len(df) and (query is None or query.kind != "user"):
        social = ~df["kind"].isin(NEWS_KINDS)
        per_author = df.groupby(["platform", "author_key"])["uid"].transform("count")
        cutoff = max(20, per_author[social].quantile(0.99)) if social.sum() > 100 else 10 ** 9
        flags = flags.where(~(social & (per_author >= cutoff)), "high-volume")
        url_only = df["text"].fillna("").str.replace(URL_RE, "", regex=True).str.replace(r"[\W_]+", "", regex=True).str.len() < 3
        flags = flags.where(~url_only, (flags + " url-only").str.strip())
        stuffed = (df["hashtags"].map(len) >= 6) & (df["hashtags"].map(len) >= 0.5 * df["n_words"].clip(lower=1))
        flags = flags.where(~stuffed, (flags + " hashtag-stuffing").str.strip())
    df["flags"] = flags
    df["suspect"] = df["flags"] != ""
    steps["flagged_suspect (kept, reported apart)"] = int(df["suspect"].sum())
    excl["kept"] = df["platform"].value_counts()
    excl = excl.fillna(0).astype(int)
    return df, steps, {"excluded": excl, "reposts": reposts}


def _norm_url(u: str) -> str:
    parts = urllib.parse.urlsplit(u or "")
    return (domain_of(u) + parts.path.rstrip("/")).lower()


def audit(raw: pd.DataFrame, df: pd.DataFrame, details: dict, data_dir: Path) -> dict:
    """The data-quality report, written before any model runs: what came in from each source and
    each day, what each cleaning step removed, missing fields, failed requests, how concentrated the
    data is in a few accounts or outlets, and how far different sources found the same articles."""
    data_dir = Path(data_dir)
    rep: dict = {}
    excl = details["excluded"]
    rep["by_source"] = excl.reset_index(names="source").to_dict("records")
    rep["dates_by_source"] = {p: {"first": str(g["created_at"].min())[:10], "last": str(g["created_at"].max())[:10],
                                  "kept": int(len(g))} for p, g in df.groupby("platform")}
    if len(df):
        span = (df["created_at"].max() - df["created_at"].min()).days
        freq = "D" if span < 21 else "W"
        per_bin = df.set_index("created_at").resample(freq)["uid"].count()
        rep["volume"] = {"bin": "day" if freq == "D" else "week", "bins": int(len(per_bin)),
                         "empty_bins": int((per_bin == 0).sum()), "max": int(per_bin.max()),
                         "median": float(per_bin.median())}
    rep["match_type"] = df["match_type"].value_counts().to_dict() if "match_type" in df else {}
    fields = ["created_at", "author_handle", "author_id", "url", "like_count", "reply_count", "share_count"]
    rep["missing_share_by_source"] = {
        p: {f: round(float((g[f].isna() | (g[f].astype(str).isin(["", "NaT", "None", "nan"]))).mean()), 3) for f in fields if f in g}
        for p, g in df.groupby("platform")}
    social = df[~df["kind"].isin(NEWS_KINDS)]
    if len(social):
        per = social.groupby(["platform", "author_key"]).size()
        rep["posts_per_author"] = {p: {"authors": int(len(s)), "median": float(s.median()), "p90": float(s.quantile(0.9)),
                                        "max": int(s.max()), "share_from_top_1pct": round(float(s.nlargest(max(1, len(s) // 100)).sum() / s.sum()), 3),
                                        "share_from_top_10": round(float(s.nlargest(10).sum() / s.sum()), 3)}
                                   for p, s in per.groupby(level=0)}
    news = df[df["kind"].isin(NEWS_KINDS)]
    if len(news):
        outlets = news["author_handle"].replace("", "unknown").value_counts()
        rep["outlets"] = {"count": int(len(outlets)), "top": outlets.head(15).to_dict(),
                          "share_from_top_5": round(float(outlets.head(5).sum() / outlets.sum()), 3)}
        rep["fulltext_status"] = news["fulltext_status"].replace("", "unknown").value_counts().to_dict()
    # overlap: the same article URL found by more than one source or endpoint
    r = raw[raw["url"].fillna("").str.startswith("http")].copy()
    if len(r):
        r["src"] = r["platform"] + "/" + r["source_endpoint"].fillna("").str.split().str[0].fillna("")
        r["u"] = r["url"].map(_norm_url)
        sets = r.groupby("u")["src"].agg(lambda x: tuple(sorted(set(x))))
        rep["source_overlap"] = {" + ".join(k): int(v) for k, v in Counter(s for s in sets if len(s) > 1).most_common(10)}
    rep["suspect_flags"] = df["flags"].replace("", pd.NA).dropna().str.split().explode().value_counts().to_dict() if len(df) else {}
    req = data_dir / "requests.jsonl"
    if req.exists():
        rows = pd.DataFrame([json.loads(l) for l in req.read_text().splitlines() if l.strip()])
        if len(rows):
            rows["ok"] = rows["status"] < 400
            rep["requests"] = {src: {"calls": int(len(g)), "failed": int((~g["ok"]).sum()),
                                     "statuses": {str(k): int(v) for k, v in g["status"].value_counts().items()},
                                     "records": int(pd.to_numeric(g.get("records"), errors="coerce").fillna(0).sum())}
                               for src, g in rows.groupby("source")}
    man = data_dir / "manifest.jsonl"
    if man.exists():
        rep["collection_runs"] = [{k: m.get(k) for k in ("platform", "status", "rows", "error", "started")}
                                  for m in map(json.loads, man.read_text().splitlines()) if m.get("platform")]
    rep["warnings"] = _audit_warnings(rep, df)
    return rep


def _audit_warnings(rep, df) -> list[str]:
    w = []
    for p, v in (rep.get("posts_per_author") or {}).items():
        if v["share_from_top_10"] >= 0.3 and v["authors"] >= 20:
            w.append(f"On {p}, 10 accounts wrote {v['share_from_top_10']:.0%} of the posts. Report results with and without them.")
    o = rep.get("outlets") or {}
    if o.get("share_from_top_5", 0) >= 0.5 and o.get("count", 0) >= 10:
        w.append(f"Five outlets supplied {o['share_from_top_5']:.0%} of the news items.")
    for src, v in (rep.get("requests") or {}).items():
        if v["calls"] and v["failed"] / v["calls"] >= 0.1:
            w.append(f"{src}: {v['failed']} of {v['calls']} requests failed. Coverage there may have gaps.")
    for m in rep.get("collection_runs") or []:
        if m["status"] != "ok":
            w.append(f"{m['platform']}: {m['status']} ({(m.get('error') or '')[:80]}).")
    vol = rep.get("volume") or {}
    if vol.get("bins") and vol.get("empty_bins", 0) / vol["bins"] >= 0.25:
        w.append(f"{vol['empty_bins']} of {vol['bins']} {vol['bin']}s have no posts. Check for collection gaps before reading trends.")
    for row in rep.get("by_source", []):
        if row["collected"] and row["off_topic"] / row["collected"] >= 0.5:
            w.append(f"{row['source']}: {row['off_topic']} of {row['collected']} items did not match the query. Check the search strings.")
    return w


def audit_markdown(rep: dict, steps: dict) -> str:
    L = ["# Data-quality audit", "", "Read this before any model result. Fix what it flags, or report it as a limit.", ""]
    if rep.get("warnings"):
        L += ["## Warnings", ""] + [f"- {x}" for x in rep["warnings"]] + [""]
    L += ["## Cleaning steps", ""] + [f"- {k.replace('_', ' ')}: {v:,}" for k, v in steps.items()] + [""]
    L += ["## By source", "", "| source | collected | empty | outside window | off topic | reposts | exact dup | near dup | not English | kept |",
          "|---|---|---|---|---|---|---|---|---|---|"]
    L += [f"| {r['source']} | " + " | ".join(f"{r[c]:,}" for c in ("collected", "empty", "outside_window", "off_topic", "reposts",
                                                                  "exact_duplicates", "near_duplicates", "not_english", "kept")) + " |"
          for r in rep["by_source"]] + [""]
    for key, title in (("match_type", "How kept items matched the query"), ("dates_by_source", "Dates by source"),
                       ("volume", "Volume"), ("posts_per_author", "Posts per author"), ("outlets", "News outlets"),
                       ("fulltext_status", "Article text status"), ("source_overlap", "Same URL found by several sources"),
                       ("suspect_flags", "Suspect flags (kept, reported apart)"), ("missing_share_by_source", "Share of missing fields"),
                       ("requests", "Requests by source")):
        if rep.get(key):
            L += [f"## {title}", "", "```", json.dumps(rep[key], indent=1, default=str), "```", ""]
    return "\n".join(L)

# --------------------------------------------------------------------------- lexical analysis

TOKEN_RE = re.compile(r"#?[a-z][a-z'\-]{1,}")
EXTRA_STOP = {"http", "user", "amp", "rt", "just", "like", "get", "got", "im", "dont", "it's", "i'm", "don't", "alt",
              # pieces of web links
              "https", "www", "com", "org", "net", "html", "htm", "php", "utm", "amp;", "href"}


def query_stopwords(value: str, aliases=()) -> set[str]:
    words = set(re.findall(r"[a-z]+", value.lower())) | {w.lower() for w in re.findall(r"[A-Z]?[a-z]+", value)}
    return words | {value.lstrip("#").lower()} | {a.lstrip("#").lower() for a in aliases}


def tokens(text: str, qwords: set[str]) -> list[str]:
    from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS
    stop = ENGLISH_STOP_WORDS | EXTRA_STOP | qwords
    return [t for t in TOKEN_RE.findall((text or "").lower()) if t.lstrip("#") not in stop and len(t.lstrip("#")) > 2]


def term_counts(df, qwords) -> Counter:
    return Counter(t for text in df["text_clean"] for t in tokens(text, qwords))


def cooccurrence_network(df, qwords, min_count=5, top_nodes=150):
    """Nodes are words. An edge joins two words used in the same post: weight = posts, npmi = association."""
    import networkx as nx
    from networkx.algorithms.community import greedy_modularity_communities
    docs = [set(tokens(t, qwords)) for t in df["text_clean"]]
    n = max(len(docs), 1)
    freq = Counter(w for d in docs for w in d)
    keep = {w for w, _ in freq.most_common(top_nodes)}
    pairs = Counter(p for d in docs for p in itertools.combinations(sorted(d & keep), 2))
    g = nx.Graph()
    for (a, b), c in pairs.items():
        if c >= min_count:
            pab = c / n
            npmi = 1.0 if pab >= 1 else math.log(pab / ((freq[a] / n) * (freq[b] / n))) / -math.log(pab)
            g.add_edge(a, b, weight=c, npmi=round(npmi, 4))
    for w in g.nodes:
        g.nodes[w]["count"] = freq[w]
    if g.number_of_nodes():
        for i, comm in enumerate(greedy_modularity_communities(g, weight="weight")):
            for w in comm:
                g.nodes[w]["community"] = i
    return g

def word_flow_network(df, qwords, window: int = 3, min_count: int = 3, top_nodes: int = 80, top_edges: int = 220):
    """A directed word network built from every collected text: posts, comments, headlines, article
    text, blog posts and video transcripts, pooled across the whole dataset. An arrow A -> B counts how
    often B follows A within `window` words (stop words removed), so arrows show the order in which
    people put words together, and the weight is how often that happens across all the data."""
    import networkx as nx
    from networkx.algorithms.community import greedy_modularity_communities
    seqs = [tokens(t, qwords) for t in df["text_clean"]]
    freq = Counter(w for sq in seqs for w in sq)
    keep = {w for w, _ in freq.most_common(top_nodes)}
    edges = Counter()
    for sq in seqs:
        for i, a in enumerate(sq):
            if a not in keep:
                continue
            for b in sq[i + 1:i + 1 + window]:
                if b in keep and b != a:
                    edges[(a, b)] += 1
    g = nx.DiGraph()
    for (a, b), c in sorted(edges.items(), key=lambda kv: -kv[1])[:top_edges]:
        if c >= min_count:
            g.add_edge(a, b, weight=c)
    for w in g.nodes:
        g.nodes[w]["count"] = freq[w]
    if g.number_of_nodes():
        for i, comm in enumerate(greedy_modularity_communities(g.to_undirected(), weight="weight")):
            for w in comm:
                g.nodes[w]["community"] = i
    return g


def flow_edges(g, top=40) -> list[dict]:
    rows = [{"from": a, "to": b, "count": d["weight"], "reverse": g[b][a]["weight"] if g.has_edge(b, a) else 0}
            for a, b, d in g.edges(data=True)]
    return sorted(rows, key=lambda r: -r["count"])[:top]


NEWS_PLATFORMS = {"news", "nytimes", "guardian", "gdelt"}
SOCIAL_PLATFORMS = {"bluesky", "mastodon", "youtube", "reddit", "threads", "instagram"}


def is_news(df) -> pd.Series:
    return df["platform"].isin(NEWS_PLATFORMS) | (df["kind"].isin(NEWS_KINDS) & ~df["platform"].isin(SOCIAL_PLATFORMS | {"blogs", "medium"}))


def is_blog(df) -> pd.Series:
    return df["platform"].isin(["blogs", "medium", "web"]) & ~is_news(df)


def _title(text) -> str:
    return re.sub(r"\s+", " ", str(text).split("\n", 1)[0]).strip()


def main_headlines(df, qwords=frozenset(), top: int = 15, sim: float = 0.4, days: int = 5) -> list[dict]:
    """The stories the news covered most. Headlines that share most of their words (Jaccard 0.4 or more,
    at least two shared words) and appeared within `days` days of each other are one story. Stories are
    ranked by how many outlets ran them, then by items."""
    from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS
    news = df[is_news(df)].copy()
    if news.empty:
        return []
    news["title"] = news["text"].map(_title)
    news = news[news["title"].str.len() > 15].reset_index(drop=True)
    stop = set(ENGLISH_STOP_WORDS) | set(qwords) | {"says", "said", "new", "news", "video", "live", "update", "watch"}
    words = [{w for w in re.findall(r"[a-z][a-z'-]+", t.lower()) if w not in stop and len(w) > 2} for t in news["title"]]
    day = news["created_at"].dt.floor("D")
    parent = list(range(len(news)))

    def find(i):
        while parent[i] != i:
            parent[i] = parent[parent[i]]
            i = parent[i]
        return i
    index: dict = {}
    for i, ws in enumerate(words):
        for w in ws:
            index.setdefault(w, []).append(i)
    for w, ids in index.items():
        if len(ids) > 400:          # a word in hundreds of headlines says little about which story it is
            continue
        for x, i in enumerate(ids):
            for j in ids[x + 1:]:
                if find(i) == find(j):
                    continue
                inter = len(words[i] & words[j])
                if inter >= 2 and inter / max(len(words[i] | words[j]), 1) >= sim and abs((day[i] - day[j]).days) <= days:
                    parent[find(i)] = find(j)
    news["story"] = [find(i) for i in range(len(news))]
    out = []
    for _, g in news.groupby("story"):
        g = g.sort_values("created_at")
        outlets = g["author_handle"].replace("", pd.NA).dropna()
        common = g["title"].str.lower().value_counts()
        rep_title = g.loc[g["title"].str.lower() == common.index[0], "title"].iloc[0] if common.iloc[0] > 1 else g["title"].iloc[0]
        out.append({"headline": rep_title, "outlets": int(outlets.nunique()), "items": len(g),
                    "first": f"{g['created_at'].min():%Y-%m-%d}", "last": f"{g['created_at'].max():%Y-%m-%d}",
                    "countries": sorted({c for c in g["author_handle"].map(outlet_country) if c}),
                    "links": [{"outlet": outlet_name(r.author_handle) if r.author_handle else "", "title": r.title,
                               "date": f"{r.created_at:%Y-%m-%d}", "url": r.url} for r in g.drop_duplicates("author_handle").head(6).itertuples()]})
    return sorted(out, key=lambda d: (-d["outlets"], -d["items"], d["first"]))[:top]


def source_list(df) -> pd.DataFrame:
    """Every news article and blog post in the analysed data, with its outlet, country and link.
    Social posts by ordinary users are not listed one by one (see references/ethics.md)."""
    keep = df[is_news(df) | is_blog(df)].copy()
    if keep.empty:
        return pd.DataFrame(columns=["date", "type", "outlet", "domain", "country", "title", "url", "text_status"])
    keep["date"] = keep["created_at"].dt.strftime("%Y-%m-%d")
    keep["type"] = ["news" if n else "blog" for n in is_news(keep)]
    keep["domain"] = keep["url"].map(domain_of).where(keep["url"].str.startswith("http"), keep["author_handle"])
    keep["outlet"] = [outlet_name(d) if t == "news" else (a or d) for d, t, a in zip(keep["domain"], keep["type"], keep["author_name"])]
    keep["country"] = keep["domain"].map(outlet_country)
    keep["title"] = keep["text"].map(_title)
    keep["text_status"] = keep["fulltext_status"]
    return keep.sort_values(["date", "outlet"])[["date", "type", "outlet", "domain", "country", "title", "url", "text_status"]]

def query_terms(meta: dict) -> list[str]:
    """The query's words and phrases, lower case, for scoring how relevant an item is."""
    terms = [meta.get("value", "")] + list(meta.get("aliases") or [])
    out = []
    for t in terms:
        for part in str(t).split(","):
            part = part.strip().lstrip("#").lower()
            if part:
                out.append(part)
                spaced = re.sub(r"(?<=[a-z])(?=[A-Z])", " ", str(t).strip().lstrip("#")).lower()
                if spaced != part:
                    out.append(spaced)
    return list(dict.fromkeys(out))


def relevant_sources(df, meta: dict, n: int = 10) -> pd.DataFrame:
    """The n most relevant news articles and blog posts, one per outlet first. An item scores higher when its
    headline names the query (three points per term), when its text does (one point per mention, up to five),
    and when it belongs to a story that several outlets ran. n = 0 returns every item, ranked."""
    sl = source_list(df)
    sl = sl[sl["url"].astype(str).str.startswith("http")]
    if sl.empty:
        return sl.assign(score=[])
    terms = query_terms(meta)
    text = df.loc[sl.index, "text"].astype(str).str.lower()
    title = sl["title"].astype(str).str.lower()
    score = pd.Series(0.0, index=sl.index)
    for t in terms:
        score += 3 * title.str.count(re.escape(t)).clip(upper=1) + text.str.count(re.escape(t)).clip(upper=5) / 5
    try:
        heads = main_headlines(df, query_stopwords(meta.get("value", ""), meta.get("aliases", [])), top=50)
        cover = {l["url"]: h["outlets"] for h in heads for l in h["links"]}
        score += sl["url"].map(cover).fillna(0).clip(upper=10) / 2
    except Exception:
        pass
    sl = sl.assign(score=score).sort_values(["score", "date"], ascending=[False, False])
    if n <= 0:
        return sl
    first = sl.drop_duplicates("outlet")
    picked = pd.concat([first, sl.drop(first.index)]).head(n)
    return picked

# --------------------------------------------------------------------------- videos

VIDEO_EXT = (".mp4", ".m3u8", ".webm", ".mov", ".m4v")


def video_candidates(df) -> pd.DataFrame:
    """Posts that carry a video. Direct video files and streams (Mastodon attachments, Bluesky video
    playlists, links to .mp4 files) can be transcribed. YouTube videos can't: YouTube's terms bar
    downloading them, and its caption download needs the channel owner's permission."""
    rows = []
    for r in df.itertuples():
        media = r.media_urls if isinstance(r.media_urls, list) else json.loads(r.media_urls or "[]") if isinstance(r.media_urls, str) else []
        links = [m for m in media if isinstance(m, str) and (m.lower().split("?")[0].endswith(VIDEO_EXT) or "video.bsky.app" in m)]
        links += [u for u in URL_RE.findall(str(r.text)) if u.lower().split("?")[0].endswith(VIDEO_EXT)]
        uid = f"{r.platform}:{r.post_id}"
        if r.platform == "youtube" and r.kind == "video":
            rows.append({"uid": uid, "platform": r.platform, "post_url": r.url, "video_url": r.url, "created_at": str(r.created_at)[:10],
                         "text": _title(r.text)[:140], "can_transcribe": False,
                         "why": "YouTube's terms bar downloading videos. The title and description are used instead."})
        for v in dict.fromkeys(links):
            rows.append({"uid": uid, "platform": r.platform, "post_url": r.url, "video_url": v, "created_at": str(r.created_at)[:10],
                         "text": _title(r.text)[:140], "can_transcribe": True, "why": ""})
    return pd.DataFrame(rows, columns=["uid", "platform", "post_url", "video_url", "created_at", "text", "can_transcribe", "why"])


def _ffmpeg_audio(url: str, path: Path, max_seconds: int) -> None:
    import shutil
    import subprocess
    if not shutil.which("ffmpeg"):
        raise SystemExit("ffmpeg is needed to read video audio. On a Mac: brew install ffmpeg. On Linux: apt install ffmpeg.")
    subprocess.run(["ffmpeg", "-nostdin", "-loglevel", "error", "-y", "-user_agent", user_agent(), "-t", str(max_seconds),
                    "-i", url, "-vn", "-ac", "1", "-ar", "16000", str(path)], check=True, timeout=max_seconds * 3 + 120)


class WhisperTranscriber:
    """faster-whisper on this computer. Nothing is sent to an outside service. The language is checked on
    the opening audio first, and the video is transcribed only when it is English."""

    def __init__(self, model: str = "small"):
        try:
            from faster_whisper import WhisperModel
        except ImportError as e:
            raise SystemExit("Transcription needs faster-whisper: pip install faster-whisper") from e
        self.name, self.model = f"faster-whisper {model}", WhisperModel(model, device="auto", compute_type="int8")

    def __call__(self, wav: Path, min_prob: float) -> tuple[str, float, str]:
        segments, info = self.model.transcribe(str(wav), language=None, vad_filter=True)
        if info.language != "en" or info.language_probability < min_prob:
            return info.language, float(info.language_probability), ""      # the segments are never decoded
        return "en", float(info.language_probability), " ".join(seg.text.strip() for seg in segments).strip()


def stream_refusal(url: str, allowed) -> str:
    """Why this video must not be read, or ''. Its host must be approved for transcription (video:<domain> in
    sources.csv), not blocked or headlines-only, and allowed by robots.txt. For an HLS stream (.m3u8) the same
    holds for every playlist and segment it points to, because ffmpeg fetches those too."""
    def host_ok(u):
        d = domain_of(u)
        if not _domain_in(d, allowed or []):
            return f"{d} is not approved for transcription (add video:{d} to sources.csv after reading its terms)"
        return policy_refusal(u, "transcribe") or ("" if ROBOTS.check(u)[0] else f"robots.txt disallows {d}")
    why = host_ok(url)
    if why or ".m3u8" not in url.lower().split("?")[0]:
        return why
    seen, queue = set(), [url]
    while queue and len(seen) < 8:
        u = queue.pop(0)
        if u in seen:
            continue
        seen.add(u)
        try:
            text = HTTP.get_text(u, tries=2)
        except HTTPError as e:
            return f"the stream's playlist could not be read ({getattr(e, 'why', '') or e.status})"
        for line in (x.strip() for x in text.splitlines()):
            for part in (re.findall(r'URI="([^"]+)"', line) if line.startswith("#") else [line] if line else []):
                full = urllib.parse.urljoin(u, part)
                why = host_ok(full)
                if why:
                    return f"part of the stream can't be read: {why}"
                if ".m3u8" in full.lower().split("?")[0]:
                    queue.append(full)
    return ""


def transcribe_videos(cands: pd.DataFrame, folder: Path, transcriber, fetch_audio=_ffmpeg_audio,
                      max_seconds: int = 900, min_prob: float = 0.6, limit: int = 200, allowed=()) -> pd.DataFrame:
    """Transcribes approved videos that are in English, only from hosts in `allowed` (the video:<domain> rows
    approved in sources.csv). Audio is kept only while it is transcribed."""
    folder.mkdir(parents=True, exist_ok=True)
    path = folder / "transcripts.parquet"
    done = pd.read_parquet(path) if path.exists() else pd.DataFrame(columns=["uid", "video_url"])
    seen = set(zip(done["uid"], done["video_url"]))
    robots, rows = ROBOTS, []
    todo = cands[cands["can_transcribe"]]
    for r in todo.head(limit).itertuples():
        if (r.uid, r.video_url) in seen:
            continue
        row = {"uid": r.uid, "video_url": r.video_url, "language": "", "language_prob": 0.0, "status": "", "text": "",
               "model": getattr(transcriber, "name", "custom"), "at": datetime.now(timezone.utc).isoformat()}
        wav = folder / f"{stable_id(r.uid, r.video_url)}.wav"
        try:
            why = stream_refusal(r.video_url, allowed)
            if why:
                row["status"] = "skipped: " + why
            else:
                fetch_audio(r.video_url, wav, max_seconds)
                lang, prob, text = transcriber(wav, min_prob)
                row.update(language=lang, language_prob=round(prob, 3))
                row["status"] = "ok" if text else f"skipped: not English ({lang}, p={prob:.2f})" if lang != "en" or prob < min_prob else "skipped: no speech"
                row["text"] = text
        except SystemExit:
            raise
        except Exception as e:
            row["status"] = f"error: {type(e).__name__}"
        finally:
            if wav.exists():
                try:
                    wav.unlink()
                except OSError:          # a folder that doesn't allow deleting: empty the file instead
                    wav.write_bytes(b"")
                    log.warning("could not delete %s, so it was emptied instead", wav)
        rows.append(row)
        log.info("video %s: %s", r.uid, row["status"])
    out = pd.concat([done, pd.DataFrame(rows)], ignore_index=True) if rows else done
    if len(out):
        out.to_parquet(path, index=False)
    return out


def attach_transcripts(raw: pd.DataFrame, data: Path) -> pd.DataFrame:
    """Adds each English transcript to its post's text, so every later step (models, words, networks,
    the reading packet) uses what was said in the video. Counts of posts don't change."""
    raw = raw.copy()
    raw["has_transcript"] = False
    path = Path(data) / "videos" / "transcripts.parquet"
    if not path.exists() or raw.empty:
        return raw
    tr = pd.read_parquet(path)
    tr = tr[tr["status"] == "ok"].groupby("uid")["text"].apply(lambda t: " ".join(t)).to_dict()
    uid = raw["platform"].astype(str) + ":" + raw["post_id"].astype(str)
    hit = uid.isin(tr.keys())
    raw.loc[hit, "text"] = raw.loc[hit, "text"].astype(str) + "\n[video transcript] " + uid[hit].map(tr)
    raw.loc[hit, "has_transcript"] = True
    return raw


# --------------------------------------------------------------------------- model analysis

MODELS = {
    "sentiment": "cardiffnlp/twitter-roberta-base-sentiment-latest",   # negative, neutral, positive
    "emotion": "j-hartmann/emotion-english-distilroberta-base",        # 6 Ekman emotions plus neutral
    "stance": "MoritzLaurer/deberta-v3-base-zeroshot-v2.0",           # zero-shot NLI
    "embeddings": "sentence-transformers/all-MiniLM-L6-v2",            # for BERTopic
}
LONG_KINDS = {"article", "transcript"}


def _device():
    import torch
    if torch.cuda.is_available():
        return 0
    return "mps" if getattr(torch.backends, "mps", None) and torch.backends.mps.is_available() else -1


def _classify(texts, kinds, model_id, batch_size=32) -> pd.DataFrame:
    """Articles and transcripts are cut into 180-word chunks, and the chunk scores averaged."""
    from transformers import pipeline
    clf = pipeline("text-classification", model=model_id, top_k=None, truncation=True, max_length=512, device=_device())
    flat, owner = [], []
    for i, (t, k) in enumerate(zip(texts, kinds)):
        w = t.split()
        parts = [" ".join(w[j:j + 180]) for j in range(0, max(len(w), 1), 180)] if k in LONG_KINDS or len(w) > 300 else [t]
        flat += parts
        owner += [i] * len(parts)
    rows = pd.DataFrame([{d["label"].lower(): d["score"] for d in s} for s in clf(flat, batch_size=batch_size)])
    probs = rows.assign(owner=owner).groupby("owner").mean().reindex(range(len(texts)))
    probs["label"] = probs.idxmax(axis=1)
    return probs.reset_index(drop=True)


def have(module: str) -> bool:
    import importlib.util
    return importlib.util.find_spec(module) is not None


def sentiment(df):
    p = _classify(df["text_clean"].tolist(), df["kind"].tolist(), MODELS["sentiment"])
    p["score"] = p.get("positive", 0) - p.get("negative", 0)          # -1 to 1
    return p.add_prefix("sent_")


def sentiment_vader(df):
    """Fallback when transformers is not installed: VADER, a rule-based lexicon built for social media.
    Weaker on news prose, sarcasm and slang, so validate it the same way."""
    from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
    sia = SentimentIntensityAnalyzer()
    rows = []
    for t in df["text_clean"]:
        c = sia.polarity_scores(t)["compound"]
        rows.append({"score": c, "label": "positive" if c >= 0.05 else "negative" if c <= -0.05 else "neutral"})
    return pd.DataFrame(rows).add_prefix("sent_")


def emotion(df):
    return _classify(df["text_clean"].tolist(), df["kind"].tolist(), MODELS["emotion"]).add_prefix("emo_")


def stance(df, target, batch_size=16):
    """First pass only. Hand-label 200 posts and check agreement before reporting it."""
    from transformers import pipeline
    zs = pipeline("zero-shot-classification", model=MODELS["stance"], device=_device())
    labels = [f"supports {target}", f"opposes {target}", f"is neutral or unrelated to {target}"]
    rows = []
    for r in zs(df["text_clean"].tolist(), candidate_labels=labels, hypothesis_template="The author of this text {}.",
                batch_size=batch_size):
        d = dict(zip(r["labels"], r["scores"]))
        s = [d[labels[0]], d[labels[1]], d[labels[2]]]
        rows.append({"favor": s[0], "against": s[1], "none": s[2], "label": ["favor", "against", "none"][s.index(max(s))]})
    return pd.DataFrame(rows).add_prefix("stance_")


def topics(df, min_topic_size=20):
    from bertopic import BERTopic
    from sentence_transformers import SentenceTransformer
    from sklearn.feature_extraction.text import CountVectorizer
    docs = df["text_clean"].tolist()
    emb = SentenceTransformer(MODELS["embeddings"]).encode(docs, batch_size=64, show_progress_bar=True)
    tm = BERTopic(vectorizer_model=CountVectorizer(stop_words="english", ngram_range=(1, 2), min_df=2),
                  min_topic_size=min_topic_size)
    ids, _ = tm.fit_transform(docs, emb)
    over_time = tm.topics_over_time(docs, df["created_at"].dt.tz_localize(None).tolist(), nr_bins=12)
    return tm, ids, over_time


def nmf_topics(df, qwords, k=None, seeds=(1, 2, 3), top_n=10):
    """A transparent baseline: NMF on TF-IDF word counts. It runs with scikit-learn alone, so every
    run has topics, and BERTopic results can be checked against it. Fitted with three seeds: the
    stability score is the mean overlap (Jaccard) of each topic's top words with its best match in
    the other fits. Near 1 means the topics hold. Under 0.5 means they shift with the seed, so name
    them with care."""
    from sklearn.decomposition import NMF
    from sklearn.feature_extraction.text import TfidfVectorizer
    docs = [" ".join(tokens(t, qwords)) for t in df["text_clean"]]
    if sum(bool(d) for d in docs) < 50:
        return None
    k = k or int(min(12, max(3, round(math.sqrt(len(docs) / 20)))))
    vec = TfidfVectorizer(min_df=3, max_df=0.6, ngram_range=(1, 2), token_pattern=r"[^ ]+")
    try:
        X = vec.fit_transform(docs)
    except ValueError:
        return None
    if X.shape[1] < k * 3:
        return None
    words = vec.get_feature_names_out()
    fits = []
    for sd in seeds:
        m = NMF(n_components=k, init="nndsvda" if sd == seeds[0] else "random", random_state=sd, max_iter=400)
        W = m.fit_transform(X)
        fits.append((W, [[words[i] for i in comp.argsort()[::-1][:top_n]] for comp in m.components_]))
    W, tops = fits[0]
    jac = lambda a, b: len(set(a) & set(b)) / len(set(a) | set(b))
    stab = [max(jac(t, u) for u in other) for _, other in fits[1:] for t in tops]
    per_topic = [round(sum(max(jac(t, u) for u in other) for _, other in fits[1:]) / max(1, len(fits) - 1), 2) for t in tops]
    ids = [int(r.argmax()) if r.max() > 0 else -1 for r in W]
    counts = Counter(ids)
    table = pd.DataFrame([{"Topic": i, "Count": counts.get(i, 0), "Top terms": ", ".join(t[:8]), "Stability": per_topic[i]}
                          for i, t in enumerate(tops)]).sort_values("Count", ascending=False)
    return {"ids": ids, "table": table, "k": k, "stability": round(sum(stab) / len(stab), 3)}


def entities(df, model="en_core_web_sm") -> pd.DataFrame:
    import spacy
    nlp = spacy.load(model, disable=["lemmatizer"])
    rows = [{"row": i, "entity": e.text, "type": e.label_}
            for i, doc in enumerate(nlp.pipe(df["text_clean"].tolist(), batch_size=256))
            for e in doc.ents if e.label_ in {"PERSON", "ORG", "GPE", "NORP", "EVENT", "LAW"}]
    return pd.DataFrame(rows, columns=["row", "entity", "type"])

# --------------------------------------------------------------------------- statistics: intervals, keyness, robustness


def wilson(k: int, n: int, z: float = 1.96) -> tuple[float, float, float]:
    """A share with its 95% Wilson interval. Better than share +/- 2 SE for small n or shares near 0 or 1."""
    if n == 0:
        return float("nan"), float("nan"), float("nan")
    p = k / n
    den = 1 + z * z / n
    centre = (p + z * z / (2 * n)) / den
    half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / den
    return p, max(0.0, centre - half), min(1.0, centre + half)


def share_table(df, col, by="platform") -> pd.DataFrame:
    """Each label's share per group (and overall), with n and the Wilson interval."""
    rows = []
    groups = [("all", df)] + (list(df.groupby(by)) if by else [])
    for g, sub in groups:
        v = sub[col].dropna().astype(str)
        for lab, k in v.value_counts().items():
            p, lo, hi = wilson(int(k), len(v))
            rows.append({"group": g, "label": lab, "n": len(v), "count": int(k), "share": round(p, 4),
                         "ci_low": round(lo, 4), "ci_high": round(hi, 4)})
    return pd.DataFrame(rows)


def log_odds(tokens_a: list, tokens_b: list, min_count: int = 5) -> pd.DataFrame:
    """Keyness: words that set group A apart from group B, as z-scores of the log-odds ratio with an
    informative Dirichlet prior (Monroe, Colaresi and Quinn 2008). The prior is the pooled counts,
    which pulls rare words toward zero so a word seen twice cannot top the list. Positive z leans to A."""
    ca, cb = Counter(tokens_a), Counter(tokens_b)
    prior = ca + cb
    vocab = [w for w, c in prior.items() if c >= min_count]
    if not vocab:
        return pd.DataFrame(columns=["word", "z", "count_a", "count_b"])
    na, nb, a0 = sum(ca.values()), sum(cb.values()), sum(prior[w] for w in vocab)
    rows = []
    for w in vocab:
        aw, ya, yb = prior[w], ca[w], cb[w]
        la = math.log((ya + aw) / (na + a0 - ya - aw))
        lb = math.log((yb + aw) / (nb + a0 - yb - aw))
        rows.append({"word": w, "z": (la - lb) / math.sqrt(1.0 / (ya + aw) + 1.0 / (yb + aw)), "count_a": ya, "count_b": yb})
    return pd.DataFrame(rows).sort_values("z", ascending=False).reset_index(drop=True)


def keyness(df, qwords, min_count=5, top=15) -> dict:
    """Every comparison the data allows: favour vs against, positive vs negative, each platform vs the
    rest, news vs social posts, and the later half of the window vs the earlier half."""
    toks = df["text_clean"].map(lambda t: tokens(t, qwords))
    pairs = []
    if "stance_label" in df:
        pairs.append(("favor vs against", df["stance_label"] == "favor", df["stance_label"] == "against"))
    if "sent_label" in df:
        pairs.append(("positive vs negative", df["sent_label"] == "positive", df["sent_label"] == "negative"))
    if df["platform"].nunique() > 1:
        for plat in df["platform"].value_counts().index[:6]:
            pairs.append((f"{plat} vs rest", df["platform"] == plat, df["platform"] != plat))
    news = df["kind"].isin(NEWS_KINDS)
    if news.any() and (~news).any():
        pairs.append(("news vs social", news, ~news))
    if len(df) >= 40:
        mid = df["created_at"].min() + (df["created_at"].max() - df["created_at"].min()) / 2
        pairs.append(("later vs earlier half", df["created_at"] >= mid, df["created_at"] < mid))
    out = {}
    for name, a, b in pairs:
        if a.sum() < 20 or b.sum() < 20:
            continue
        t = log_odds([w for ws in toks[a] for w in ws], [w for ws in toks[b] for w in ws], min_count)
        if len(t):
            out[name] = {"a_posts": int(a.sum()), "b_posts": int(b.sum()),
                         "a": t.head(top).round(2).to_dict("records"),
                         "b": t.tail(top).iloc[::-1].round(2).to_dict("records")}
    return out


def hashtag_network(df, exclude=(), min_count=3, top_nodes=150):
    """Hashtags used together in one post, with Louvain communities (or greedy modularity on older networkx)."""
    import networkx as nx
    ex = {e.lstrip("#").lower() for e in exclude}
    docs = [sorted(set(h) - ex) for h in df["hashtags"]]
    freq = Counter(t for d in docs for t in d)
    keep = {t for t, _ in freq.most_common(top_nodes)}
    pairs = Counter(p for d in docs for p in itertools.combinations([t for t in d if t in keep], 2))
    g = nx.Graph()
    for (a, b), c in pairs.items():
        if c >= min_count:
            g.add_edge(a, b, weight=c)
    for n in g.nodes:
        g.nodes[n]["count"] = freq[n]
    if g.number_of_nodes():
        try:
            comms = nx.community.louvain_communities(g, weight="weight", seed=7)
        except AttributeError:
            from networkx.algorithms.community import greedy_modularity_communities as gm
            comms = gm(g, weight="weight")
        for i, c in enumerate(sorted(comms, key=len, reverse=True)):
            for n in c:
                g.nodes[n]["community"] = i
    return g


def network_neighbours(g, top=8, nodes=20) -> list[dict]:
    rows = []
    for n in sorted(g.nodes, key=lambda x: -g.nodes[x].get("count", 0))[:nodes]:
        nb = sorted(g[n].items(), key=lambda kv: -kv[1]["weight"])[:top]
        rows.append({"node": n, "count": g.nodes[n].get("count", 0), "community": g.nodes[n].get("community", -1),
                     "neighbours": ", ".join(f"{m} ({d['weight']})" for m, d in nb)})
    return rows


def descriptives(df, reposts) -> dict:
    """Who and what is in the data: unique authors and outlets, original, reply and repost shares,
    engagement medians and quantiles, linked domains, and the busiest accounts' share."""
    out = {}
    allp = pd.concat([df, reposts], ignore_index=True) if len(reposts) else df
    for plat, g in allp.groupby("platform"):
        d = {"items": int(len(g)), "unique_authors": int(g["author_key"].nunique()) if "author_key" in g else int(g["author_handle"].nunique())}
        kinds = g["kind"].value_counts(normalize=True).round(3).to_dict()
        d["kind_share"] = kinds
        eng = g[["like_count", "reply_count", "share_count"]].apply(pd.to_numeric, errors="coerce").sum(axis=1, min_count=1).dropna()
        if len(eng):
            d["engagement"] = {"median": float(eng.median()), "p75": float(eng.quantile(.75)), "p90": float(eng.quantile(.9)),
                               "p99": float(eng.quantile(.99)), "max": float(eng.max()),
                               "share_of_total_from_top_1pct": round(float(eng.nlargest(max(1, len(eng) // 100)).sum() / max(eng.sum(), 1)), 3)}
        out[plat] = d
    links = Counter(domain_of(u) for t in df["text"].fillna("") for u in URL_RE.findall(t))
    links.update(domain_of(u) for u in df.loc[df["kind"].isin(NEWS_KINDS), "url"].fillna(""))
    links.pop("", None)
    out["_top_domains"] = dict(links.most_common(20))
    out["_hashtags"] = dict(Counter(h for hs in df["hashtags"] for h in hs).most_common(25))
    return out


def robustness(df, query: Query | None = None) -> pd.DataFrame:
    """Do the headline numbers hold? Each row recomputes them on another reasonable version of the data:
    social posts only, original posts only (no replies), without suspect accounts, with each account
    capped at 5 posts, every platform weighted equally, exact-hashtag matches only, phrase matches
    only, and without the top 5 outlets. A finding that flips between rows is not a finding."""
    measures = [m for m in (("sent_label", "negative"), ("sent_label", "positive"), ("stance_label", "favor"),
                            ("stance_label", "against")) if m[0] in df]
    if not measures:
        return pd.DataFrame()
    variants = [("all kept items", df), ("social posts only", df[~df["kind"].isin(NEWS_KINDS)]),
                ("original posts only (no replies)", df[df["kind"] == "post"]),
                ("without suspect accounts", df[~df["suspect"]] if "suspect" in df else df),
                ("each account capped at 5 posts", df.sort_values("created_at").groupby(["platform", "author_key"]).head(5))]
    if "match_type" in df and (df["match_type"] == "hashtag").any():
        variants.append(("exact hashtag matches only", df[df["match_type"] == "hashtag"]))
    if "match_type" in df and (df["match_type"] == "phrase").any():
        variants.append(("phrase matches only", df[df["match_type"] == "phrase"]))
    if "match_type" in df and (df["match_type"] == "counter").any():
        variants.append(("without counter-tag matches", df[df["match_type"] != "counter"]))
    news = df[df["kind"].isin(NEWS_KINDS)]
    if len(news):
        top5 = news["author_handle"].value_counts().head(5).index
        variants.append(("without the top 5 outlets", df[~(df["kind"].isin(NEWS_KINDS) & df["author_handle"].isin(top5))]))
    rows = []
    for name, sub in variants:
        r = {"variant": name, "n": len(sub)}
        for col, lab in measures:
            v = sub[col].dropna()
            p, lo, hi = wilson(int((v == lab).sum()), len(v))
            r[f"{lab} share"] = f"{p:.0%} ({lo:.0%} to {hi:.0%})" if len(v) else "n/a"
        rows.append(r)
    if df["platform"].nunique() > 1:
        r = {"variant": "every platform weighted equally", "n": len(df)}
        for col, lab in measures:
            r[f"{lab} share"] = f"{df.groupby('platform')[col].apply(lambda v: (v == lab).mean()).mean():.0%}"
        rows.append(r)
    return pd.DataFrame(rows)


def reproducibility(argv=None) -> dict:
    import importlib.metadata as md
    pkgs = {}
    for name in ("pandas", "numpy", "scikit-learn", "networkx", "lingua-language-detector", "transformers", "torch",
                 "bertopic", "sentence-transformers", "spacy", "vaderSentiment", "trafilatura", "reportlab", "requests"):
        try:
            pkgs[name] = md.version(name)
        except md.PackageNotFoundError:
            pass
    return {"titus_scraper_version": VERSION, "script_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
            "python": sys.version.split()[0], "os": _platform.platform(), "packages": pkgs, "models": MODELS,
            "seeds": {"nmf": [1, 2, 3], "near_duplicates": 7, "samples": "see each command's --seed"},
            "command": " ".join(argv or sys.argv), "run_at": datetime.now(timezone.utc).isoformat()}

# --------------------------------------------------------------------------- validation: two coders, agreement, corrected shares

TASKS = {"sentiment": ("sent_label", ["positive", "neutral", "negative"]),
         "stance": ("stance_label", ["favor", "against", "none"]),
         "emotion": ("emo_label", ["anger", "disgust", "fear", "joy", "neutral", "sadness", "surprise"]),
         "relevance": ("", ["relevant", "partly", "irrelevant"])}


def make_sheets(df, tasks: list[str], n: int, folder: Path, seed: int = 42) -> dict:
    """A stratified sample for two coders: by platform and by the model's label for the first task, so
    rare labels get checked too. coder_A.csv and coder_B.csv list the same items in different orders
    with no model labels. key.csv holds the model labels and each item's sampling weight."""
    folder.mkdir(parents=True, exist_ok=True)
    rng = random.Random(seed)
    first = TASKS[tasks[0]][0]
    strat = ["platform"] + ([first] if first and first in df else [])
    groups = list(df.groupby(strat, dropna=False))
    base = max(1, n // max(1, len(groups)))
    picked = []
    for _, g in groups:
        take = min(len(g), base)
        picked += [(i, len(g) / take) for i in rng.sample(list(g.index), take)]
    if len(picked) < n:
        used = {i for i, _ in picked}
        picked += [(i, 1.0) for i in rng.sample([i for i in df.index if i not in used], min(n - len(picked), len(df) - len(used)))]
    picked = picked[:n]
    key = pd.DataFrame([{"item": f"i{k + 1:04d}", "uid": df.at[i, "uid"], "platform": df.at[i, "platform"],
                         "url": df.at[i, "url"], "weight": round(w, 3),
                         **{f"model_{t}": df.at[i, TASKS[t][0]] for t in tasks if TASKS[t][0] in df}}
                        for k, (i, w) in enumerate(picked)])
    key.to_csv(folder / "key.csv", index=False)
    texts = dict(zip(df["uid"], df["text_norm"]))
    for coder, sd in (("A", seed + 1), ("B", seed + 2)):
        rows = [{"item": r.item, "text": texts[r.uid], **{t: "" for t in tasks}} for r in key.itertuples()]
        random.Random(sd).shuffle(rows)
        pd.DataFrame(rows).to_csv(folder / f"coder_{coder}.csv", index=False)
    labels = {t: TASKS[t][1] for t in tasks}
    (folder / "labels.json").write_text(json.dumps(labels, indent=2))
    return {"items": len(key), "tasks": tasks, "labels": labels, "folder": str(folder)}


def cohen_kappa(a: list, b: list) -> float:
    pairs = [(x, y) for x, y in zip(a, b) if x and y]
    if not pairs:
        return float("nan")
    n = len(pairs)
    po = sum(x == y for x, y in pairs) / n
    ca, cb = Counter(x for x, _ in pairs), Counter(y for _, y in pairs)
    pe = sum(ca[c] * cb[c] for c in set(ca) | set(cb)) / (n * n)
    return (po - pe) / (1 - pe) if pe < 1 else 1.0


def krippendorff_alpha_nominal(units: list[list]) -> float:
    """units: the labels each coder gave one item (missing ones left out)."""
    vals = [[v for v in u if v not in ("", None) and v == v] for u in units]
    vals = [u for u in vals if len(u) >= 2]
    if not vals:
        return float("nan")
    cats = sorted({v for u in vals for v in u})
    ix = {c: i for i, c in enumerate(cats)}
    o = [[0.0] * len(cats) for _ in cats]
    for u in vals:
        m = len(u)
        for i, x in enumerate(u):
            for j, y in enumerate(u):
                if i != j:
                    o[ix[x]][ix[y]] += 1.0 / (m - 1)
    n_c = [sum(r) for r in o]
    n = sum(n_c)
    if n <= 1:
        return float("nan")
    do = (n - sum(o[i][i] for i in range(len(cats)))) / n
    de = (n * n - sum(x * x for x in n_c)) / (n * (n - 1))
    return 1.0 - do / de if de > 0 else 1.0


def _kappa_reading(k: float) -> str:
    if k != k:
        return "n/a"
    return ("poor: rewrite the codebook and relabel before trusting any model" if k < 0.4 else
            "moderate: tighten the codebook definitions" if k < 0.6 else "substantial" if k < 0.8 else "almost perfect")


def agreement(folder: Path, tasks: list[str]) -> dict:
    a = pd.read_csv(folder / "coder_A.csv", dtype=str).fillna("")
    b = pd.read_csv(folder / "coder_B.csv", dtype=str).fillna("")
    m = a.merge(b, on="item", suffixes=("_A", "_B"))
    adj, out = m[["item", "text_A"]].rename(columns={"text_A": "text"}), {}
    for t in tasks:
        la, lb = m[f"{t}_A"].str.strip().str.lower(), m[f"{t}_B"].str.strip().str.lower()
        done = (la != "") & (lb != "")
        adj[f"{t}_A"], adj[f"{t}_B"] = la, lb
        adj[f"{t}_gold"] = [x if x == y and x else "" for x, y in zip(la, lb)]
        if not done.any():
            out[t] = {"note": "no item labelled by both coders yet"}
            continue
        k = cohen_kappa(la[done].tolist(), lb[done].tolist())
        out[t] = {"items_both": int(done.sum()), "percent_agreement": round(float((la[done] == lb[done]).mean()), 3),
                  "cohen_kappa": round(float(k), 3),
                  "krippendorff_alpha": round(float(krippendorff_alpha_nominal([[x, y] for x, y in zip(la[done], lb[done])])), 3),
                  "reading": _kappa_reading(k), "disagreements": int((la[done] != lb[done]).sum())}
    adj.to_csv(folder / "adjudicate.csv", index=False)
    (folder / "agreement.json").write_text(json.dumps(out, indent=2))
    return out


def score(folder: Path, df_full: pd.DataFrame, task: str, boot: int = 1000) -> dict:
    """Model against the settled ('gold') labels: accuracy, macro-F1, per-class precision, recall and
    F1, the confusion matrix, F1 by platform, and the model's shares corrected for its errors. The
    correction applies P(true label | model label), measured in the stratified sample, to the model's
    shares in the full data, with a 95% interval from 1,000 bootstrap draws within each model label.
    For relevance there is no model: the result is the query's precision with a Wilson interval."""
    key = pd.read_csv(folder / "key.csv", dtype=str).fillna("")
    adj = pd.read_csv(folder / "adjudicate.csv", dtype=str).fillna("")
    m = key.merge(adj[["item", f"{task}_gold"]], on="item")
    m = m[m[f"{task}_gold"].str.strip() != ""]
    if m.empty:
        return {"task": task, "note": f"no settled labels yet: fill {task}_gold in adjudicate.csv"}
    y = m[f"{task}_gold"].str.strip().str.lower()
    if task == "relevance":
        w = m["weight"].astype(float)
        k = int((y == "relevant").sum())
        kp = int(y.isin(["relevant", "partly"]).sum())
        res = {"task": task, "items": len(y), "precision_strict": [round(v, 3) for v in wilson(k, len(y))],
               "precision_incl_partly": [round(v, 3) for v in wilson(kp, len(y))],
               "precision_weighted": round(float((w * (y == "relevant")).sum() / w.sum()), 3),
               "by_platform": {p: round(float((g == "relevant").mean()), 3) for p, g in y.groupby(m["platform"])},
               "verdict": "usable" if k / len(y) >= 0.8 else "tighten the query: add exclusions or drop loose variants"}
        (folder / f"validation_{task}.json").write_text(json.dumps(res, indent=2))
        return res
    from sklearn.metrics import accuracy_score, classification_report, confusion_matrix, f1_score
    p = m[f"model_{task}"].str.strip().str.lower()
    labels = sorted(set(y) | set(p))
    rep = classification_report(y, p, labels=labels, output_dict=True, zero_division=0)
    res = {"task": task, "items": len(y), "accuracy": round(float(accuracy_score(y, p)), 3),
           "macro_f1": round(float(f1_score(y, p, labels=labels, average="macro", zero_division=0)), 3),
           "per_class": {l: {k: round(float(v), 3) for k, v in rep[l].items()} for l in labels if l in rep},
           "macro_f1_by_platform": {pl: round(float(f1_score(y[g.index], p[g.index], average="macro", zero_division=0)), 3)
                                    for pl, g in m.groupby("platform")},
           "confusion_matrix": {"rows_true_cols_model": labels, "matrix": confusion_matrix(y, p, labels=labels).tolist()}}
    col = TASKS[task][0]
    if col in df_full:
        import numpy as np
        pred = df_full[col].dropna().astype(str).str.lower().value_counts(normalize=True)
        mm = pd.DataFrame({"y": y.values, "p": p.values})
        groups = {pl: mm.loc[mm["p"] == pl, "y"].to_numpy() for pl in pred.index}

        def corrected(draw=None):
            c = Counter()
            for pl, share in pred.items():
                g = groups.get(pl)
                if g is None or not len(g):
                    c[pl] += share
                    continue
                g = draw(g) if draw else g
                for tl, k in Counter(g).items():
                    c[tl] += share * k / len(g)
            return c

        base = corrected()
        rng = np.random.default_rng(0)
        draws = [corrected(lambda g: rng.choice(g, size=len(g), replace=True)) for _ in range(boot)]
        res["model_shares"] = {k: round(float(v), 3) for k, v in pred.items()}
        res["corrected_shares"] = {k: round(float(v), 3) for k, v in sorted(base.items(), key=lambda kv: -kv[1])}
        res["corrected_ci95"] = {k: [round(float(np.percentile([d.get(k, 0.0) for d in draws], 2.5)), 3),
                                     round(float(np.percentile([d.get(k, 0.0) for d in draws], 97.5)), 3)] for k in base}
    res["verdict"] = ("usable" if res["macro_f1"] >= 0.7 else
                      "weak: report with caution and show the corrected shares" if res["macro_f1"] >= 0.5 else
                      "do not report this measure")
    (folder / f"validation_{task}.json").write_text(json.dumps(res, indent=2))
    return res

# --------------------------------------------------------------------------- figures (static, for the PDF)

INK, INK2, MUTED, GRID, AXIS, SURFACE = "#0b0b0b", "#52514e", "#898781", "#e1e0d9", "#c3c2b7", "#fcfcfb"
SERIES = ["#2a78d6", "#eb6834", "#1baf7a", "#eda100", "#e87ba4", "#008300", "#6250d6", "#e34948"]
SENT_COLORS = {"negative": "#eb6834", "neutral": "#c3c2b7", "positive": "#2a78d6"}


def platform_colors(platforms) -> dict:
    """Colour follows the platform, in a fixed order, so it never changes between charts."""
    order = ["bluesky", "mastodon", "youtube", "reddit", "threads", "instagram", "news", "nytimes", "medium", "web"]
    names = sorted(set(platforms), key=lambda p: (order.index(p) if p in order else 99, p))
    return {p: SERIES[i % len(SERIES)] for i, p in enumerate(names)}


def _axes(ax):
    ax.set_facecolor(SURFACE)
    for s in ("top", "right"):
        ax.spines[s].set_visible(False)
    for s in ("left", "bottom"):
        ax.spines[s].set_color(AXIS)
    ax.tick_params(colors=INK2, labelsize=8)
    ax.grid(axis="x" if ax.get_label() == "h" else "y", color=GRID, linewidth=0.6)
    ax.set_axisbelow(True)


def _fig(w=7.0, h=3.4):
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    plt.rcParams.update({"font.family": "DejaVu Sans", "font.size": 8.5, "text.color": INK})
    fig, ax = plt.subplots(figsize=(w, h))
    fig.patch.set_facecolor(SURFACE)
    return plt, fig, ax


def _save(plt, fig, path):
    fig.tight_layout()
    fig.savefig(path, dpi=200, facecolor=SURFACE)
    plt.close(fig)
    return path


def time_bin(df) -> tuple[str, str]:
    """Days for windows under three weeks, weeks up to about six months, months beyond that, the same bins
    as sentiment over time. Returns (pandas rule, word)."""
    span = (df["created_at"].max() - df["created_at"].min()).days if len(df) else 0
    return ("D", "day") if span < 21 else ("W-SUN", "week") if span <= 180 else ("MS", "month")


def fig_volume(df, path):
    plt, fig, ax = _fig()
    colors = platform_colors(df["platform"])
    rule, word = time_bin(df)
    binned = df.set_index("created_at").groupby("platform").resample(rule)["post_id"].count()
    for p in colors:
        if p in binned.index.get_level_values(0):
            s = binned.loc[p]
            ax.plot(s.index, s.values, color=colors[p], linewidth=1.6, label=p)
    _axes(ax)
    ax.set_ylabel(f"Posts per {word}", color=INK2)
    ax.legend(frameon=False, fontsize=8, ncol=min(len(colors), 6), loc="upper left")
    return _save(plt, fig, path)


def fig_sentiment_by_platform(df, path):
    plt, fig, ax = _fig(7.0, 0.5 + 0.42 * df["platform"].nunique())
    ax.set_label("h")
    t = pd.crosstab(df["platform"], df["sent_label"], normalize="index").reindex(columns=list(SENT_COLORS), fill_value=0)
    left = pd.Series(0.0, index=t.index)
    for lab, col in SENT_COLORS.items():
        ax.barh(t.index, t[lab], left=left, color=col, edgecolor=SURFACE, linewidth=1.5, label=lab, height=0.6)
        for y, (l, v) in enumerate(zip(left, t[lab])):
            if v >= 0.08:
                ax.text(l + v / 2, y, f"{v:.0%}", va="center", ha="center", fontsize=7.5,
                        color="#ffffff" if lab != "neutral" else INK)
        left += t[lab]
    _axes(ax)
    ax.set_xlim(0, 1)
    ax.xaxis.set_major_formatter(plt.matplotlib.ticker.PercentFormatter(1.0))
    ax.legend(frameon=False, ncol=3, fontsize=8, loc="lower center", bbox_to_anchor=(0.5, 1.0))
    return _save(plt, fig, path)


def fig_weekly_sentiment(df, path):
    plt, fig, ax = _fig()
    colors = platform_colors(df["platform"])
    weekly = df.set_index("created_at").groupby("platform").resample("W")["sent_score"].mean()
    for p in colors:
        if p in weekly.index.get_level_values(0):
            s = weekly.loc[p].dropna()
            ax.plot(s.index, s.values, color=colors[p], linewidth=1.6, label=p)
    ax.axhline(0, color=AXIS, linewidth=0.8)
    _axes(ax)
    ax.set_ylim(-1, 1)
    ax.set_ylabel("Mean sentiment (-1 to 1)", color=INK2)
    ax.legend(frameon=False, fontsize=8, ncol=min(len(colors), 6), loc="upper left")
    return _save(plt, fig, path)


def fig_bars(values: pd.Series, path, xlabel):
    """One measure across items: a single hue, sorted, value at the end of each bar."""
    plt, fig, ax = _fig(7.0, 0.5 + 0.3 * len(values))
    ax.set_label("h")
    v = values.sort_values()
    ax.barh(v.index.astype(str), v.values, color=SERIES[0], height=0.6)
    for y, x in enumerate(v.values):
        ax.text(x, y, f" {x:.0%}" if v.max() <= 1 else f" {x:,.0f}", va="center", fontsize=7.5, color=INK2)
    _axes(ax)
    ax.set_xlabel(xlabel, color=INK2)
    return _save(plt, fig, path)


def fig_wordcloud(counts: Counter, path):
    """An oval word cloud: words are placed inside an ellipse, so the cloud reads as one shape."""
    import numpy as np
    from wordcloud import WordCloud
    w, h = 1600, 1000
    yy, xx = np.ogrid[:h, :w]
    inside = ((xx - w / 2) / (w / 2 - 10)) ** 2 + ((yy - h / 2) / (h / 2 - 10)) ** 2 <= 1
    mask = np.where(inside, 0, 255).astype(np.uint8)
    wc = WordCloud(width=w, height=h, mask=mask, background_color=SURFACE, collocations=False, max_words=150,
                   color_func=lambda *a, **k: random.Random(zlib.crc32(a[0].encode())).choice(SERIES[:3] + [INK2]))
    wc.generate_from_frequencies(counts).to_file(str(path))
    return path


def doc_counts(df, qwords) -> Counter:
    """How many posts or articles use each word at least once."""
    return Counter(w for text in df["text_clean"] for w in set(tokens(text, qwords)))


def sentiment_bin(df) -> tuple[str, str]:
    """Days for windows under three weeks, weeks up to about six months, months beyond that."""
    span = (df["created_at"].max() - df["created_at"].min()).days if len(df) else 0
    return ("D", "day") if span < 21 else ("W-SUN", "week") if span <= 180 else ("MS", "month")


def sentiment_series(df, min_n=5) -> tuple[pd.Series, str]:
    """Mean sentiment score per time bin over all items, leaving out bins with fewer than min_n items."""
    rule, word = sentiment_bin(df)
    g = df.dropna(subset=["sent_score"]).set_index("created_at").resample(rule)["sent_score"]
    m, n = g.mean(), g.count()
    return m[n >= min_n], word


def fig_sentiment_time(df, path):
    """Mean sentiment over time: a thick line for all items, thin lines for each source."""
    plt, fig, ax = _fig()
    rule, word = sentiment_bin(df)
    colors = platform_colors(df["platform"])
    if len(colors) > 1:
        per = df.dropna(subset=["sent_score"]).set_index("created_at").groupby("platform").resample(rule)["sent_score"].agg(["mean", "count"])
        for p in colors:
            if p in per.index.get_level_values(0):
                s = per.loc[p]
                s = s[s["count"] >= 5]["mean"]
                if len(s):
                    ax.plot(s.index, s.values, color=colors[p], linewidth=1.0, alpha=0.75, label=p)
    allm, _ = sentiment_series(df)
    if len(allm):
        ax.plot(allm.index, allm.values, color=INK, linewidth=2.2, label="all items", marker="o" if len(allm) < 15 else None, markersize=3)
    ax.axhline(0, color=AXIS, linewidth=0.8)
    _axes(ax)
    ax.set_ylim(-1, 1)
    ax.set_ylabel(f"Mean sentiment per {word} (-1 to 1)", color=INK2)
    ax.legend(frameon=False, fontsize=8, ncol=min(len(colors) + 1, 6), loc="upper left")
    return _save(plt, fig, path)


def fig_network(g, path, max_labels=60):
    import networkx as nx
    plt, fig, ax = _fig(7.0, 5.6)
    if g.number_of_nodes():
        pos = nx.spring_layout(g, k=0.7, seed=7, weight="weight")
        nx.draw_networkx_edges(g, pos, alpha=0.18, edge_color=MUTED, ax=ax)
        nodes = list(g.nodes)
        nx.draw_networkx_nodes(g, pos, nodelist=nodes, ax=ax, alpha=0.9, linewidths=0.8, edgecolors=SURFACE,
                               node_size=[25 + 2.5 * g.nodes[n]["count"] ** 0.8 for n in nodes],
                               node_color=[SERIES[g.nodes[n].get("community", 0) % len(SERIES)] for n in nodes])
        top = sorted(nodes, key=lambda n: -g.nodes[n]["count"])[:max_labels]
        nx.draw_networkx_labels(g, pos, labels={n: n for n in top}, font_size=7, font_color=INK, ax=ax)
    ax.axis("off")
    return _save(plt, fig, path)

def fig_hashtag_map(g, path, max_labels=45):
    """Hashtag network map: hashtags used in the same post are joined. Small separate clusters are kept near
    the main one, so the map reads as one picture, and labels carry a white halo so they stay legible."""
    import networkx as nx
    from matplotlib import patheffects
    plt, fig, ax = _fig(7.0, 6.2)
    if g.number_of_nodes():
        comps = sorted(nx.connected_components(g), key=len, reverse=True)
        hub = max(comps[0], key=lambda n: g.nodes[n]["count"])
        lay = nx.Graph()
        lay.add_nodes_from(g.nodes)
        lay.add_edges_from(g.edges, dist=1.0)
        for c in comps[1:]:
            lay.add_edge(hub, max(c, key=lambda n: g.nodes[n]["count"]), dist=2.2)
        try:
            pos = nx.kamada_kawai_layout(lay, weight="dist")
        except Exception:
            pos = nx.spring_layout(lay, k=1.6 / math.sqrt(lay.number_of_nodes()), seed=7, iterations=300)
        w = [d.get("weight", 1) for _, _, d in g.edges(data=True)]
        top_w = max(w) if w else 1
        nx.draw_networkx_edges(g, pos, ax=ax, edge_color=MUTED, alpha=0.35,
                               width=[0.5 + 2.5 * d.get("weight", 1) / top_w for _, _, d in g.edges(data=True)])
        nodes = list(g.nodes)
        nx.draw_networkx_nodes(g, pos, nodelist=nodes, ax=ax, alpha=0.92, linewidths=0.8, edgecolors=SURFACE,
                               node_size=[40 + 6 * g.nodes[x]["count"] ** 0.8 for x in nodes],
                               node_color=[SERIES[g.nodes[x].get("community", 0) % len(SERIES)] for x in nodes])
        top = sorted(nodes, key=lambda x: -g.nodes[x]["count"])[:max_labels]
        for x in top:
            ax.text(pos[x][0], pos[x][1] + 0.025, "#" + x, fontsize=7.5, color=INK, ha="center", va="bottom",
                    path_effects=[patheffects.withStroke(linewidth=2.5, foreground=SURFACE)])
    ax.axis("off")
    ax.margins(0.08)
    return _save(plt, fig, path)



def fig_flow_network(g, path, max_labels=60):
    """Arrows point from a word to the words that follow it. Line width grows with how often that happens."""
    import networkx as nx
    plt, fig, ax = _fig(7.0, 6.0)
    comps = sorted(nx.weakly_connected_components(g), key=len, reverse=True)
    g = g.subgraph(set().union(*[c for c in comps if len(c) >= 3 or c is comps[0]])).copy() if comps else g
    if g.number_of_nodes():
        u = g.to_undirected()
        for a, b, d in u.edges(data=True):
            d["dist"] = 1.0 / math.log1p(d["weight"])
        try:
            start = nx.kamada_kawai_layout(u, weight="dist")
        except Exception:
            start = None
        pos = nx.spring_layout(u, pos=start, k=1.2 / math.sqrt(max(u.number_of_nodes(), 1)), seed=7, weight="weight", iterations=60)
        w = [d["weight"] for _, _, d in g.edges(data=True)]
        lo, hi = min(w), max(w)
        scale = lambda x: 0.4 + 5.6 * ((x - lo) / (hi - lo) if hi > lo else 0.5)
        order = sorted(g.edges(data=True), key=lambda e: e[2]["weight"])
        nodes = list(g.nodes)
        sizes = {n: 40 + 3.0 * g.nodes[n]["count"] ** 0.75 for n in nodes}
        nx.draw_networkx_edges(g, pos, edgelist=[(a, b) for a, b, _ in order], ax=ax, arrows=True, arrowstyle="-|>",
                               arrowsize=[6 + 1.8 * scale(d["weight"]) for _, _, d in order], width=[scale(d["weight"]) for _, _, d in order],
                               edge_color=[INK2 if scale(d["weight"]) > 3 else MUTED for _, _, d in order],
                               alpha=0.55, connectionstyle="arc3,rad=0.12", nodelist=nodes, node_size=[sizes[n] for n in nodes],
                               min_source_margin=2, min_target_margin=4)
        nx.draw_networkx_nodes(g, pos, nodelist=nodes, ax=ax, alpha=0.92, linewidths=0.8, edgecolors=SURFACE,
                               node_size=[sizes[n] for n in nodes],
                               node_color=[SERIES[g.nodes[n].get("community", 0) % len(SERIES)] for n in nodes])
        top = sorted(nodes, key=lambda n: -g.nodes[n]["count"])[:max_labels]
        nx.draw_networkx_labels(g, pos, labels={n: n for n in top}, font_size=7, font_color=INK, ax=ax)
    ax.axis("off")
    return _save(plt, fig, path)

# --------------------------------------------------------------------------- comparing topics

def diff_ci(k1, n1, k2, n2) -> tuple[float, float, float]:
    """Difference of two shares (p1 - p2) with Newcombe's 95% interval built from the Wilson intervals."""
    p1, l1, u1 = wilson(k1, n1)
    p2, l2, u2 = wilson(k2, n2)
    d = p1 - p2
    return d, d - math.sqrt((p1 - l1) ** 2 + (u2 - p2) ** 2), d + math.sqrt((u1 - p1) ** 2 + (p2 - l2) ** 2)


def _load_run(d):
    out = Path(d) / "outputs"
    if not (out / "posts_analyzed.parquet").exists():
        raise SystemExit(f"{d}: run analyze on this topic first.")
    df = pd.read_parquet(out / "posts_analyzed.parquet")
    df["created_at"] = pd.to_datetime(df["created_at"], utc=True)
    meta = json.loads((out / "run_meta.json").read_text()) if (out / "run_meta.json").exists() else {}
    return df, meta


def fig_compare_volume(dfs: dict, path):
    plt, fig, ax = _fig()
    allc = pd.concat(dfs.values())
    rule, word = time_bin(allc)
    for i, (label, df) in enumerate(dfs.items()):
        sr = df.set_index("created_at").resample(rule)["uid"].count()
        ax.plot(sr.index, sr.values, color=SERIES[i % len(SERIES)], linewidth=1.8, label=label)
    _axes(ax)
    ax.set_ylabel(f"Posts per {word}", color=INK2)
    ax.legend(frameon=False, fontsize=8, ncol=len(dfs), loc="upper left")
    return _save(plt, fig, path)


def fig_compare_shares(dfs: dict, col: str, order: list, colors_: dict, path):
    """One stacked bar per topic and platform, so each topic is read against the same platforms."""
    rows = []
    for label, df in dfs.items():
        if col not in df:
            continue
        for plat, g in [("all platforms", df)] + list(df.groupby("platform")):
            v = g[col].value_counts(normalize=True)
            rows.append((f"{label} | {plat}", [float(v.get(o, 0)) for o in order]))
    if not rows:
        return None
    plt, fig, ax = _fig(7.0, 0.5 + 0.34 * len(rows))
    ax.set_label("h")
    names = [r[0] for r in rows][::-1]
    vals = [r[1] for r in rows][::-1]
    left = [0.0] * len(rows)
    for j, o in enumerate(order):
        w = [v[j] for v in vals]
        ax.barh(names, w, left=left, color=colors_[o], edgecolor=SURFACE, linewidth=1.5, label=o, height=0.62)
        for y, (l, x) in enumerate(zip(left, w)):
            if x >= 0.08:
                ax.text(l + x / 2, y, f"{x:.0%}", va="center", ha="center", fontsize=7, color=INK if o in ("neutral", "none") else "#ffffff")
        left = [l + x for l, x in zip(left, w)]
    _axes(ax)
    ax.set_xlim(0, 1)
    ax.xaxis.set_major_formatter(plt.matplotlib.ticker.PercentFormatter(1.0))
    ax.legend(frameon=False, ncol=len(order), fontsize=8, loc="lower center", bbox_to_anchor=(0.5, 1.0))
    return _save(plt, fig, path)


STANCE_COLORS = {"favor": "#2a78d6", "none": "#c3c2b7", "against": "#eb6834"}


def compare_runs(run_dirs: list, labels: list, out_dir: Path, title: str = "") -> dict:
    """Compares two to four topics, each collected and analysed in its own run folder. Writes
    comparison.json, comparison.md and figures to <out_dir>/outputs. Shares are compared overall
    and on each platform both topics share, because platform mix alone can make two topics look
    different. Differences come with Newcombe 95% intervals."""
    out = Path(out_dir).resolve() / "outputs"
    (out / "figures").mkdir(parents=True, exist_ok=True)
    runs = {lab: _load_run(d) for lab, d in zip(labels, run_dirs)}
    dfs = {lab: r[0].assign(topic=lab) for lab, r in runs.items()}
    cm: dict = {"title": title, "labels": labels, "runs": [str(Path(d).resolve()) for d in run_dirs], "figures": {},
                "queries": {lab: {k: r[1].get(k) for k in ("type", "value", "aliases", "counter", "exclude", "variants", "stance_target")}
                            for lab, r in runs.items()}}
    allc = pd.concat(dfs.values(), ignore_index=True)
    cm["since"] = min((r[1].get("since") or "") for r in runs.values()) or str(allc["created_at"].min())[:10]
    cm["until"] = max((r[1].get("until") or "") for r in runs.values()) or str(allc["created_at"].max())[:10]
    cm["counts"] = {lab: {"items": len(df), "by_platform": df["platform"].value_counts().to_dict(),
                          "by_kind": df["kind"].value_counts().to_dict(), "first": str(df["created_at"].min())[:10],
                          "last": str(df["created_at"].max())[:10]} for lab, df in dfs.items()}
    rule, word = time_bin(allc)
    peaks = {}
    for lab, df in dfs.items():
        sr = df.set_index("created_at").resample(rule)["uid"].count()
        peaks[lab] = [{"bin_start": str(k)[:10], "items": int(v)} for k, v in sr.sort_values(ascending=False).head(3).items()]
    cm["peaks"] = {"bin": word, "top": peaks}
    if len(dfs) >= 2:
        series = [df.set_index("created_at").resample(rule)["uid"].count() for df in dfs.values()]
        both = pd.concat(series[:2], axis=1).fillna(0)
        cm["volume_correlation_first_two"] = round(float(both.corr().iloc[0, 1]), 3) if len(both) > 2 else None
    # shares and differences
    measures = {"sentiment": ("sent_label", ["positive", "neutral", "negative"]), "stance": ("stance_label", ["favor", "none", "against"]),
                "emotion": ("emo_label", None)}
    cm["shares"], cm["differences"] = {}, []
    for name, (col, order) in measures.items():
        if not all(col in df for df in dfs.values()):
            continue
        cm["shares"][name] = {lab: share_table(df, col).to_dict("records") for lab, df in dfs.items()}
        labs_ = order or sorted(set(allc[col].dropna()))
        for a_, b_ in itertools.combinations(dfs, 2):
            A, B = dfs[a_], dfs[b_]
            plats = [("all platforms", A, B)] + [(p, A[A.platform == p], B[B.platform == p]) for p in sorted(set(A.platform) & set(B.platform))]
            eq = {lab: A.groupby("platform")[col].apply(lambda v: (v == lab).mean()).mean() - B.groupby("platform")[col].apply(lambda v: (v == lab).mean()).mean()
                  for lab in labs_}
            for plat, x, y in plats:
                for lab in labs_:
                    vx, vy = x[col].dropna(), y[col].dropna()
                    if len(vx) < 10 or len(vy) < 10:
                        continue
                    d, lo, hi = diff_ci(int((vx == lab).sum()), len(vx), int((vy == lab).sum()), len(vy))
                    cm["differences"].append({"measure": name, "label": lab, "platform": plat, "a": a_, "b": b_,
                                              "share_a": round((vx == lab).mean(), 4), "n_a": len(vx), "share_b": round((vy == lab).mean(), 4),
                                              "n_b": len(vy), "diff": round(d, 4), "ci_low": round(lo, 4), "ci_high": round(hi, 4),
                                              "clear": bool(lo > 0 or hi < 0)})
            cm.setdefault("equal_platform_weight_diff", {})[f"{name}: {a_} minus {b_}"] = {k: round(float(v), 4) for k, v in eq.items()}
    if "sentiment" in cm["shares"]:
        cm["figures"]["compare_sentiment"] = str(fig_compare_shares(dfs, "sent_label", ["negative", "neutral", "positive"], SENT_COLORS, out / "figures" / "compare_sentiment.png"))
    if "stance" in cm["shares"]:
        cm["figures"]["compare_stance"] = str(fig_compare_shares(dfs, "stance_label", ["against", "none", "favor"], STANCE_COLORS, out / "figures" / "compare_stance.png"))
    cm["figures"]["compare_volume"] = str(fig_compare_volume(dfs, out / "figures" / "compare_volume.png"))
    # words
    qwords = set()
    for _, m in runs.values():
        qwords |= query_stopwords(m.get("value", ""), (m.get("aliases") or []) + (m.get("counter") or []))
    cm["top_terms"] = {lab: dict(term_counts(df, qwords).most_common(20)) for lab, df in dfs.items()}
    cm["keyness"] = {}
    for a_, b_ in itertools.combinations(dfs, 2):
        ta = [w for t in dfs[a_]["text_clean"] for w in tokens(t, qwords)]
        tb = [w for t in dfs[b_]["text_clean"] for w in tokens(t, qwords)]
        k = log_odds(ta, tb)
        if len(k):
            cm["keyness"][f"{a_} vs {b_}"] = {"a": k.head(20).round(2).to_dict("records"), "b": k.tail(20).iloc[::-1].round(2).to_dict("records")}
    # overlap: the same post in two topics, accounts posting on both, shared hashtags
    cm["overlap"] = {}
    for a_, b_ in itertools.combinations(dfs, 2):
        A, B = dfs[a_], dfs[b_]
        both = set(A["uid"]) & set(B["uid"])
        sa = set(A.loc[~A["kind"].isin(NEWS_KINDS), "author_key"].replace("", pd.NA).dropna())
        sb = set(B.loc[~B["kind"].isin(NEWS_KINDS), "author_key"].replace("", pd.NA).dropna())
        outlets_a = set(A.loc[A["kind"].isin(NEWS_KINDS), "author_handle"])
        outlets_b = set(B.loc[B["kind"].isin(NEWS_KINDS), "author_handle"])
        ha, hb = Counter(h for hs in A["hashtags"] for h in hs), Counter(h for hs in B["hashtags"] for h in hs)
        shared = sorted(set(ha) & set(hb), key=lambda h: -(ha[h] + hb[h]))[:20]
        cm["overlap"][f"{a_} and {b_}"] = {
            "items_in_both": len(both), "share_of_a": round(len(both) / max(len(A), 1), 4), "share_of_b": round(len(both) / max(len(B), 1), 4),
            "accounts_posting_on_both": len(sa & sb), "accounts_a": len(sa), "accounts_b": len(sb),
            "outlets_covering_both": len(outlets_a & outlets_b), "outlets_a": len(outlets_a), "outlets_b": len(outlets_b),
            "shared_hashtags": [{"tag": h, "a": ha[h], "b": hb[h]} for h in shared]}
        cm["overlap"][f"{a_} and {b_}"]["sample_uids"] = sorted(both)[:30]
    (out / "comparison.json").write_text(json.dumps(cm, indent=2, default=str))
    (out / "comparison.md").write_text(comparison_markdown(cm, dfs), encoding="utf-8")
    return cm


def comparison_markdown(cm: dict, dfs: dict) -> str:
    pct = lambda v: f"{v:.0%}"
    L = [f"# Comparison: {' vs '.join(cm['labels'])}", "",
         "Read each topic's reading packet first, then this file. Shares differ partly because the platform mix differs, "
         "so prefer the per-platform rows when a difference matters.", "", "## Size", ""]
    for lab, c in cm["counts"].items():
        L.append(f"- {lab}: {c['items']:,} items, {c['first']} to {c['last']}. " + ", ".join(f"{k} {v:,}" for k, v in c["by_platform"].items()))
    L += ["", f"## Peaks (by {cm['peaks']['bin']})", ""]
    for lab, pk in cm["peaks"]["top"].items():
        L.append(f"- {lab}: " + ", ".join(f"{p['bin_start']} ({p['items']:,})" for p in pk))
    if cm.get("volume_correlation_first_two") is not None:
        L.append(f"- Correlation of the two volume series: {cm['volume_correlation_first_two']:+.2f}")
    if cm["differences"]:
        L += ["", "## Differences with 95% intervals", "", "Clear means the interval leaves out zero.", "",
              "| Measure | Label | Platform | A | B | A share | B share | A minus B | 95% interval | Clear |", "|---|---|---|---|---|---|---|---|---|---|"]
        for d in cm["differences"]:
            L.append(f"| {d['measure']} | {d['label']} | {d['platform']} | {d['a']} | {d['b']} | {pct(d['share_a'])} (n={d['n_a']:,}) | "
                     f"{pct(d['share_b'])} (n={d['n_b']:,}) | {d['diff']:+.0%} | {d['ci_low']:+.0%} to {d['ci_high']:+.0%} | {'yes' if d['clear'] else 'no'} |")
    for name, k in cm.get("keyness", {}).items():
        a_, b_ = name.split(" vs ")
        L += ["", f"## Words that set {a_} apart from {b_}", "",
              f"- Leans to {a_}: " + ", ".join(f"{r['word']} ({r['z']:+.1f})" for r in k["a"][:15]),
              f"- Leans to {b_}: " + ", ".join(f"{r['word']} ({r['z']:+.1f})" for r in k["b"][:15])]
    for name, o in cm["overlap"].items():
        a_, b_ = name.split(" and ")
        L += ["", f"## Overlap: {name}", "",
              f"- Items found by both searches: {o['items_in_both']:,} ({pct(o['share_of_a'])} of {a_}, {pct(o['share_of_b'])} of {b_})",
              f"- Accounts that posted on both: {o['accounts_posting_on_both']:,} of {o['accounts_a']:,} and {o['accounts_b']:,}",
              f"- Outlets that covered both: {o['outlets_covering_both']:,} of {o['outlets_a']:,} and {o['outlets_b']:,}",
              "- Shared hashtags: " + ", ".join(f"#{h['tag']} ({h['a']:,} / {h['b']:,})" for h in o["shared_hashtags"][:15])]
        A = dfs[a_]
        sample = A[A["uid"].isin(o["sample_uids"])].sort_values("created_at")
        if len(sample):
            L += ["", "Items that mention both topics (read these: they show how people connect or contrast them):", ""]
            for r in sample.itertuples():
                text = re.sub(r"\s+", " ", str(r.text))[:400]
                L.append(f"- {r.created_at:%Y-%m-%d} | {r.platform} {r.kind} | {r.author_name or r.author_handle} | {text} | {r.url}")
    return "\n".join(L) + "\n"


def compare_story(cm, story, table, image, figs, body, small, h1, h2, h3, width=450):
    """The comparison section that opens Part 2 of a comparison PDF."""
    from reportlab.platypus import KeepTogether, Paragraph
    P = lambda t: Paragraph(_md_inline(t), body)
    pct = lambda v: f"{v:.0%}"
    num = itertools.count(1)
    sec = lambda name: Paragraph(f"{next(num)}. {name}", h2)
    flow = lambda name, cap: [image(figs[name], cap)] if name in figs else []
    story.append(Paragraph(_md_inline("Comparison: " + " vs ".join(cm["labels"])), h1))
    story.append(sec("What was compared"))
    W = lambda *fr: [width * f for f in fr]
    rows = [["Topic", "Query", "Items kept", "Dates", "By platform"]]
    for lab in cm["labels"]:
        q, c = cm["queries"].get(lab, {}), cm["counts"][lab]
        terms = [t.strip() for t in re.split(r"[,\s]+", q.get("value") or "") if t.strip()] if q.get("type") == "hashtag" else [q.get("value", "")]
        terms += list(q.get("aliases") or [])
        rows.append([lab, f"{q.get('type', '')}: {', '.join(terms)}", f"{c['items']:,}", f"{c['first']} to {c['last']}",
                     ", ".join(f"{k} {v:,}" for k, v in c["by_platform"].items())])
    story.append(table(rows, W(0.17, 0.35, 0.1, 0.16, 0.22)))
    story.append(P("Each topic was collected, cleaned and analysed on its own with the same settings. The platform mix differs between "
                   "topics, so a pooled difference can come from where the posts were found. The per-platform rows below control for that."))
    story += flow("compare_volume", f"Items per {cm['peaks']['bin']} for each topic.")
    if cm.get("volume_correlation_first_two") is not None:
        story.append(P(f"Correlation of the first two topics' volume over time: **{cm['volume_correlation_first_two']:+.2f}**. "
                       "Peaks: " + "; ".join(f"{lab}: " + ", ".join(f"{p['bin_start']} ({p['items']:,})" for p in pk)
                                            for lab, pk in cm["peaks"]["top"].items()).replace(";", ".") + "."))
    if cm["differences"]:
        story.append(KeepTogether([sec("Tone and stance, side by side")] + flow("compare_sentiment", "Sentiment by topic and platform.")))
        story += flow("compare_stance", "Stance by topic and platform. Each topic's stance is toward its own target.")
        for a_, b_ in itertools.combinations(cm["labels"], 2):
            rows = [["Measure", "Label", "Platform", a_, b_, "Difference (95% interval)", "Clear"]]
            for d in cm["differences"]:
                if (d["a"], d["b"]) != (a_, b_) or (d["measure"] == "emotion" and not d["clear"]):
                    continue
                rows.append([d["measure"], d["label"], d["platform"], f"{pct(d['share_a'])} (n={d['n_a']:,})", f"{pct(d['share_b'])} (n={d['n_b']:,})",
                             f"{d['diff']:+.0%} ({d['ci_low']:+.0%} to {d['ci_high']:+.0%})", "yes" if d["clear"] else "no"])
            story.append(table(rows, W(0.11, 0.1, 0.15, 0.17, 0.17, 0.21, 0.09)))
        story.append(P("Clear means the 95% interval for the difference (Newcombe's method) leaves out zero. A difference that is clear "
                       "overall but not on any single platform may come from the platform mix."))
    if cm.get("keyness"):
        head = [sec("Words that set the topics apart")]
        for name, k in cm["keyness"].items():
            a_, b_ = name.split(" vs ")
            fmt = lambda rs: ", ".join(f"{r['word']} ({r['z']:+.1f})" for r in rs[:15])
            story.append(KeepTogether(head + [table([[f"Leans to {a_}", f"Leans to {b_}"], [fmt(k["a"]), fmt(k["b"])]], W(0.5, 0.5))]))
            head = []
        story.append(P("Log-odds ratio with an informative Dirichlet prior. Each query's own words are removed."))
    story.append(sec("Where the topics meet"))
    for name, o in cm["overlap"].items():
        story.append(table([["Overlap", name],
                            ["Items found by both searches", f"{o['items_in_both']:,} ({pct(o['share_of_a'])} and {pct(o['share_of_b'])})"],
                            ["Accounts that posted on both", f"{o['accounts_posting_on_both']:,} (of {o['accounts_a']:,} and {o['accounts_b']:,})"],
                            ["Outlets that covered both", f"{o['outlets_covering_both']:,} (of {o['outlets_a']:,} and {o['outlets_b']:,})"],
                            ["Shared hashtags", ", ".join(f"#{h['tag']} ({h['a']:,} / {h['b']:,})" for h in o["shared_hashtags"][:12]) or "none"]], W(0.32, 0.68)))
        story.append(P("Shared hashtag counts are given for each topic in order. Accounts are counted, never named."))
    story.append(P("The full report for each topic follows: data quality, descriptives, intervals, robustness, topics, words and validation."))


# --------------------------------------------------------------------------- PDF report


def _plain(s) -> str:
    """Text from the web that goes inside a Markdown link: no brackets or emphasis marks."""
    return re.sub(r"[\[\]*`]", "", str(s))


def _md_inline(s: str) -> str:
    s = html.escape(s)
    s = re.sub(r"\*\*(.+?)\*\*", r"<b>\1</b>", s)
    s = re.sub(r"(?<!\*)\*(?!\s)(.+?)(?<!\s)\*(?!\*)", r"<i>\1</i>", s)
    s = re.sub(r"`(.+?)`", r"<font face='Courier'>\1</font>", s)
    return re.sub(r"\[(.+?)\]\((https?://[^)]+)\)", r"<link href='\2' color='#2a78d6'>\1</link>", s)


REQUIRED_FIGURES = ["volume", "wordcloud", "top_terms", "network", "hashtags", "sentiment", "sentiment_time"]
FIGURE_ALIASES = {"weekly_sentiment": "sentiment_time"}
FIGURE_TITLES = {"volume": "Posts over time", "wordcloud": "Word cloud", "top_terms": "The most used words",
                 "network": "Word network", "hashtags": "Hashtag network", "sentiment": "Tone of coverage",
                 "sentiment_time": "Sentiment over time"}


def and_list(items: list[str]) -> str:
    """'a', 'a and b', 'a, b and c'."""
    items = [str(i) for i in items]
    return items[0] if len(items) == 1 else ", ".join(items[:-1]) + " and " + items[-1] if items else ""


def bin_label(ts, word: str) -> str:
    """A time bin in words: '12 Nov 2026', 'the week ending 15 Nov 2026' or 'November 2026'."""
    day = f"{ts.day} {ts:%b %Y}"
    return day if word == "day" else f"the week ending {day}" if word == "week" else f"{ts:%B %Y}"


def build_pdf(data_dir, blog_path, out_path, title=None, author="", full=False, max_sources=10, hide_words=(), fmt=None):
    """One PDF. By default it holds the cover and Part 1: the blog post (blog.md), followed by the four key figures
    with explanations (any the post didn't place itself), a short note on the data, and the sources, at most
    max_sources of them, ranked by relevance (0 lists them all). With full=True, Part 2, the analysis report
    built from outputs/, follows. For a comparison folder (made by the compare command), Part 2 opens with the
    comparison and then gives each topic's full analysis report. hide_words keeps names (such as a private
    person's) out of the word cloud, the word lists and both networks."""
    hidden = {w.lower() for h in hide_words for w in re.findall(r"[\w']+", h.lstrip("#"))} | {h.lstrip("#").lower().replace(" ", "") for h in hide_words}
    from reportlab.lib import colors
    from reportlab.lib.enums import TA_LEFT
    from reportlab.lib.pagesizes import letter
    from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
    from reportlab.lib.units import inch
    from reportlab.platypus import (Image, KeepTogether, ListFlowable, ListItem, PageBreak, Paragraph,
                                    SimpleDocTemplate, Spacer, Table, TableStyle)

    data_dir = Path(data_dir)
    cmp_path = data_dir / "outputs" / "comparison.json"
    ss = getSampleStyleSheet()
    body = ParagraphStyle("body", parent=ss["BodyText"], fontName="Helvetica", fontSize=10.5, leading=15,
                          textColor=colors.HexColor(INK), alignment=TA_LEFT, spaceAfter=7)
    small = ParagraphStyle("small", parent=body, fontSize=8.5, leading=11, textColor=colors.HexColor(INK2))
    h1 = ParagraphStyle("h1", parent=ss["Heading1"], fontName="Helvetica-Bold", fontSize=20, leading=24,
                        textColor=colors.HexColor(INK), spaceAfter=10, keepWithNext=1)
    h2 = ParagraphStyle("h2", parent=ss["Heading2"], fontName="Helvetica-Bold", fontSize=14, leading=18,
                        textColor=colors.HexColor(INK), spaceBefore=12, spaceAfter=6, keepWithNext=1)
    h3 = ParagraphStyle("h3", parent=ss["Heading3"], fontName="Helvetica-Bold", fontSize=11.5, leading=15,
                        textColor=colors.HexColor(INK), spaceBefore=8, spaceAfter=4, keepWithNext=1)
    cover_t = ParagraphStyle("cover", parent=h1, fontSize=28, leading=34, spaceAfter=18, keepWithNext=0)
    width = letter[0] - 2 * inch

    def table(rows, col_widths=None):
        rows = [[Paragraph(_md_inline(str(c)), small) for c in r] for r in rows]
        t = Table(rows, colWidths=col_widths, repeatRows=1, hAlign="LEFT")
        t.setStyle(TableStyle([("LINEBELOW", (0, 0), (-1, 0), 0.8, colors.HexColor(AXIS)),
                               ("LINEBELOW", (0, 1), (-1, -1), 0.3, colors.HexColor(GRID)),
                               ("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
                               ("VALIGN", (0, 0), (-1, -1), "TOP"),
                               ("TOPPADDING", (0, 0), (-1, -1), 3), ("BOTTOMPADDING", (0, 0), (-1, -1), 3)]))
        return t

    def image(path, caption=None, w=width):
        from reportlab.lib.utils import ImageReader
        iw, ih = ImageReader(str(path)).getSize()
        parts = [Image(str(path), width=w, height=w * ih / iw)]
        if caption:
            parts.append(Paragraph(_md_inline(caption), small))
        return KeepTogether(parts + [Spacer(1, 8)])

    figs_all: dict = {}
    expl_all: dict = {}
    caps_all: dict = {}

    def run_report(data_dir, prefix, heading, story):
        """Appends one run's analysis report to story. Returns (df, meta)."""
        data_dir = Path(data_dir)
        out = data_dir / "outputs"
        figdir = out / "figures"
        figdir.mkdir(parents=True, exist_ok=True)
        df = pd.read_parquet(out / "posts_analyzed.parquet")
        df["created_at"] = pd.to_datetime(df["created_at"], utc=True)
        meta = json.loads((out / "run_meta.json").read_text()) if (out / "run_meta.json").exists() else {}
        steps = json.loads((out / "cleaning_log.json").read_text()) if (out / "cleaning_log.json").exists() else {}
        manifest = [json.loads(l) for l in (data_dir / "manifest.jsonl").read_text().splitlines()] \
            if (data_dir / "manifest.jsonl").exists() else []
        qwords = query_stopwords(meta.get("value", ""), meta.get("aliases", [])) | hidden

        # ---- figures
        figs = {}
        has = lambda c: c in df.columns and df[c].notna().any()
        counts, dcounts, hg, tag_min, g = Counter(), Counter(), None, None, None
        if len(df):
            figs["volume"] = fig_volume(df, figdir / "volume.png")
            counts = term_counts(df, qwords)
            dcounts = doc_counts(df, qwords)
            if counts:
                figs["wordcloud"] = fig_wordcloud(counts, figdir / "wordcloud.png")
                figs["top_terms"] = fig_bars(pd.Series(dict(dcounts.most_common(20))), figdir / "top_terms.png", "Posts and articles using the word")
            if meta.get("network", "post") == "flow":
                g = word_flow_network(df, qwords, window=meta.get("flow_window", 3), min_count=meta.get("min_edge", 5))
                figs["network"] = fig_flow_network(g, figdir / "word_network.png", max_labels=80)
            else:
                g = cooccurrence_network(df, qwords, min_count=meta.get("min_edge", 5))
                figs["network"] = fig_network(g, figdir / "word_network.png")
            hg, tag_min = None, None
            if "hashtags" in df:
                for k in dict.fromkeys([meta.get("min_tag_edge", 3), 2, 1]):
                    hg = hashtag_network(df, list(meta.get("query_tags", [])) + sorted(hidden), min_count=k)
                    if hg.number_of_nodes() >= 3:
                        tag_min = k
                        figs["hashtags"] = fig_hashtag_map(hg, figdir / "hashtag_network.png")
                        break
        if has("sent_label"):
            figs["sentiment"] = fig_sentiment_by_platform(df, figdir / "sentiment_by_platform.png")
            if has("sent_score"):
                figs["sentiment_time"] = figs["weekly_sentiment"] = fig_sentiment_time(df, figdir / "sentiment_time.png")
        if has("emo_label"):
            figs["emotion"] = fig_bars(df["emo_label"].value_counts(normalize=True), figdir / "emotion.png", "Share of posts")
        if has("stance_label"):
            figs["stance"] = fig_bars(df["stance_label"].value_counts(normalize=True), figdir / "stance.png", "Share of posts")
        jload = lambda name: json.loads((out / name).read_text()) if (out / name).exists() else {}
        n_all = max(len(df), 1)
        expl = {}
        if len(df) and counts:
            top5 = [w for w, _ in counts.most_common(5)]
            expl["wordcloud"] = (f"The bigger the word, the more often it appears across all {len(df):,} posts, articles and blog posts. "
                                 "The query's own words and common words such as \"the\" are left out. The largest are "
                                 + ", ".join(top5[:-1]) + f" and {top5[-1]}." if len(top5) > 1 else
                                 f"The bigger the word, the more often it appears. The largest is {top5[0]}.")
            t3 = dcounts.most_common(3)
            expl["top_terms"] = (f"Each bar counts the posts and articles that use the word at least once, out of {len(df):,}. "
                                 + " ".join(f"\"{w}\" appears in {c:,} ({c / n_all:.0%})." for w, c in t3)
                                 + " A word used many times in one article still counts once, so long articles don't dominate.")
        else:
            expl["wordcloud"] = expl["top_terms"] = "There was no text left to count after cleaning."
        if has("sent_score"):
            sm, word = sentiment_series(df)
            vfile = data_dir / "validation" / "validation_sentiment.json"
            checked = ("It was checked against hand coding (see the validation scores)." if vfile.exists()
                       else "Nobody has checked these scores by hand, so treat small moves as noise.")
            if len(sm):
                lo, hi = sm.idxmin(), sm.idxmax()
                fmt = "%d %b %Y" if word != "month" else "%B %Y"
                expl["sentiment_time"] = (f"The thick line is the mean sentiment score of all items in each {word}, from -1 (most negative) to 1 "
                                          f"(most positive). Thin lines show each source. Each point is a {word} because the data covers "
                                          f"{(df['created_at'].max() - df['created_at'].min()).days + 1} days, and {word}s with fewer than 5 items are left out. "
                                          f"The overall mean is {df['sent_score'].mean():+.2f}. The lowest {word} was {lo:{fmt}} ({sm[lo]:+.2f}) "
                                          f"and the highest {hi:{fmt}} ({sm[hi]:+.2f}). {checked}")
            else:
                expl["sentiment_time"] = "Too few items per period to draw sentiment over time."
        else:
            expl["sentiment_time"] = "Sentiment didn't run for this dataset."
        if "hashtags" in figs:
            tops = sorted(hg.nodes, key=lambda x: -hg.nodes[x]["count"])[:5]
            ncom = len({hg.nodes[x].get("community", 0) for x in hg.nodes})
            expl["hashtags"] = (f"Each dot is a hashtag, sized by how many posts use it. A line joins two hashtags used together in at least "
                                f"{tag_min} post{'s' if tag_min != 1 else ''}. Colours mark {ncom} group{'s' if ncom != 1 else ''} of hashtags that tend to "
                                "travel together. The query's own tags are left out, so the map shows what people paired them with. "
                                "The most used are " + ", ".join("#" + t for t in tops) + ".")
        else:
            ntag = int(df["hashtags"].map(lambda h: len(h) > 0 if hasattr(h, "__len__") else False).sum()) if "hashtags" in df else 0
            expl["hashtags"] = (f"No hashtag network could be drawn. Only {ntag:,} of {len(df):,} items carried hashtags, and too few "
                                "besides the query's own were used together. News articles and blog posts rarely use hashtags.")
        rule, word = time_bin(df) if len(df) else ("W-SUN", "week")
        days = (df["created_at"].max() - df["created_at"].min()).days + 1 if len(df) else 0
        if len(df):
            vol = df.set_index("created_at").resample(rule).size()
            peaks = vol.sort_values(ascending=False).head(2)
            per = df["platform"].value_counts()
            expl["volume"] = (f"Each line counts one source's items per {word}. Each point is a {word} because the data covers {days} "
                              f"day{'s' if days != 1 else ''}. In all, {len(df):,} items ran from {bin_label(df['created_at'].min(), 'day')} to "
                              f"{bin_label(df['created_at'].max(), 'day')}: " + and_list([f"{k} {v:,}" for k, v in per.items()]) + ". "
                              f"The busiest {word} was {bin_label(peaks.index[0], word)}, with {int(peaks.iloc[0]):,} items"
                              + (f", and the next busiest was {bin_label(peaks.index[1], word)}, with {int(peaks.iloc[1]):,}"
                                 if len(peaks) > 1 and peaks.iloc[1] > 0 else "")
                              + f". The first and last {word}s may be partial, so a dip there can be the window edge.")
        else:
            expl["volume"] = "No items were left after cleaning."
        if len(df) and g is not None and g.number_of_edges():
            top = sorted(g.edges(data=True), key=lambda e: -e[2].get("weight", 0))[:3]
            links = and_list([f"\"{a}\" to \"{b}\" ({d.get('weight', 0):,} times)" for a, b, d in top])
            if meta.get("network", "post") == "flow":
                expl["network"] = ("An arrow from one word to another means the second word often follows the first within a few words, "
                                   "across all the collected text. Thicker lines mean the pair occurs more often, and colours mark groups of "
                                   f"words that tend to appear together. The strongest links are {links}.")
            else:
                expl["network"] = ("A line joins two words used in the same post. Thicker lines mean more posts use both, and colours "
                                   f"mark groups of words that tend to appear together. The strongest pairs are {links}.")
        else:
            expl["network"] = "Too few words were repeated together to draw a word network."
        if has("sent_label"):
            method = meta.get("sentiment_method") or "the sentiment model"
            ct = pd.crosstab(df["platform"], df["sent_label"])
            parts = []
            for p_, row in ct.iterrows():
                n_ = int(row.sum())
                sh = {lab: row.get(lab, 0) / n_ for lab in ("positive", "neutral", "negative")}
                parts.append(f"{p_.capitalize()} ({n_:,} items): {sh['positive']:.0%} positive, {sh['neutral']:.0%} neutral and "
                             f"{sh['negative']:.0%} negative.")
            n_all_s = int(df["sent_label"].notna().sum())
            kp, kn = int((df["sent_label"] == "positive").sum()), int((df["sent_label"] == "negative").sum())
            pp, plo, phi = wilson(kp, n_all_s)
            pn, nlo, nhi = wilson(kn, n_all_s)
            vfile = data_dir / "validation" / "validation_sentiment.json"
            expl["sentiment"] = (f"Each bar splits one source's items into negative, neutral and positive, as scored by {method}. "
                                 + " ".join(parts) + f" Across all {n_all_s:,} items, {pp:.0%} were positive (95% interval {plo:.0%} to "
                                 f"{phi:.0%}) and {pn:.0%} negative ({nlo:.0%} to {nhi:.0%}). "
                                 + ("The scores were checked against hand coding (see the validation scores)." if vfile.exists()
                                    else "Nobody has checked these scores by hand, and a word-based score measures the tone of the "
                                         "words, which differs from support for or opposition to the topic."))
        else:
            expl["sentiment"] = "Sentiment didn't run for this dataset."
        sword = sentiment_bin(df)[1] if len(df) else "week"
        caps = {"volume": f"Items per {word}, by source.",
                "wordcloud": "Word cloud. Word size follows how often the word is used.",
                "top_terms": "The 20 most used words, with the number of posts and articles that use each one.",
                "network": "Word network. Arrows point from a word to the word that often follows it." if meta.get("network", "post") == "flow"
                           else "Word network. Lines join words used in the same post.",
                "hashtags": "Hashtag network. Lines join hashtags used in the same post.",
                "sentiment": "Share of items scored negative, neutral and positive, by source.",
                "sentiment_time": f"Mean sentiment per {sword}, from -1 (negative) to +1 (positive), for all items and each source."}
        caps_all.update({prefix + k: v for k, v in caps.items()})
        expl_all.update({prefix + k: v for k, v in expl.items()})
        audit_rep, desc, keys = jload("audit.json"), jload("descriptives.json"), jload("keyness.json")
        vdir = data_dir / "validation"

        def fig_flow(name, caption=None):
            return [image(figs[name], caption)] if name in figs else [Paragraph(f"(Figure '{name}' not available for this run.)", small)]

        # ---- part 2: analysis report
        story.append(Paragraph(_md_inline(heading), h1))
        num = itertools.count(1)
        sec = lambda name: Paragraph(f"{next(num)}. {name}", h2)
        ptext = lambda t: Paragraph(_md_inline(t), body)
        pct = lambda v: f"{v:.0%}"

        story.append(sec("Data collected"))
        if meta.get("variants"):
            story += [Paragraph("Query dictionary", h3),
                      table([["Variant", "Match type", "Role"]] + [[v["variant"], v["match_type"], v["role"]] for v in meta["variants"]])]
        if manifest:
            rows = [["Source", "Status", "Rows", "Search strings", "Note"]]
            for m in manifest:
                rows.append([m["platform"], m["status"], f"{m['rows']:,}", ", ".join(m.get("search_strings", []))[:80],
                             (m.get("error") or "")[:90]])
            story += [Paragraph("Collection runs", h3), table(rows, [0.9 * inch, 0.9 * inch, 0.6 * inch, 1.8 * inch, 2.3 * inch])]
        by_p = df.groupby(["platform", "kind"]).size().unstack(fill_value=0)
        rows = [["Platform"] + list(by_p.columns) + ["Total"]]
        rows += [[p] + [f"{v:,}" for v in r] + [f"{r.sum():,}"] for p, r in by_p.iterrows()]
        story += [Spacer(1, 6), Paragraph("Items kept for analysis, by platform and type", h3), table(rows)]
        if steps:
            story += [Paragraph("Cleaning steps", h3),
                      table([["Step", "Rows left"]] + [[k.replace("_", " "), f"{v:,}"] for k, v in steps.items()])]
        rule, word = time_bin(df) if len(df) else ("W", "week")
        story += fig_flow("volume", f"Posts per {word} by platform. The first and last {word}s may be partial, so a dip there "
                                    "can be the window edge.")

        story.append(sec("Data quality"))
        if audit_rep:
            if audit_rep.get("warnings"):
                story.append(Paragraph("Warnings", h3))
                story += [ptext(f"- {w}") for w in audit_rep["warnings"]]
            cols = ["collected", "empty", "outside_window", "off_topic", "reposts", "exact_duplicates", "near_duplicates", "not_english", "kept"]
            heads = ["Source", "In", "Empty", "Out of window", "Off topic", "Reposts", "Exact dup", "Near dup", "Not English", "Kept"]
            story += [Paragraph("What each step removed, by source", h3),
                      table([heads] + [[r["source"]] + [f"{r[c]:,}" for c in cols] for r in audit_rep.get("by_source", [])])]
            if audit_rep.get("match_type"):
                mt = audit_rep["match_type"]
                tot = max(sum(mt.values()), 1)
                story += [Paragraph("How kept items matched the query", h3),
                          table([["Match type", "Items", "Share"]] + [[k, f"{v:,}", pct(v / tot)] for k, v in mt.items()])]
            if audit_rep.get("posts_per_author"):
                story += [Paragraph("Concentration: posts per account", h3),
                          table([["Platform", "Accounts", "Median", "90th pct", "Max", "Top 1% share", "Top 10 share"]] +
                                [[p, f"{v['authors']:,}", f"{v['median']:.0f}", f"{v['p90']:.0f}", f"{v['max']:,}",
                                  pct(v["share_from_top_1pct"]), pct(v["share_from_top_10"])] for p, v in audit_rep["posts_per_author"].items()])]
            if audit_rep.get("outlets"):
                o = audit_rep["outlets"]
                top5 = ", ".join(f"{k} ({v:,})" for k, v in list(o["top"].items())[:5])
                story.append(ptext(f"News items came from {o['count']:,} outlets: {top5}." if o["count"] <= 5 else
                                   f"News items came from {o['count']:,} outlets. The top five supplied {pct(o['share_from_top_5'])}: {top5}."))
            if audit_rep.get("fulltext_status"):
                story.append(ptext("Article text status: " + ", ".join(f"{k} {v:,}" for k, v in audit_rep["fulltext_status"].items()) + "."))
            if audit_rep.get("source_overlap"):
                story += [Paragraph("The same article found by more than one source", h3),
                          table([["Sources", "URLs"]] + [[k, f"{v:,}"] for k, v in audit_rep["source_overlap"].items()])]
            if audit_rep.get("requests"):
                story += [Paragraph("Requests", h3),
                          table([["Source", "Calls", "Failed", "Records", "Status codes"]] +
                                [[k, f"{v['calls']:,}", f"{v['failed']:,}", f"{v['records']:,}",
                                  ", ".join(f"{c}: {n}" for c, n in v["statuses"].items())] for k, v in audit_rep["requests"].items()])]
        else:
            story.append(ptext("No audit file. Run the audit or analyze command."))

        heads = jload("headlines.json") if (out / "headlines.json").exists() else []
        if heads:
            story.append(sec("Main headlines"))
            story.append(ptext("The stories the most outlets ran in the window. Headlines that share most of their words within a few days "
                               "are grouped as one story. Links go to the outlets' own pages."))
            rows = [["Story", "Outlets", "Items", "Dates", "Coverage"]]
            for h in heads[:12]:
                links = ", ".join(f"[{_plain(l['outlet'] or domain_of(l['url']))}]({l['url']})" for l in h["links"][:4] if str(l["url"]).startswith("http"))
                rows.append([_plain(h["headline"]), str(h["outlets"]), str(h["items"]), f"{h['first']} to {h['last']}", links])
            story.append(table(rows, [2.4 * inch, 0.6 * inch, 0.5 * inch, 1.0 * inch, 2.0 * inch]))
        if desc:
            story.append(sec("Who and what is in the data"))
            rows = [["Platform", "Items", "Accounts or outlets", "Posts", "Replies", "Reposts", "News", "Median engagement", "90th pct"]]
            for p, d in desc.items():
                if p.startswith("_"):
                    continue
                k, e = d.get("kind_share", {}), d.get("engagement", {})
                rows.append([p, f"{d['items']:,}", f"{d['unique_authors']:,}", pct(k.get("post", 0)), pct(k.get("comment", 0)),
                             pct(k.get("repost", 0)), pct(sum(k.get(x, 0) for x in NEWS_KINDS)),
                             f"{e['median']:,.0f}" if e else "n/a", f"{e['p90']:,.0f}" if e else "n/a"])
            story.append(table(rows))
            story.append(ptext("Engagement is likes plus replies plus shares. It is skewed, so the table shows the median and the "
                              "90th percentile, not the mean. Platforms count engagement differently, so compare within a platform."))
            if desc.get("_top_domains"):
                story.append(ptext("Most linked or published domains: " + ", ".join(f"{k} ({v:,})" for k, v in list(desc["_top_domains"].items())[:12]) + "."))

        story.append(sec("Sentiment"))
        if has("sent_label"):
            bal = df.groupby("platform")["sent_score"].mean()
            story.append(ptext(f"Mean sentiment with each platform weighted equally: **{bal.mean():+.2f}** on a scale from -1 (negative) "
                              f"to +1 (positive). Method: `{meta.get('sentiment_method', 'not recorded')}`."))
            story += fig_flow("sentiment", "Share of negative, neutral and positive posts by platform.")
            st = share_table(df, "sent_label")
            story.append(table([["Group", "Label", "n", "Share", "95% interval"]] +
                               [[r.group, r.label, f"{r.n:,}", pct(r.share), f"{r.ci_low:.0%} to {r.ci_high:.0%}"] for r in st.itertuples()]))
            story += fig_flow("weekly_sentiment", "Weekly mean sentiment by platform.")
        else:
            story.append(ptext("No sentiment model ran for this dataset."))

        if has("emo_label"):
            story += [sec("Emotion"), ptext(f"Model: `{MODELS['emotion']}` (anger, disgust, fear, joy, neutral, sadness, surprise).")]
            story += fig_flow("emotion", "Share of posts by strongest emotion.")
        if has("stance_label"):
            story += [sec("Stance"),
                      ptext(f"Zero-shot stance toward \"{meta.get('stance_target', meta.get('value', ''))}\" with `{MODELS['stance']}`. "
                           "Read it together with the Validation section.")]
            story += fig_flow("stance", "Share of posts by stance.")
            st = share_table(df, "stance_label")
            story.append(table([["Group", "Label", "n", "Share", "95% interval"]] +
                               [[r.group, r.label, f"{r.n:,}", pct(r.share), f"{r.ci_low:.0%} to {r.ci_high:.0%}"] for r in st.itertuples()]))
            if has("sent_label"):
                x = pd.crosstab(df["stance_label"], df["sent_label"], normalize="index")
                story += [Paragraph("Stance by sentiment", h3),
                          ptext("Stance and sentiment measure different things: an angry post can still support the cause. "
                               "Each row shows how posts with that stance split by tone."),
                          table([["Stance"] + list(x.columns)] + [[i] + [pct(v) for v in r] for i, r in x.iterrows()])]

        if (out / "robustness.csv").exists():
            rb = pd.read_csv(out / "robustness.csv")
            story += [KeepTogether([sec("Robustness"),
                      ptext("Each row recomputes the headline shares on another reasonable version of the data, with 95% "
                           "intervals. A result that changes a lot between rows depends on that choice and should be reported that way."),
                      table([list(rb.columns)] + [[f"{v:,}" if isinstance(v, (int,)) else str(v) for v in r] for r in rb.itertuples(index=False)])])]

        story.append(sec("Topics"))
        if (out / "topics.csv").exists():
            tp = pd.read_csv(out / "topics.csv")
            tp = tp[tp["Topic"] != -1].head(12)
            rows = [["Topic", "Posts", "Top terms"]] + [[str(r.Topic), f"{r.Count:,}", str(r.Name).split("_", 1)[-1].replace("_", ", ")]
                                                       for r in tp.itertuples()]
            story += [ptext("BERTopic on `all-MiniLM-L6-v2` embeddings. Topic -1 (posts that fit no topic) is left out."),
                      table(rows, [0.6 * inch, 0.8 * inch, 5.1 * inch])]
        if (out / "topics_nmf.csv").exists():
            tn = pd.read_csv(out / "topics_nmf.csv")
            story += [ptext(f"Baseline: NMF on TF-IDF, {meta.get('nmf_k', len(tn))} topics, refitted with three seeds. Mean stability "
                           f"**{meta.get('nmf_stability', float('nan')):.2f}** (1 means the same top words every time). Name only the stable topics."),
                      table([["Topic", "Posts", "Top terms", "Stability"]] + [[str(r.Topic), f"{r.Count:,}", r._3, f"{r.Stability:.2f}"]
                                                                            for r in tn.itertuples()], [0.6 * inch, 0.8 * inch, 4.2 * inch, 0.9 * inch])]
        if not (out / "topics.csv").exists() and not (out / "topics_nmf.csv").exists():
            story.append(ptext("Topic modelling did not run for this dataset. NMF needs at least 50 posts and BERTopic at least 200."))

        story.append(KeepTogether([sec("Words")] + fig_flow("wordcloud", "Word cloud. The query's own words are removed.")))
        story += fig_flow("top_terms", "The 20 most used words.")
        if meta.get("network", "post") == "flow":
            story += fig_flow("network", "Word flow network, built from all the collected text pooled together: posts, comments, "
                                         "headlines, articles, blog posts and video transcripts. An arrow from A to B means B often follows A "
                                         f"(within {meta.get('flow_window', 3)} words, stop words removed). Thicker lines mean the pair occurs more often "
                                         f"across the whole dataset (at least {meta.get('min_edge', 5)} times). Colours mark communities of words "
                                         "that travel together. The GEXF file in outputs/ opens in Gephi.")
            if (out / "word_flow_edges.csv").exists():
                fe = pd.read_csv(out / "word_flow_edges.csv").head(15)
                if len(fe):
                    story.append(table([["From", "To", "Times", "The other way"]] +
                                       [[r["from"], r["to"], f"{r['count']:,}", f"{r['reverse']:,}"] for _, r in fe.iterrows()],
                                       [1.6 * inch, 1.6 * inch, 1.0 * inch, 1.2 * inch]))
        else:
            story += fig_flow("network", "Word co-occurrence network. Words are linked when they appear in the same post at least "
                                         f"{meta.get('min_edge', 5)} times. Colours mark communities of words that travel together. "
                                         "The GEXF file in outputs/ opens in Gephi.")
        if keys:
            story.append(Paragraph("Words that set groups apart (keyness)", h3))
            story.append(ptext("Log-odds ratio with an informative Dirichlet prior. A z-score above 2 means the word leans clearly to that group."))
            for name, k in keys.items():
                a_name, b_name = name.split(" vs ")
                fmt = lambda rs: ", ".join(f"{r['word']} ({r['z']:+.1f})" for r in rs[:10])
                story.append(table([["Comparison", f"Leans to {a_name} ({k['a_posts']:,} posts)", f"Leans to {b_name} ({k['b_posts']:,} posts)"],
                                    [name, fmt(k["a"]), fmt(k["b"])]], [1.3 * inch, 2.6 * inch, 2.6 * inch]))
                story.append(Spacer(1, 4))

        if "hashtags" in figs or (out / "hashtag_neighbours.csv").exists() and (out / "hashtag_neighbours.csv").stat().st_size > 10:
            story.append(KeepTogether([sec("Hashtags")] + fig_flow("hashtags", "Hashtags used in the same post. Colours mark Louvain communities.")))
            if (out / "hashtag_neighbours.csv").exists() and (out / "hashtag_neighbours.csv").stat().st_size > 10:
                hn = pd.read_csv(out / "hashtag_neighbours.csv").head(15)
                story.append(table([["Hashtag", "Posts", "Most frequent partners (posts together)"]] +
                                   [[f"#{r.node}", f"{r.count:,}", r.neighbours] for r in hn.itertuples()], [1.3 * inch, 0.7 * inch, 4.5 * inch]))

        if (out / "top_entities.csv").exists():
            ent = pd.read_csv(out / "top_entities.csv").head(20)
            story += [sec("People, organisations and places"),
                      table([["Entity", "Type", "Mentions"]] + [[r.entity, r.type, f"{int(r._3):,}"] for r in ent.itertuples()])]

        story.append(sec("Validation"))
        agree_j = json.loads((vdir / "agreement.json").read_text()) if (vdir / "agreement.json").exists() else {}
        vals = [json.loads(f.read_text()) for f in sorted(vdir.glob("validation_*.json"))] if vdir.exists() else []
        if agree_j:
            story += [Paragraph("Agreement between the two coders", h3),
                      table([["Task", "Items", "Agreement", "Cohen's kappa", "Krippendorff's alpha", "Reading"]] +
                            [[t, v.get("items_both", 0), pct(v["percent_agreement"]) if "percent_agreement" in v else "n/a",
                              v.get("cohen_kappa", "n/a"), v.get("krippendorff_alpha", "n/a"), v.get("reading", v.get("note", ""))]
                             for t, v in agree_j.items()])]
        for v in vals:
            if v.get("note"):
                continue
            if v["task"] == "relevance":
                lo, hi = v["precision_strict"][1], v["precision_strict"][2]
                story.append(ptext(f"**Query precision** on {v['items']} hand-checked items: {pct(v['precision_strict'][0])} relevant "
                                  f"(95% interval {pct(lo)} to {pct(hi)}), {pct(v['precision_incl_partly'][0])} counting partly relevant. "
                                  f"Verdict: {v['verdict']}."))
                continue
            story += [Paragraph(f"{v['task'].capitalize()}: model against settled labels", h3),
                      ptext(f"{v['items']} items. Accuracy {v['accuracy']:.2f}, macro-F1 **{v['macro_f1']:.2f}**. Verdict: {v['verdict']}."),
                      table([["Label", "Precision", "Recall", "F1", "Items"]] +
                            [[l, f"{c['precision']:.2f}", f"{c['recall']:.2f}", f"{c['f1-score']:.2f}", int(c["support"])]
                             for l, c in v["per_class"].items()])]
            if v.get("corrected_shares"):
                story.append(table([["Label", "Model share", "Corrected share", "95% interval"]] +
                                   [[l, pct(v["model_shares"].get(l, 0)), pct(c), f"{pct(v['corrected_ci95'][l][0])} to {pct(v['corrected_ci95'][l][1])}"]
                                    for l, c in v["corrected_shares"].items()]))
        if not vals and not agree_j:
            story.append(ptext("No hand-labelled validation yet. Treat every model result above as unvalidated."))

        story.append(sec("Methods and limits"))
        steps_not_sources = {"purge", "fetch-text", "videos"}
        covered = sorted({m["platform"] for m in manifest if m["status"] == "ok"} - steps_not_sources) or sorted(df["platform"].unique())
        missing = sorted({m["platform"] for m in manifest if m["status"] != "ok"} - steps_not_sources)
        for line in [
            f"Sources covered: {', '.join(covered)}." + (f" Sources that returned nothing or were unavailable: {', '.join(missing)}." if missing else ""),
            "Only public material was collected, through official APIs, publisher feeds, sitemaps and public web pages that robots.txt allows. "
            "Nothing behind a login or paywall was read, and sources that needed a key the run didn't have were skipped. "
            "X, LinkedIn, Facebook and TikTok offer no free official route to public posts, so they are absent.",
            *([f"{meta['videos_transcribed']:,} posts had an English video transcribed on this computer with the user's approval, and the "
               "transcript was added to the post's text before analysis. YouTube videos were not transcribed, because YouTube's terms bar downloading them."]
              if meta.get("videos_transcribed") else []),
            "Each platform has its own audience and its own search ranking. Results are reported per platform, and the headline sentiment gives each platform equal weight.",
            "The sample is what the official search endpoints, feeds and sitemaps returned for the query dictionary above. It is not every post on the topic, and no one can know true recall.",
            "Text was normalised, " + (f"exact duplicates and near-duplicates (MinHash, Jaccard {meta['near_dup']:.2f} or more) were merged"
                                       if meta.get("near_dup", 0.85) else "exact duplicates were merged (near-duplicate merging was off for this run)")
            + " and counted as copies, reposts were set aside" + (", and non-English items were dropped with lingua." if meta.get("english_only", True) else ", and all languages were kept."),
            "Model outputs are estimates. The Validation section shows how far they agree with hand labels, and the Robustness section shows how far they move when the data changes.",
        ]:
            story.append(ptext(line))
        if meta.get("repro"):
            r = meta["repro"]
            story += [Paragraph("Reproducibility", h3),
                      ptext(f"titus-scraper {r.get('titus_scraper_version', '')}, script SHA-256 `{r.get('script_sha256', '')[:16]}`, Python {r.get('python', '')}. "
                           "Packages: " + ", ".join(f"{k} {v}" for k, v in r.get("packages", {}).items()) + ". "
                           f"Run at {r.get('run_at', '')[:16]} UTC. Raw responses and the request log (requests.jsonl) are kept in the run folder.")]

        skipped = {}
        for m in manifest:
            skipped[m["platform"]] = m
        skipped = {k: m for k, m in skipped.items() if m.get("status") != "ok" and k not in steps_not_sources}
        if skipped:
            story.append(Paragraph("Sources the run could not use", h3))
            rows = [["Source", "Why", "How to add it"]]
            for k, m in skipped.items():
                h = ACCESS_HELP.get(k)
                how = (f"Set {', '.join(h['vars'])}. {h['get']} [{h['url']}]({h['url']})" if h and m["status"] == "no key"
                       else "No free route for automated reading." if k in CLOSED else "")
                rows.append([k, (m.get("error") or m["status"])[:160], how])
            story.append(table(rows, [0.9 * inch, 2.4 * inch, 3.2 * inch]))
            story.append(ptext("Keys go in environment variables, never in a file or a chat. access_report.md in the run folder has the steps."))
        sl = pd.read_csv(out / "sources.csv", dtype=str, keep_default_na=False) if (out / "sources.csv").exists() else source_list(df)
        story.append(sec("Sources"))
        soc = df[df["platform"].isin(SOCIAL_PLATFORMS)]
        if len(soc):
            story.append(ptext("Social posts came from " + ", ".join(f"{k} ({v:,} items)" for k, v in soc["platform"].value_counts().items())
                               + ", through each platform's public search. Posts by ordinary users are not listed one by one, to protect them. "
                               "Public figures and organisations quoted in the blog are linked where they are quoted."))
        if len(sl):
            by = sl.groupby(["outlet", "domain", "country", "type"]).size().reset_index(name="items").sort_values("items", ascending=False)
            cap = max_sources if max_sources > 0 else len(by)
            story.append(Paragraph("Outlets and blogs", h3))
            story.append(table([["Outlet", "Country", "Type", "Items"]] +
                               [[f"[{r.outlet}](https://{r.domain})" if r.domain and "." in str(r.domain) else r.outlet, r.country or "",
                                 r.type, f"{r.items:,}"] for r in by.head(cap).itertuples()],
                               [3.0 * inch, 1.5 * inch, 0.8 * inch, 0.8 * inch]))
            if len(by) > cap:
                story.append(ptext(f"The {cap} outlets with the most items are shown, of {len(by):,}. outputs/sources.csv lists them all."))
            story.append(Paragraph("Articles and posts", h3))
            items = sl[sl["url"].astype(str).str.startswith("http")]
            shown = relevant_sources(df, meta, max_sources)
            for r in shown.itertuples():
                story.append(Paragraph(_md_inline(f"{r.date}. {_plain(r.outlet)}. [{_plain(r.title)[:150]}]({r.url})"), small))
            if len(items) > len(shown):
                story.append(ptext(f"The {len(shown):,} most relevant of {len(items):,} items are listed. outputs/sources.csv has every one with its link."))
        figs_all.update({prefix + k: v for k, v in figs.items()})
        return df, meta

    part2 = []
    runs = []
    if cmp_path.exists():
        cm = json.loads(cmp_path.read_text())
        figs_all.update({k: Path(v) for k, v in cm.get("figures", {}).items()})
        compare_story(cm, part2, table, image, figs_all, body, small, h1, h2, h3, width)
        for i, (d, label) in enumerate(zip(cm["runs"], cm["labels"])):
            part2.append(PageBreak())
            runs.append(run_report(Path(d), f"t{i + 1}.", f"Analysis report: {label}", part2))
        df = pd.concat([r[0] for r in runs], ignore_index=True)
        meta = {"title": cm.get("title") or "What people said about " + " and ".join(cm["labels"]),
                "since": cm.get("since", ""), "until": cm.get("until", ""), "cover": "Comparison of " + (" and ".join(cm["labels"]) if len(cm["labels"]) == 2 else ", ".join(cm["labels"][:-1]) + " and " + cm["labels"][-1])}
    else:
        df, meta = run_report(data_dir, "", "Analysis report", part2)

    def fig_block(name, caption=None):
        return [("figure", figs_all[name], caption)] if name in figs_all else [("small", f"(Figure '{name}' not available for this run.)")]

    # ---- part 1, built once as neutral blocks, so every output format carries the same content
    fmt = (fmt or Path(out_path).suffix.lstrip(".") or "pdf").lower()
    fmt = FORMAT_ALIASES.get(fmt, fmt)
    if fmt not in REPORT_FORMATS:
        raise SystemExit(f"report: unknown format '{fmt}'. Use one of: {', '.join(REPORT_FORMATS)}.")
    title = title or meta.get("title") or f"What people said about {meta.get('label') or meta.get('value', 'this topic')}"
    window = f"{meta.get('since', '')[:10]} to {meta.get('until', '')[:10]}" if meta.get("since") else "full history"
    cover = [("cover_title", title),
             ("p", f"{meta.get('cover') or (meta.get('type', '').capitalize() + ' ' + meta.get('value', ''))}, {window}. "
                   f"{len(df):,} posts from {df['platform'].nunique()} sources after cleaning.")]
    if author:
        cover.append(("p", author))
    cover.append(("small", f"Generated {datetime.now(timezone.utc):%d %B %Y}"))
    cover.append(("spacer", 0.3))
    if full and fmt == "pdf":
        cover.append(("small", "Part 1 is the blog post. Part 2 is the analysis report behind it."))
    elif full:
        cover.append(("small", "The blog post, its key figures and its sources. The full analysis report (Part 2) is in the PDF version."))
    else:
        cover.append(("small", "The blog post, its key figures and its sources. The full analysis report is left out. "
                               "Rerun report with --full to add it."))
    p1 = [("small", "Part 1. Blog post")] if full and fmt == "pdf" else []
    used = set()

    def render(lines, max_bullets=None):
        """Turns the Markdown subset into blocks. max_bullets caps the bullets kept (for the Sources list). Returns bullets dropped."""
        bullets, para, dropped = [], [], [0]

        def flush():
            if bullets:
                p1.append(("bullets", list(bullets), "body"))
                bullets.clear()

        kept = 0
        for line in lines + [""]:
            s = line.strip()
            fig = re.fullmatch(r"\{\{figure:([\w.]+)(?:\|(.+))?\}\}", s)
            if (not s or s.startswith("#") or s.startswith(("- ", "* ")) or fig) and para:
                p1.append(("p", " ".join(para)))
                para = []
            if s.startswith(("- ", "* ")):
                if max_bullets is not None and kept >= max_bullets:
                    dropped[0] += 1
                    continue
                kept += 1
                bullets.append(s[2:])
                continue
            flush()
            if not s:
                continue
            if fig:
                name = fig.group(1)
                base = name.split(".")[-1]
                key = name[: len(name) - len(base)] + FIGURE_ALIASES.get(base, base)
                flows = fig_block(name, fig.group(2))
                if p1 and p1[-1][0] in ("h2", "h3"):
                    flows = [("keep", [p1.pop()] + flows)]     # a heading never sits alone above its figure
                p1.extend(flows)
                if key not in used and key in expl_all and key.split(".")[-1] in REQUIRED_FIGURES:
                    p1.append(("p", expl_all[key]))   # every key figure carries its explanation
                used.add(key)
            elif s.startswith("### "):
                p1.append(("h3", s[4:]))
            elif s.startswith("## "):
                p1.append(("h2", s[3:]))
            elif s.startswith("# "):
                p1.append(("h1", s[2:]))
            else:
                para.append(s)
        flush()
        return dropped[0]

    lines = Path(blog_path).read_text(encoding="utf-8").splitlines()
    if not has_synthesis(lines):
        log.warning("blog.md has no synthesis section. SKILL.md Step 9c asks for one, \"## What it all adds up to\", "
                    "that pulls the whole dataset together before the caveats.")
    cut = next((i for i, l in enumerate(lines) if re.match(r"^##\s+(sources|references)\b", l.strip(), flags=re.I)), None)
    main_lines, src_lines = (lines, []) if cut is None else (lines[:cut], lines[cut:])
    # the blog's own closing sections after Sources (rare) stay with the main text
    if src_lines:
        nxt = next((i for i, l in enumerate(src_lines[1:], 1) if re.match(r"^#{1,2}\s", l.strip())), None)
        if nxt is not None:
            main_lines, src_lines = main_lines + src_lines[nxt:], src_lines[:nxt]
    render(main_lines)

    # the key figures, each with its explanation, unless the post already placed them
    prefixes = [f"t{i + 1}." for i in range(len(json.loads(cmp_path.read_text())["runs"]))] if cmp_path.exists() else [""]
    labels = json.loads(cmp_path.read_text())["labels"] if cmp_path.exists() else [""]
    missing = [(px, lab, n) for px, lab in zip(prefixes, labels) for n in REQUIRED_FIGURES if px + n not in used]
    for i, (px, lab, n) in enumerate(missing):
        block = ([("h2", "Key figures")] if i == 0 else []) + [("h3", FIGURE_TITLES[n] + (f": {lab}" if lab else ""))]
        if px + n in figs_all:
            block.append(("figure", figs_all[px + n], caps_all.get(px + n)))
        block.append(("p", expl_all.get(px + n, "")))
        p1.append(("keep", block))

    if not full or fmt != "pdf":
        # the data behind the post, in brief, since Part 2 is left out
        p1.append(("h2", "About the data"))
        kept = df["platform"].value_counts()
        p1.append(("table", [["Source", "Items kept"]] + [[k, f"{v:,}"] for k, v in kept.items()] + [["Total", f"{len(df):,}"]], [3.0, 1.2]))
        notes = []
        for d in ([Path(r) for r in json.loads(cmp_path.read_text())["runs"]] if cmp_path.exists() else [data_dir]):
            mf = d / "manifest.jsonl"
            if mf.exists():
                last = {}
                for l in mf.read_text().splitlines():
                    m = json.loads(l)
                    last[m["platform"]] = m
                notes += [f"{k}: {(m.get('error') or m['status'])[:140]}" for k, m in last.items()
                          if m.get("status") != "ok" and k not in {"purge", "fetch-text", "videos"}]
        n_barred = int(ai_barred_mask(df).sum())
        if n_barred:
            p1.append(("small", f"{n_barred:,} items come from outlets whose terms forbid AI use. They are counted here and "
                                "were kept out of the material the AI assistant read."))
        if notes:
            p1.append(("h3", "Sources the run could not use"))
            p1.append(("bullets", list(dict.fromkeys(notes)), "small"))
            p1.append(("small", "access_report.md in the run folder explains how to add each one."))

    # sources: the post's own list, capped, or the most relevant items
    cap = max_sources if max_sources > 0 else None
    if src_lines:
        dropped = render(src_lines, cap)
        if dropped:
            p1.append(("small", f"The {cap} most relevant sources are listed. outputs/sources.csv has all of them with links."))
    else:
        rs = pd.concat([relevant_sources(d, m, max_sources) for d, m in
                        ([(r[0], r[1]) for r in runs] if cmp_path.exists() else [(df, meta)])]) if len(df) else pd.DataFrame()
        if len(rs):
            rs = rs.sort_values("score", ascending=False).head(cap) if cap else rs
            p1.append(("h2", "Sources"))
            p1.append(("bullets", [f"{_plain(r.outlet)}, \"{_plain(r.title)[:150]}\", {r.date}. [link]({r.url})" for r in rs.itertuples()], "body"))
            n_all = int((source_list(df)["url"].astype(str).str.startswith("http")).sum())
            if cap and n_all > len(rs):
                p1.append(("small", f"The {len(rs)} most relevant of {n_all:,} articles and blog posts. "
                                    "outputs/sources.csv lists every one with its link."))

    out_path = Path(out_path)
    if fmt == "docx":
        return _write_docx(cover, p1, out_path, title, author)
    if fmt == "md":
        return _write_md(cover, p1, out_path)
    if fmt == "html":
        return _write_html(cover, p1, out_path, title, author)
    if fmt == "tex":
        return _write_tex(cover, p1, out_path, title, author)

    # ---- PDF
    def to_flow(b):
        kind = b[0]
        if kind == "keep":
            return [KeepTogether([f for x in b[1] for f in to_flow(x)])]
        if kind == "figure":
            return [image(b[1], b[2])]
        if kind == "table":
            return [table(b[1], [w * inch for w in b[2]] if b[2] else None)]
        if kind == "bullets":
            style = small if b[2] == "small" else body
            return [ListFlowable([ListItem(Paragraph(_md_inline(x), style), leftIndent=12) for x in b[1]],
                                 bulletType="bullet", start="\u2022", leftIndent=12)]
        if kind == "spacer":
            return [Spacer(1, b[1] * inch)]
        style = {"cover_title": cover_t, "h1": h1, "h2": h2, "h3": h3, "small": small}.get(kind, body)
        return [Paragraph(_md_inline(b[1]), style)]

    story = [Spacer(1, 1.6 * inch)] + [f for b in cover for f in to_flow(b)] + [PageBreak()]
    story += [f for b in p1 for f in to_flow(b)]
    if full:
        story.append(PageBreak())
        story += [Paragraph("Part 2. Analysis report", small)] + part2

    def footer(canvas, doc):
        canvas.saveState()
        canvas.setFont("Helvetica", 8)
        canvas.setFillColor(colors.HexColor(MUTED))
        canvas.drawRightString(letter[0] - inch, 0.6 * inch, f"{doc.page}")
        canvas.restoreState()

    SimpleDocTemplate(str(out_path), pagesize=letter, leftMargin=inch, rightMargin=inch, topMargin=inch,
                      bottomMargin=inch, title=title, author=author or "titus-scraper").build(
        story, onFirstPage=lambda c, d: None, onLaterPages=footer)
    return out_path


SYNTHESIS_HEADING = re.compile(r"^#{2,3}\s+.*\b(adds? up|synthesis|the big picture|taken together|in sum)\b", re.I)


def has_synthesis(lines) -> bool:
    """True when the post has a synthesis section, such as "## What it all adds up to"."""
    return any(SYNTHESIS_HEADING.match(l.strip()) for l in lines)


REPORT_FORMATS = ("pdf", "docx", "md", "html", "tex")
FORMAT_ALIASES = {"markdown": "md", "htm": "html", "word": "docx", "latex": "tex"}
_INLINE = re.compile(r"\*\*(?P<b>.+?)\*\*|(?<!\*)\*(?!\s)(?P<i>.+?)(?<!\s)\*(?!\*)|`(?P<c>.+?)`|\[(?P<lt>.+?)\]\((?P<lu>https?://[^)]+)\)")


def _inline_parts(s: str):
    """Splits the Markdown inline subset into (text, kind, url) parts: kind is '', 'b', 'i', 'code' or 'link'."""
    pos = 0
    for m in _INLINE.finditer(s):
        if m.start() > pos:
            yield s[pos:m.start()], "", None
        if m.group("b") is not None:
            yield m.group("b"), "b", None
        elif m.group("i") is not None:
            yield m.group("i"), "i", None
        elif m.group("c") is not None:
            yield m.group("c"), "code", None
        else:
            yield m.group("lt"), "link", m.group("lu")
        pos = m.end()
    if pos < len(s):
        yield s[pos:], "", None


def _flat(blocks):
    """Blocks with the keep-together groups opened up, for formats that flow freely."""
    for b in blocks:
        if b[0] == "keep":
            yield from _flat(b[1])
        else:
            yield b


def _write_docx(cover, blocks, out_path: Path, title: str, author: str) -> Path:
    """Part 1 as a Word document, with the same headings, figures, captions, tables and links as the PDF."""
    try:
        import docx
        from docx.enum.text import WD_BREAK
        from docx.opc.constants import RELATIONSHIP_TYPE
        from docx.oxml import OxmlElement
        from docx.oxml.ns import qn
        from docx.shared import Inches, Pt, RGBColor
    except ImportError:
        raise SystemExit("report --format docx needs python-docx: pip install python-docx (or conda install -c conda-forge python-docx)")
    d = docx.Document()
    d.core_properties.title = title
    d.core_properties.author = author or "titus-scraper"
    grey = RGBColor(0x55, 0x55, 0x55)

    def link(par, url, text):
        rid = par.part.relate_to(url, RELATIONSHIP_TYPE.HYPERLINK, is_external=True)
        h = OxmlElement("w:hyperlink")
        h.set(qn("r:id"), rid)
        r = OxmlElement("w:r")
        rpr = OxmlElement("w:rPr")
        col = OxmlElement("w:color")
        col.set(qn("w:val"), "2A78D6")
        und = OxmlElement("w:u")
        und.set(qn("w:val"), "single")
        rpr.append(col)
        rpr.append(und)
        r.append(rpr)
        tx = OxmlElement("w:t")
        tx.text = text
        tx.set(qn("xml:space"), "preserve")
        r.append(tx)
        h.append(r)
        par._p.append(h)

    def fill(par, text, size=None, italic=False):
        for part, kind, url in _inline_parts(text):
            if kind == "link":
                link(par, url, part)
                continue
            run = par.add_run(part)
            run.bold = kind == "b" or None
            run.italic = (kind == "i" or italic) or None
            if kind == "code":
                run.font.name = "Courier New"
            if size:
                run.font.size = Pt(size)
                run.font.color.rgb = grey
        return par

    def put(b):
        kind = b[0]
        if kind == "cover_title":
            d.add_heading(b[1], level=0)
        elif kind in ("h1", "h2", "h3"):
            d.add_heading(b[1], level=int(kind[1]))
        elif kind == "p":
            fill(d.add_paragraph(), b[1])
        elif kind == "small":
            fill(d.add_paragraph(), b[1], size=9)
        elif kind == "bullets":
            for x in b[1]:
                fill(d.add_paragraph(style="List Bullet"), x, size=9 if b[2] == "small" else None)
        elif kind == "figure":
            d.add_picture(str(b[1]), width=Inches(6.0))
            if b[2]:
                fill(d.add_paragraph(), b[2], size=9, italic=True)
        elif kind == "table":
            rows = b[1]
            tb = d.add_table(rows=len(rows), cols=len(rows[0]))
            tb.style = "Table Grid"
            for i, row in enumerate(rows):
                for j, cell in enumerate(row):
                    c = tb.cell(i, j)
                    c.text = ""
                    fill(c.paragraphs[0], str(cell))
                    if i == 0:
                        for run in c.paragraphs[0].runs:
                            run.bold = True
        elif kind == "spacer":
            d.add_paragraph()

    for b in cover:
        put(b)
    d.add_paragraph().add_run().add_break(WD_BREAK.PAGE)
    for b in _flat(blocks):
        put(b)
    d.save(str(out_path))
    return out_path


def _copy_figure(src, out_path: Path) -> str:
    """Copies a figure into <stem>_files/ next to out_path and returns its path relative to out_path."""
    import shutil
    figdir = out_path.with_name(out_path.stem + "_files")
    figdir.mkdir(parents=True, exist_ok=True)
    dest = figdir / Path(src).name
    if Path(src).resolve() != dest.resolve():
        shutil.copyfile(src, dest)
    return f"{figdir.name}/{dest.name}"


def _write_md(cover, blocks, out_path: Path) -> Path:
    """Part 1 as Markdown. Figures are copied into a folder next to the file and linked by relative path."""
    lines = []

    def put(b):
        kind = b[0]
        if kind == "cover_title":
            lines.extend([f"# {b[1]}", ""])
        elif kind in ("h1", "h2", "h3"):
            lines.extend(["#" * int(kind[1]) + " " + b[1], ""])
        elif kind == "p":
            lines.extend([b[1], ""])
        elif kind == "small":
            lines.extend([f"*{b[1]}*" if "*" not in b[1] else b[1], ""])
        elif kind == "bullets":
            lines.extend([f"- {x}" for x in b[1]] + [""])
        elif kind == "figure":
            rel = _copy_figure(b[1], out_path)
            alt = re.sub(r"[\[\]]", "", b[2] or Path(b[1]).stem)
            lines.extend([f"![{alt}]({rel})", ""] + ([f"*{b[2]}*", ""] if b[2] else []))
        elif kind == "table":
            esc = lambda c: str(c).replace("|", "\\|")
            rows = b[1]
            lines.extend(["| " + " | ".join(esc(c) for c in rows[0]) + " |", "|" + "---|" * len(rows[0])]
                         + ["| " + " | ".join(esc(c) for c in r) + " |" for r in rows[1:]] + [""])

    for b in cover:
        if b[0] != "spacer":
            put(b)
    lines.extend(["---", ""])
    for b in _flat(blocks):
        put(b)
    out_path.write_text("\n".join(lines).rstrip() + "\n", encoding="utf-8")
    return out_path


def _write_html(cover, blocks, out_path: Path, title: str, author: str) -> Path:
    """Part 1 as one self-contained HTML file: the figures are embedded, so the file can be shared on its own."""
    import base64

    def inl(s):
        out = []
        for part, kind, url in _inline_parts(s):
            e = html.escape(part)
            out.append({"b": f"<strong>{e}</strong>", "i": f"<em>{e}</em>", "code": f"<code>{e}</code>",
                        "link": f"<a href=\"{html.escape(url or '', quote=True)}\">{e}</a>"}.get(kind, e))
        return "".join(out)

    body = []

    def put(b):
        kind = b[0]
        if kind == "cover_title":
            body.append(f"<h1 class=\"title\">{inl(b[1])}</h1>")
        elif kind in ("h1", "h2", "h3"):
            body.append(f"<h{int(kind[1]) + 1}>{inl(b[1])}</h{int(kind[1]) + 1}>")
        elif kind == "p":
            body.append(f"<p>{inl(b[1])}</p>")
        elif kind == "small":
            body.append(f"<p class=\"small\">{inl(b[1])}</p>")
        elif kind == "bullets":
            cls = " class=\"small\"" if b[2] == "small" else ""
            body.append(f"<ul{cls}>" + "".join(f"<li>{inl(x)}</li>" for x in b[1]) + "</ul>")
        elif kind == "figure":
            data = base64.b64encode(Path(b[1]).read_bytes()).decode("ascii")
            cap = f"<figcaption>{inl(b[2])}</figcaption>" if b[2] else ""
            body.append(f"<figure><img src=\"data:image/png;base64,{data}\" alt=\"{html.escape(b[2] or Path(b[1]).stem, quote=True)}\">{cap}</figure>")
        elif kind == "table":
            rows = b[1]
            body.append("<table><thead><tr>" + "".join(f"<th>{inl(str(c))}</th>" for c in rows[0]) + "</tr></thead><tbody>"
                        + "".join("<tr>" + "".join(f"<td>{inl(str(c))}</td>" for c in r) + "</tr>" for r in rows[1:])
                        + "</tbody></table>")

    body.append("<header>")
    for b in cover:
        if b[0] != "spacer":
            put(b)
    body.append("</header><main>")
    for b in _flat(blocks):
        put(b)
    body.append("</main>")
    css = ("body{font-family:Helvetica,Arial,sans-serif;max-width:46rem;margin:2rem auto;padding:0 1rem;line-height:1.55;color:#1f2328}"
           "h1.title{font-size:2rem;line-height:1.2}header{border-bottom:1px solid #d0d7de;margin-bottom:2rem;padding-bottom:1rem}"
           "figure{margin:1.5rem 0}figure img{max-width:100%;height:auto}figcaption,.small{font-size:.85rem;color:#57606a}"
           "table{border-collapse:collapse;margin:1rem 0}th,td{border-bottom:1px solid #d0d7de;padding:.3rem .8rem;text-align:left}"
           "a{color:#2a78d6}code{font-size:.9em}")
    doc = (f"<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n"
           f"<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>{html.escape(title)}</title>\n"
           f"<meta name=\"author\" content=\"{html.escape(author or 'titus-scraper', quote=True)}\">\n<style>{css}</style>\n</head>\n"
           "<body>\n" + "\n".join(body) + "\n</body>\n</html>\n")
    out_path.write_text(doc, encoding="utf-8")
    return out_path


_TEX_SPECIAL = {"\\": r"\textbackslash{}", "&": r"\&", "%": r"\%", "$": r"\$", "#": r"\#", "_": r"\_",
                "{": r"\{", "}": r"\}", "~": r"\textasciitilde{}", "^": r"\textasciicircum{}"}


def _tex_escape(s: str) -> str:
    # "--" would print as a dash in LaTeX, so "--full" keeps its two hyphens
    return "".join(_TEX_SPECIAL.get(c, c) for c in str(s)).replace("--", "-{}-")


def _write_tex(cover, blocks, out_path: Path, title: str, author: str) -> Path:
    """Part 1 as a LaTeX document. Figures are copied into a folder next to the file. It compiles with pdflatex,
    and with xelatex or lualatex, which also handle text in non-Latin scripts."""

    def inl(s):
        out = []
        for part, kind, url in _inline_parts(s):
            e = _tex_escape(part)
            if kind == "link":
                u = (url or "").replace("\\", "/").replace("%", r"\%").replace("#", r"\#").replace("{", "").replace("}", "")
                out.append(f"\\href{{{u}}}{{{e}}}")
            else:
                out.append({"b": f"\\textbf{{{e}}}", "i": f"\\emph{{{e}}}", "code": f"\\texttt{{{e}}}"}.get(kind, e))
        return "".join(out)

    body = []

    def put(b):
        kind = b[0]
        if kind == "cover_title":
            body.append(f"{{\\LARGE\\bfseries {inl(b[1])}\\par}}\n\\vspace{{1em}}\n")
        elif kind in ("h1", "h2", "h3"):
            cmd = {"h1": "section", "h2": "subsection", "h3": "subsubsection"}[kind]
            body.append(f"\\{cmd}*{{{inl(b[1])}}}\n")
        elif kind == "p":
            body.append(inl(b[1]) + "\n")
        elif kind == "small":
            body.append(f"{{\\small {inl(b[1])}\\par}}\n")
        elif kind == "bullets":
            items = "\n".join(f"  \\item {inl(x)}" for x in b[1])
            env = f"\\begin{{itemize}}\n{items}\n\\end{{itemize}}"
            body.append((f"{{\\small\n{env}\n}}" if b[2] == "small" else env) + "\n")
        elif kind == "figure":
            rel = _copy_figure(b[1], out_path)
            cap = f"\\\\[0.4em]\n{{\\small\\itshape {inl(b[2])}\\par}}" if b[2] else ""
            body.append("\\begin{center}\n"
                        f"\\includegraphics[width=\\linewidth,height=0.42\\textheight,keepaspectratio]{{{rel}}}{cap}\n"
                        "\\end{center}\n")
        elif kind == "table":
            rows = b[1]
            spec = "l" + "r" * (len(rows[0]) - 1)
            lines = [" & ".join(f"\\textbf{{{inl(str(c))}}}" for c in rows[0]) + r" \\ \hline"]
            lines += [" & ".join(inl(str(c)) for c in r) + r" \\" for r in rows[1:]]
            body.append(f"\\begin{{tabular}}{{{spec}}}\n\\hline\n" + "\n".join(lines) + "\n\\hline\n\\end{tabular}\n")
        elif kind == "spacer":
            body.append(f"\\vspace{{{b[1]}in}}\n")

    for b in cover:
        put(b)
    body.append("\\newpage\n")
    for b in _flat(blocks):
        put(b)
    head = "\n".join([
        "% Written by titus-scraper. Compile with pdflatex, or with xelatex or lualatex for non-Latin scripts.",
        "% The figures are in the folder next to this file. Keep the two together.",
        r"\documentclass[11pt]{article}",
        r"\usepackage{iftex}",
        r"\ifPDFTeX",
        r"  \usepackage[utf8]{inputenc}",
        r"  \usepackage[T1]{fontenc}",
        r"  \usepackage{lmodern}",
        r"  \usepackage{textcomp}",
        r"\else",
        r"  \usepackage{fontspec}",
        r"\fi",
        r"\usepackage[margin=1in]{geometry}",
        r"\usepackage{graphicx}",
        r"\usepackage{xcolor}",
        r"\definecolor{tslink}{RGB}{42,120,214}",
        r"\usepackage[colorlinks=true,urlcolor=tslink,linkcolor=black]{hyperref}",
        r"\setlength{\parindent}{0pt}",
        r"\setlength{\parskip}{0.6em}",
        f"\\hypersetup{{pdftitle={{{_tex_escape(title)}}},pdfauthor={{{_tex_escape(author or 'titus-scraper')}}}}}",
        r"\begin{document}",
        ""])
    out_path.write_text(head + "\n".join(body) + "\n\\end{document}\n", encoding="utf-8")
    return out_path

# --------------------------------------------------------------------------- commands


def iso(d: str) -> str:
    return datetime.fromisoformat(d).replace(tzinfo=timezone.utc).isoformat().replace("+00:00", "Z")


SOURCE_REGISTRY = {
    "bluesky": {"docs": "https://docs.bsky.app/", "terms": "https://bsky.social/about/support/tos",
                "notes": "searchPosts ranking and indexing affect coverage. Needs an app password."},
    "mastodon": {"docs": "https://docs.joinmastodon.org/client/public/", "terms": "each server's /about page",
                 "notes": "No single database. Each server sees what its users follow. Some servers require login for hashtag timelines."},
    "youtube": {"docs": "https://developers.google.com/youtube/v3", "terms": "https://developers.google.com/youtube/terms/developer-policies",
                "notes": "Restricted. Quota-limited search. Items are deleted 30 days after collection. " + RESTRICTED["youtube"]},
    "reddit": {"docs": "https://www.reddit.com/dev/api/", "terms": "https://redditinc.com/policies/data-api-terms",
               "notes": "Restricted. " + RESTRICTED["reddit"]},
    "threads": {"docs": "https://developers.facebook.com/docs/threads", "terms": "https://developers.facebook.com/terms",
                "notes": "keyword_search on other people's posts needs Meta's approval."},
    "instagram": {"docs": "https://developers.facebook.com/docs/instagram-platform", "terms": "https://developers.facebook.com/terms",
                  "notes": "Hashtag search covers 24 hours and needs Public Content Access."},
    "gdelt": {"docs": "https://blog.gdeltproject.org/gdelt-doc-2-0-api-debuts/", "terms": "https://www.gdeltproject.org/about.html#termsofuse",
              "notes": "About the last 3 months. Headlines and URLs only. Coverage varies by country and outlet."},
    "guardian": {"docs": "https://open-platform.theguardian.com/documentation/", "terms": "https://www.theguardian.com/open-platform/terms-and-conditions",
                 "notes": "Restricted. " + RESTRICTED["guardian"]},
    "nytimes": {"docs": "https://developer.nytimes.com/apis", "terms": "https://developer.nytimes.com/terms",
                "notes": "Metadata only (headline, abstract, lead paragraph). Its pages and feeds are blocked (SITE_RULES)."},
    "news": {"docs": "each outlet's robots.txt, sitemaps and feeds", "terms": "each outlet's terms",
             "notes": "Needs --country or --site, and a site:<domain> row approved for each outlet. robots.txt is not permission."},
    "blogs": {"docs": "Medium and WordPress.com tag feeds", "terms": "https://policy.medium.com/medium-terms-of-service-9db0094a1e0f and https://wordpress.com/tos/",
              "notes": "Medium and WordPress.com tag feeds. Medium is headlines only: titles and short summaries."},
    "feeds": {"docs": "each site's feed", "terms": "each site's terms",
              "notes": "Recent items only. Each feed's site needs a site:<domain> row approved."},
    "sitemaps": {"docs": "https://www.sitemaps.org/protocol.html", "terms": "each site's terms and robots.txt",
                 "notes": "Discovery of URLs and headlines. robots.txt is checked for every sitemap. robots.txt is not permission."},
}
REGISTRY_COLUMNS = ["source", "decision", "approval_ref", "reviewer", "date_checked", "terms_url", "robots_url", "api_docs_url",
                    "allowed_fields", "rate_limits", "retention_rule", "publication_rule", "notes"]
APPROVE_WORDS = {"approve", "approved", "yes", "allow", "allowed"}


def load_registry(data) -> dict | None:
    """sources.csv as {source: row}, or None when the run folder has none."""
    path = Path(data) / "sources.csv"
    if not path.exists():
        return None
    rows = pd.read_csv(path, dtype=str, keep_default_na=False).to_dict("records")
    return {str(r.get("source", "")).strip().lower(): r for r in rows if str(r.get("source", "")).strip()}


def approval(reg: dict | None, key: str) -> tuple[bool, str]:
    """Whether sources.csv approves this source ('gdelt', 'site:ghanaweb.com', 'fulltext:citinewsroom.com'), and
    why not. An approval needs decision=approve, date_checked and reviewer. Restricted sources also need
    approval_ref. A site that SITE_RULES blocks can't be approved, and a headlines-only site can't be
    approved for full text."""
    key = key.strip().lower()
    kind, _, dom = key.partition(":")
    if dom:
        rule = site_rule(dom)
        if rule and rule[1] == "block":
            return False, f"{rule[0]} is blocked: {rule[2]}"
        if rule and rule[1] == "headlines" and kind in ("fulltext", "video"):
            return False, f"{rule[0]} is headlines only: {rule[2]}"
    if reg is None:
        return False, "the run folder has no sources.csv. Run init first, then approve each source you will use"
    row = reg.get(key)
    if row is None and dom:          # feeds.npr.org is covered by a row for npr.org
        labels = dom.split(".")
        row = next((reg[f"{kind}:{'.'.join(labels[i:])}"] for i in range(1, len(labels) - 1)
                    if f"{kind}:{'.'.join(labels[i:])}" in reg), None)
    if row is None:
        return False, f"sources.csv has no row for {key}. Run init with it, read its terms, then approve it"
    decision = str(row.get("decision", "")).strip().lower()
    if decision not in APPROVE_WORDS:
        return False, f"sources.csv does not approve {key} (decision: {decision or 'blank'})"
    missing = [c for c in ("date_checked", "reviewer") if not str(row.get(c, "")).strip()]
    if missing:
        return False, f"the approval of {key} needs {' and '.join(missing)} filled in"
    if key in RESTRICTED and not str(row.get("approval_ref", "")).strip():
        return False, f"{key} is restricted and needs approval_ref. {RESTRICTED[key]}"
    return True, ""


def _registry_row(source: str) -> dict:
    kind, _, dom = source.partition(":")
    info = SOURCE_REGISTRY.get(source, {"docs": "", "terms": "", "notes": ""})
    row = {c: "" for c in REGISTRY_COLUMNS}
    row.update(source=source, terms_url=info["terms"], api_docs_url=info["docs"], notes=info["notes"])
    if dom:
        rule = site_rule(dom)
        row.update(robots_url=f"https://{dom}/robots.txt", terms_url=f"https://{dom}/ (find the terms page)")
        if kind == "site":
            row["notes"] = f"{outlet_name(dom)} ({outlet_country(dom) or 'country not listed'}). Headlines, summaries and links from its sitemaps and feeds."
        elif kind == "video":
            row["notes"] = ("Video files for transcribe. Approve only when the host's terms allow downloading and transcribing "
                            "the audio, for every part of a stream.")
        else:
            row["notes"] = "Article text through fetch-text. Approve only when the site's terms allow automated reading and text mining."
        if rule and (rule[1] == "block" or (rule[1] == "headlines" and kind in ("fulltext", "video"))):
            row.update(decision="blocked", date_checked=rule[3], notes=f"{rule[2]} (SITE_RULES, {rule[3]}). It can't be approved.")
        elif rule and rule[1] == "headlines":
            row["notes"] += f" Headlines only: {rule[2]}."
        entry = terms_entry(dom)
        if entry and entry.get("verdict") not in ("", "unreviewed"):
            row["terms_url"] = entry["terms_url"]
            if row.get("decision") != "blocked":
                row["notes"] += f" Terms register ({entry['date_read']}): {entry['verdict']}. {entry['clause']}."
        elif row.get("decision") != "blocked":
            row["notes"] += " Its terms are not in references/terms_register.csv yet. Read them before approving."
        if entry and entry.get("ai_use") == "forbidden":
            row["notes"] += " Its terms forbid AI use, so its items stay out of the reading packet."
    if source in RESTRICTED:
        row["notes"] = row["notes"] or RESTRICTED[source]
    return row


def cmd_init(a):
    """Writes protocol.md and sources.csv for a new study. A rerun keeps every decision already made in
    sources.csv and adds rows for new sources. --approve writes the ready-made approvals (PRESET_APPROVALS).
    Every other source is approved by editing its row after reading its terms."""
    data = Path(a.data)
    data.mkdir(parents=True, exist_ok=True)
    q = Query(a.type, a.value, a.alias or [], a.exclude or [], a.counter or [])
    plats = [p.strip() for p in a.platforms.split(",") if p.strip()]
    proto, reg = data / "protocol.md", data / "sources.csv"
    today = f"{datetime.now(timezone.utc):%Y-%m-%d}"
    study = {} if a.force else load_study(data)
    changes = []
    if a.ethics:
        if a.ethics != "pending" and not (a.ethics_ref or "").strip():
            raise SystemExit("--ethics needs --ethics-ref: the board, the protocol number and the date, or who decided that "
                             "the study is exempt or not human-subjects research, and when.")
        study["ethics"] = {"status": a.ethics, "ref": (a.ethics_ref or "").strip(), "recorded": today}
        changes.append(f"ethics review recorded: {a.ethics}" + (f" ({a.ethics_ref.strip()})" if (a.ethics_ref or "").strip() else ""))
    if a.retain_days is not None:
        if a.retain_days < 1:
            raise SystemExit("--retain-days takes a number of days, 1 or more.")
        if study.get("retain_days") != a.retain_days:
            changes.append(f"retention set to {a.retain_days} days after collection")
        study["retain_days"] = a.retain_days
    study.setdefault("retain_days", DEFAULT_RETAIN_DAYS)
    if a.compute:
        study["compute"] = a.compute.strip()
        changes.append(f"compute and storage: {a.compute.strip()}")
    study.setdefault("compute", "not recorded")
    study.setdefault("ethics", {"status": "not recorded", "ref": "", "recorded": ""})
    study.setdefault("created", today)
    (data / STUDY_FILE).write_text(json.dumps(study, indent=2))
    eth = study["ethics"]
    if proto.exists() and not a.force:
        print(f"{proto} exists. Pass --force to replace it.")
        if changes:
            with proto.open("a", encoding="utf-8") as fh:
                fh.write("".join(f"- {today}: {c}\n" for c in changes))
            print(f"added to its Changes: {'; '.join(changes)}")
    else:
        variants = "\n".join(f"| {v['variant']} | {v['match_type']} | {v['role']} |" for v in q.variant_table())
        proto.write_text(PROTOCOL_TEMPLATE.format(
            value=q.label() if a.type == "hashtag" else a.value, type=a.type, date=f"{datetime.now(timezone.utc):%Y-%m-%d}", since=a.since or "", until=a.until or "",
            platforms=", ".join(plats) + (f" (news countries: {', '.join(a.country)})" if getattr(a, "country", None) else ""), variants=variants or "| (an account) | account | main |",
            ethics=eth["status"], ethics_ref=eth.get("ref") or "none", retain=study["retain_days"], compute=study["compute"]), encoding="utf-8")
        print(f"wrote {proto}")
    approve = [x.strip().lower() for x in (a.approve or "").split(",") if x.strip()]
    unknown = [x for x in approve if x not in PRESET_APPROVALS]
    if unknown:
        raise SystemExit(f"--approve takes only the ready-made approvals: {', '.join(PRESET_APPROVALS)}. Approve "
                         f"{', '.join(unknown)} by editing its row in sources.csv after reading its terms.")
    if approve and not (a.reviewer or "").strip():
        raise SystemExit("--approve needs --reviewer NAME: the person who read the terms and takes responsibility for the approval.")
    sites = list(a.site or [])
    if "news" in plats or getattr(a, "country", None):
        sites += [d for d, _, _ in news_candidates(getattr(a, "country", None), None)]
    wanted = plats + [f"site:{x.strip().lower().removeprefix('www.')}" for x in sites if x.strip()]
    wanted += [f"fulltext:{x.strip().lower().removeprefix('www.')}" for x in (a.fulltext or []) if x.strip()]
    wanted += [f"video:{x.strip().lower().removeprefix('www.')}" for x in (getattr(a, "video", None) or []) if x.strip()]
    old = {} if a.force else (load_registry(data) or {})
    rows = {k: {c: str(r.get(c, "")) for c in REGISTRY_COLUMNS} for k, r in old.items()}
    added = 0
    for src in dict.fromkeys(wanted):
        if src.lower() not in rows:
            rows[src.lower()] = _registry_row(src)
            added += 1
    for name in approve:
        row = rows.setdefault(name, _registry_row(name))
        row.update(decision="approve", reviewer=a.reviewer.strip(), date_checked=today,
                   notes=(PRESET_APPROVALS[name] + " " + row.get("notes", "")).strip())
    pd.DataFrame(list(rows.values()), columns=REGISTRY_COLUMNS).to_csv(reg, index=False)
    print(f"{'wrote' if not old else 'updated'} {reg}: {len(rows)} sources, {added} new"
          + (f", approved {', '.join(approve)}" if approve else "") + ".")
    if eth.get("status") not in ETHICS_OK:
        print(f"Ethics review: {eth.get('status')}. collect, fetch-text and transcribe wait until it is recorded with --ethics "
              "approved, exempt or not-human-subjects and --ethics-ref.")
    print(f"Retention: items are deleted {study['retain_days']} days after collection (--retain-days to change).")
    waiting = [k for k, r in rows.items() if r.get("decision", "").strip().lower() not in APPROVE_WORDS | {"blocked"}]
    if waiting:
        print("Not approved yet: " + ", ".join(waiting[:12]) + (" and more" if len(waiting) > 12 else "") + ". Read each source's terms, "
              "then set decision=approve, date_checked and reviewer in sources.csv. collect skips every source that isn't approved.")


PROTOCOL_TEMPLATE = """# Study protocol: {value}

Version 1, {date}. Commit this file before collecting. When a rule changes, add a dated note under
"Changes" instead of editing the old rule.

## Question and audience
- Research question:
- Who will read the result:
- The claim is about: the collected corpus only (default), or a wider population (say how that is justified)

## Scope
- Query type: {type}
- Window: {since} to {until} (UTC)
- Languages: English (the analyze step keeps English only unless --all-languages)
- Places in scope:
- Unit of analysis: post, comment, article or headline
- Replies and comments: included / excluded
- Reposts: set aside from text analysis, counted in the descriptives
- Linked articles: headline only, or full text through fetch-text for domains approved in sources.csv (fulltext:<domain>)

## Sources
- Included: {platforms}
- Excluded, and why: X, LinkedIn, Facebook and TikTok (no free official route to public posts)
- The source registry (sources.csv) records terms, robots.txt, limits and the decision for each source.
  collect reads only the sources and sites approved there, and refuses sites that SITE_RULES blocks.

## Query dictionary
Review this table before collecting. Exact hashtags, textual phrases and counter-tags are matched and
reported separately (match_type).

| Variant | Match type | Role |
|---|---|---|
{variants}

- Misspellings reviewed by hand:
- Words that mark a false match (exclusions):

## Definitions
- Relevant: the item is about the topic, not only a passing use of a word in the query
- Stance: favor / against / none (neutral, reporting, unclear or unrelated). See references/validation.md for the codebook.
- Sentiment: the tone of the text, which is not the same as stance

## Cleaning rules
- Exact duplicates (after normalising links, handles and case) and near-duplicates (MinHash, Jaccard 0.85) are merged and counted as copies
- Suspect accounts (top 1% by volume with 20 or more posts, link-only posts, hashtag stuffing) are kept and reported apart

## Validation plan
- Pilot relevance check: 200 or more items, two coders, before the full run
- Sentiment and stance: 200 or more items, two coders, kappa and alpha, then score against the model

## Ethics review
- Status: {ethics}
- Reference: {ethics_ref}
- collect, fetch-text and transcribe run only when the status is approved, exempt or not-human-subjects, with a reference
- Lawful basis, where EU or UK data protection law applies (Article 6, and an Article 9 condition for political opinions or other special categories):
- Where the commands run and the data is stored: {compute}

## Retention, deletion and quoting
- Raw data stays in the run folder and is not published. Raw API responses are kept only with --keep-raw
- Every item, with its cached page, transcript and saved responses, is deleted {retain} days after collection. Every command enforces this (study.json)
- YouTube items are deleted automatically 30 days after collection
- Only the public/ folder written by export is shared. Everything else in the run folder stays private
- Ordinary users are not named or quoted word for word. Public figures, organisations and outlets may be.
- Deletion requests: purge --author HANDLE, then rerun analyze and report

## Known gaps and planned robustness checks
- Platform search ranking is not random
- Robustness: without reposts, accounts capped at 5 posts, without suspect accounts, per platform, exact-hashtag matches only

## Changes
- {date}: protocol created
"""


def cmd_check(a):
    print("Source      Ready  Needs")
    for name, cls in COLLECTORS.items():
        missing = [k for k in cls.needs if not os.environ.get(k)]
        print(f"{name:11s} {'yes' if not missing else 'no ':5s}  {', '.join(missing) or '-'}")
    for name, why in CLOSED.items():
        print(f"{name:11s} no     {why}")
    print("feeds needs --feed URL or --outlet NAME. sitemaps needs --site DOMAIN or --sitemap URL.")
    print(f"news knows {len(WORLD_NEWS)} English-language outlets in {len({r[2] for r in WORLD_NEWS})} countries and regions. "
          "It reads only the countries (--country) or sites (--site) you name.")
    print("Every source also needs an approved row in the run folder's sources.csv (see init). Restricted sources "
          f"({', '.join(RESTRICTED)}) need approval_ref too.")
    print(f"Blocked sites: {', '.join(k for k, v in SITE_RULES.items() if v[0] == 'block')}. "
          f"Headlines only: {', '.join(k for k, v in SITE_RULES.items() if v[0] == 'headlines')}.")
    for name, cls in COLLECTORS.items():
        missing = [k for k in cls.needs if not os.environ.get(k)]
        if missing and name in ACCESS_HELP:
            print(f"  to enable {name}: {ACCESS_HELP[name]['get']} {ACCESS_HELP[name]['url']}")
    print(SET_KEYS_HOWTO)
    print(f"{CONTACT_ENV}: {'set' if os.environ.get(CONTACT_ENV) else 'not set (fetch-text needs it)'}")


def query_of(a) -> Query:
    return Query(a.type, a.value, a.alias or [], a.exclude or [], getattr(a, "counter", None) or [])


DEFAULT_PER_SEARCH = 5000   # the default cap: posts per search string on each source, unless --max-posts or --limit is given


def share_of(remaining: int, sources_left: int) -> int:
    """An equal share of the posts still allowed for the sources still to run. A source that returns fewer
    leaves the rest of its share to the sources after it."""
    return max(0, -(-remaining // sources_left)) if sources_left > 0 else 0


def thin_evenly(posts: list, k: int) -> list:
    """At most k posts, spread evenly across the time window instead of the newest k. Duplicates (same source and
    post id) count once."""
    seen = {}
    for p in posts:
        seen[(p.platform, p.post_id)] = p
    posts = sorted(seen.values(), key=lambda p: str(p.created_at or ""))
    n = len(posts)
    if k <= 0:
        return []
    if n <= k:
        return posts
    if k == 1:
        return [posts[-1]]
    picks = sorted({round(i * (n - 1) / (k - 1)) for i in range(k)})
    return [posts[i] for i in picks]


class LimitReached(Exception):
    """The --max-posts budget ran out before a source's turn."""


class Skip(Exception):
    """A source collect must not run: not approved, closed or unknown."""

    def __init__(self, status: str, why: str):
        super().__init__(why)
        self.status, self.why = status, why


def _hosts_approved(reg, hosts) -> tuple[list[str], dict]:
    """The hosts whose site:<domain> row is approved, and {host: why} for the others."""
    ok, refused = [], {}
    for h in dict.fromkeys(hosts):
        good, why = approval(reg, f"site:{h}")
        if good:
            ok.append(h)
        else:
            refused[h] = why
    return ok, refused


def plan_source(name: str, a, reg) -> dict:
    """What collect may do with one source: whether it is approved, why not, the hosts it would contact
    once approved, and the sites or feeds left after the approvals. collect --dry-run prints this and stops."""
    p = {"name": name, "ok": False, "why": "", "status": "not approved", "hosts": [], "refused": {}, "sites": [], "feeds": [], "sitemaps": []}
    if name in CLOSED:
        p.update(status="not available", why=CLOSED[name])
        return p
    if name not in COLLECTORS:
        p.update(status="not available", why=f"unknown source '{name}'. Known: {', '.join(COLLECTORS)}")
        return p
    try:
        if name == "news":
            if not (a.country or a.site):
                raise NotImplementedError("news: name the countries (--country) or the sites (--site) to read. "
                                          "The skill no longer reads every outlet by default")
            cands = news_candidates(a.country, a.site)
            good, p["refused"] = _hosts_approved(reg, [d for d, _, _ in cands])
            p["sites"] = [r for r in cands if r[0] in good]
            p["hosts"] = good
        elif name == "sitemaps":
            urls = [u.strip() for u in (a.sitemap or []) if u.strip()]
            sites = [x.strip().lower().removeprefix("www.") for x in (a.site or []) if x.strip()]
            good, p["refused"] = _hosts_approved(reg, sites + [domain_of(u) for u in urls])
            p["sites"] = [s for s in sites if s in good]
            p["sitemaps"] = [u for u in urls if domain_of(u) in good]
            p["hosts"] = good
        elif name == "feeds":
            feeds = Feeds.resolve(a.feed, a.outlet)
            good, p["refused"] = _hosts_approved(reg, [domain_of(u) for _, u in feeds])
            p["feeds"] = [(lab, u) for lab, u in feeds if domain_of(u) in good]
            p["hosts"] = good
        elif name == "mastodon":
            p["hosts"] = Mastodon(a.mastodon_server).servers
        else:
            p["hosts"] = list(API_HOSTS.get(name, []))
    except NotImplementedError as e:
        p.update(status="not available", why=str(e))
        return p
    ok, why = approval(reg, name)
    if not ok:
        p["why"] = why
        return p
    if name in ("news", "sitemaps", "feeds") and not p["hosts"]:
        p["why"] = (f"no site for {name} is approved in sources.csv. Approve each site:<domain> row after reading the "
                    "site's terms" + (f" ({'; '.join(f'{h}: {w}' for h, w in list(p['refused'].items())[:3])})" if p["refused"] else ""))
        return p
    p.update(ok=True, status="approved")
    return p


def cmd_collect(a):
    q, data = query_of(a), Path(a.data)
    data.mkdir(parents=True, exist_ok=True)
    reg = load_registry(data)
    if reg is None and not a.dry_run:
        raise SystemExit(f"No sources.csv in {data}. Run init first, read each source's terms, and approve the sources "
                         "you will use. collect reads only approved sources.")
    if not (data / "protocol.md").exists():
        log.warning("No protocol.md in %s. Run init first so the study's rules are written down before collecting.", data)
    since, until = iso(a.since), iso(a.until)
    started_run = datetime.now(timezone.utc).isoformat()
    names = [p.strip() for p in (a.platforms or DEFAULT_PLATFORMS).split(",") if p.strip()]
    if a.platforms is None and (a.feed or a.outlet):
        names.append("feeds")
    if a.platforms is None and a.sitemap:
        names.append("sitemaps")
    if a.type == "user" and not (a.public_figure or "").strip():
        raise SystemExit("--type user reads one account. Collect it only when it belongs to a public figure, an organisation or "
                         "an outlet, and say why with --public-figure, for example --public-figure \"member of parliament\" or "
                         "--public-figure \"official account of the Ghana Police Service\". Never study a private person's account.")
    plans = {n: plan_source(n, a, reg) for n in names}
    if a.dry_run:
        print("Dry run: nothing was requested.\n")
        for n, p in plans.items():
            missing = [k for k in COLLECTORS[n].needs if not os.environ.get(k)] if n in COLLECTORS else []
            state = p["status"] if not (p["ok"] and missing) else "no key"
            print(f"{n:10s} {state:14s} {', '.join(p['hosts']) or '-'}")
            if p["why"]:
                print(f"{'':10s} why: {p['why']}")
            if missing and p["ok"]:
                print(f"{'':10s} needs {', '.join(missing)}")
            for h, why in list(p["refused"].items())[:20]:
                print(f"{'':10s} skips {h}: {why}")
        return
    if not os.environ.get(CONTACT_ENV, "").strip():
        raise SystemExit(f"Set {CONTACT_ENV} to your email or website first, so every request says who is asking "
                         f"(for example: export {CONTACT_ENV}=you@example.org).")
    require_ethics(data, "collect")
    HTTP.keep_raw = bool(a.keep_raw)
    HTTP.site_budget = a.max_requests_per_site
    expire_youtube(data)
    # --max-posts: one budget for all sources, shared evenly among the ones that can run
    budget = a.max_posts if getattr(a, "max_posts", None) and a.max_posts > 0 else None
    runnable = [n for n in names if plans[n]["ok"] and not [k for k in COLLECTORS[n].needs if not os.environ.get(k)]]
    left, kept_total = len(runnable), 0
    for name in names:
        started, path, c, plan = datetime.now(timezone.utc).isoformat(), None, None, plans[name]
        HTTP.bind(data, name)
        before = HTTP.n
        share = share_of(budget - kept_total, left) if budget is not None and name in runnable else None
        # --max-posts replaces the default cap. An explicit --limit still applies on top of it.
        if share is not None:
            per = min(a.limit, share) if a.limit else share
        else:
            per = a.limit or DEFAULT_PER_SEARCH
        collected = None
        try:
            if not plan["ok"]:
                raise Skip(plan["status"], plan["why"])
            if share == 0:
                raise LimitReached(f"--max-posts {budget} was reached before this source ran")
            missing = [k for k in COLLECTORS[name].needs if not os.environ.get(k)]
            if missing:
                raise KeyError(", ".join(missing))
            if name == "news":
                c = News(None if a.type == "user" else q, registry=plan["sites"], sitemaps_per_site=a.sitemaps_per_site, workers=a.workers)
                c.site_report.update({h: {"outlet": outlet_name(h), "country": outlet_country(h), "sitemap_items": 0, "feed_items": 0,
                                          "matched": 0, "status": "not approved", "why": w} for h, w in plan["refused"].items()})
            elif name == "blogs":
                c = Blogs()
            elif name == "feeds":
                c = Feeds(feeds=plan["feeds"])
            elif name == "sitemaps":
                c = Sitemaps(plan["sites"], plan["sitemaps"], None if a.type == "user" else q, a.max_sitemaps)
            elif name == "nytimes":
                c = NYTimes(a.nyt_mode, q)
            elif name == "mastodon":
                c = Mastodon(a.mastodon_server)
            else:
                c = COLLECTORS[name]()
            if a.type == "user":
                posts = c.user(a.value, since, until, per)
            else:
                tags = q.hashtags() + q.counter_tags()
                if name in ("feeds", "sitemaps", "news", "blogs"):
                    tags = tags + q.phrases() + q.counter_phrases()
                posts = c.hashtag(tags, since, until, per)
                phrases = q.phrases() + q.counter_phrases()
                try:
                    posts += c.topic(phrases, since, until, per) if phrases and name not in ("feeds", "sitemaps", "news", "blogs") else []
                except NotImplementedError:
                    pass
            if share is not None:
                collected = len(posts)
                posts = thin_evenly(posts, share)
                kept_total += len(posts)
            path, status, n, err = save_posts(posts, data, name), "ok", len(posts), ""
            if isinstance(c, News) and c.site_report and all(v["status"] != "ok" for v in c.site_report.values()):
                status, err = "error", "no news site could be read. Check the network connection, then see access_report.md"
        except Skip as e:
            status, n, err = e.status, 0, e.why
        except LimitReached as e:
            status, n, err = "limit reached", 0, str(e)
        except NotImplementedError as e:
            status, n, err = "not available", 0, str(e)
        except KeyError as e:
            status, n, err = "no key", 0, f"missing environment variable {str(e).strip(chr(39))}"
        except DailyLimit as e:
            status, n, err = "daily limit", 0, str(e)
        except Exception as e:     # record and carry on with the next platform
            status, n, err = "error", 0, repr(e)[:300]
        entry = {"platform": name, "query_type": a.type, "query": a.value, "aliases": a.alias or [], "counter": a.counter or [],
                 "search_strings": q.search_strings() or [a.value], "since": since, "until": until, "status": status,
                 "rows": n, "requests": HTTP.n - before, "file": str(path or ""), "error": err, "started": started,
                 "finished": datetime.now(timezone.utc).isoformat(), "hosts": plan["hosts"],
                 **({"public_figure": a.public_figure} if a.type == "user" else {})}
        if plan["refused"]:
            entry["refused_sites"] = plan["refused"]
        if isinstance(c, News):
            entry["sites"] = c.site_report
        if getattr(c, "opted_out", None):
            entry["opted_out"] = dict(c.opted_out)
        if share is not None:
            entry.update({"max_posts": budget, "share": share, "collected_before_cap": collected})
        if name in runnable:
            left -= 1
        with (data / "manifest.jsonl").open("a") as fh:
            fh.write(json.dumps(entry) + "\n")
        print(f"{name:10s} {status:14s} {n:7d} rows  {err[:100]}")
    HTTP.bind(None, "")
    if budget is not None:
        print(f"\nKept {kept_total:,} posts under --max-posts {budget:,}, shared evenly across the sources that could run.")
    (data / "access_report.md").write_text(access_report(data), encoding="utf-8")
    skipped = [json.loads(l) for l in (data / "manifest.jsonl").read_text().splitlines()]
    skipped = {r["platform"]: r for r in skipped if r.get("started", "") >= started_run and r.get("status") != "ok"}
    if skipped:
        print("\nSkipped sources (the run used the open ones):")
        for name, r in skipped.items():
            h = ACCESS_HELP.get(name)
            how = f" To add it, set {', '.join(h['vars'])} ({h['url']})." if h and r["status"] == "no key" else ""
            print(f"  {name}: {r['status']}. {r['error'][:160].rstrip('.')}.{how}")
    print(f"\nWrote {data / 'access_report.md'}: what could not be read, why, and how to add keys or approvals.")


def cmd_fetch_text(a):
    data = Path(a.data)
    require_ethics(data, "fetch-text")
    df = load_posts(data)
    if a.since:
        df = df[df["created_at"] >= pd.Timestamp(a.since, tz="UTC")]
    if a.until:
        df = df[df["created_at"] < pd.Timestamp(a.until, tz="UTC")]
    reg = load_registry(data)
    approved = [k.split(":", 1)[1] for k in (reg or {}) if k.startswith("fulltext:") and approval(reg, k)[0]]
    domains = approved
    if a.domains:
        domains = [d for d in a.domains if _domain_in(d.lower().removeprefix("www."), approved)]
        for d in a.domains:
            if d not in domains:
                print(f"{d}: skipped. {approval(reg, 'fulltext:' + d.lower().removeprefix('www.'))[1]}.")
    if not domains:
        raise SystemExit("fetch-text reads article pages only from domains approved in sources.csv. For each one, read the "
                         "site's terms, run init --fulltext DOMAIN to add its row, then set decision=approve, date_checked "
                         "and reviewer. Blocked and headlines-only sites (SITE_RULES) can't be approved.")
    HTTP.bind(data, "fetch-text")
    HTTP.keep_raw = bool(a.keep_raw)
    HTTP.site_budget = a.max_requests_per_site
    df = df.assign(created_at=df["created_at"].map(lambda t: t.isoformat() if pd.notna(t) else ""))
    rows, report = fetch_fulltext(df, domains, data / "cache" / "articles", a.min_interval, a.max_per_domain, a.workers)
    HTTP.bind(None, "")
    if rows:
        out = pd.DataFrame(rows).reindex(columns=COLUMNS)
        out["media_urls"] = out["media_urls"].map(lambda v: v if isinstance(v, str) else json.dumps(v or []))
        path = data / "raw" / f"fulltext_{datetime.now(timezone.utc):%Y%m%dT%H%M%S}.parquet"
        out.to_parquet(path, index=False)
    (data / "fetch_report.json").write_text(json.dumps(report, indent=2))
    with (data / "manifest.jsonl").open("a") as fh:
        fh.write(json.dumps({"platform": "fetch-text", "status": "ok", "rows": sum(v["fetched"] for v in report.values()),
                             "domains": domains, "search_strings": [], "error": "",
                             "started": datetime.now(timezone.utc).isoformat()}) + "\n")
    for d, v in sorted(report.items(), key=lambda kv: -kv[1]["fetched"]):
        print(f"{d:30s} fetched {v['fetched']:5d}  skipped {v['skipped']}  {v.get('why', '')}")
    (data / "access_report.md").write_text(access_report(data), encoding="utf-8")
    print(f"Sites that refused or hid their pages are listed in {data / 'access_report.md'}.")


def _clean_and_audit(a):
    out = Path(a.data) / "outputs"
    out.mkdir(parents=True, exist_ok=True)
    q = query_of(a)
    raw = attach_transcripts(load_posts(a.data), Path(a.data))
    df, steps, det = prepare(raw, None if a.type == "user" else q, a.since, a.until, not a.all_languages, a.near_dup)
    rep = audit(raw, df, det, Path(a.data))
    (out / "cleaning_log.json").write_text(json.dumps(steps, indent=2))
    (out / "audit.json").write_text(json.dumps(rep, indent=2, default=str))
    (out / "audit.md").write_text(audit_markdown(rep, steps), encoding="utf-8")
    df.to_parquet(out / "posts_clean.parquet", index=False)        # for the pilot relevance check
    print("cleaning:", steps)
    for w in rep["warnings"]:
        print("WARNING:", w)
    return q, df, steps, det, out


def cmd_audit(a):
    _, df, _, _, out = _clean_and_audit(a)
    print(f"{len(df):,} items kept. Read {out / 'audit.md'} before running any model.")


def cmd_analyze(a):
    q, df, steps, det, out = _clean_and_audit(a)
    if df.empty:
        raise SystemExit("No posts left after cleaning. Check the query, the window, audit.md and the manifest.")
    qwords = query_stopwords(a.value, (a.alias or []) + (a.counter or []))
    meta = {"type": a.type, "value": a.value, "label": q.label(), "aliases": a.alias or [], "counter": a.counter or [], "exclude": a.exclude or [],
            "variants": q.variant_table(), "query_tags": q.hashtags() + q.counter_tags(),
            "since": iso(a.since) if a.since else "", "until": iso(a.until) if a.until else "",
            "stance_target": a.stance_target or a.value, "min_edge": a.min_edge, "min_tag_edge": a.min_tag_edge,
            "near_dup": a.near_dup, "english_only": not a.all_languages, "notes": [], "network": a.network,
            "flow_window": a.flow_window, "videos_transcribed": int(df["has_transcript"].sum()) if "has_transcript" in df else 0}
    pd.DataFrame(term_counts(df, qwords).most_common(200), columns=["term", "count"]).to_csv(out / "top_terms.csv", index=False)
    import networkx as nx
    if a.network == "post":
        nx.write_gexf(cooccurrence_network(df, qwords, a.min_edge), out / "word_network.gexf")
    else:
        wf = word_flow_network(df, qwords, window=a.flow_window, min_count=a.min_edge)
        nx.write_gexf(wf, out / "word_network.gexf")
        pd.DataFrame(flow_edges(wf, top=200)).to_csv(out / "word_flow_edges.csv", index=False)
    heads = main_headlines(df, qwords)
    (out / "headlines.json").write_text(json.dumps(heads, indent=2))
    sl = source_list(df)
    sl.to_csv(out / "sources.csv", index=False)
    hg = hashtag_network(df, meta["query_tags"], a.min_tag_edge)
    nx.write_gexf(hg, out / "hashtag_network.gexf")
    nb = network_neighbours(hg)
    if nb:
        pd.DataFrame(nb).to_csv(out / "hashtag_neighbours.csv", index=False)
    (out / "descriptives.json").write_text(json.dumps(descriptives(df, det["reposts"]), indent=2, default=str))
    if not a.lexical_only:
        parts = [df]
        if have("transformers"):
            parts += [sentiment(df), emotion(df)]
            meta["sentiment_method"] = MODELS["sentiment"]
            if a.type != "user" and not a.skip_stance:
                parts.append(stance(df, a.stance_target or a.value))
        elif have("vaderSentiment"):
            parts.append(sentiment_vader(df))
            meta["sentiment_method"] = "VADER (transformers not installed)"
            meta["notes"].append("Emotion and stance need transformers, so they did not run.")
        else:
            meta["notes"].append("No sentiment model installed (transformers or vaderSentiment).")
        df = pd.concat(parts, axis=1)
        if have("spacy"):
            try:
                ents = entities(df)
                if len(ents):
                    ents.groupby(["entity", "type"]).size().sort_values(ascending=False).head(200).to_csv(out / "top_entities.csv")
            except OSError:
                meta["notes"].append("spaCy model en_core_web_sm is not installed: python -m spacy download en_core_web_sm")
        if not a.skip_topics and len(df) >= 200 and have("bertopic"):
            tm, ids, over_time = topics(df)
            df["topic"] = ids
            tm.get_topic_info().to_csv(out / "topics.csv", index=False)
            over_time.to_csv(out / "topics_over_time.csv", index=False)
    if not a.skip_topics:
        nmf = nmf_topics(df, qwords)
        if nmf:
            df["topic_nmf"] = nmf["ids"]
            nmf["table"].to_csv(out / "topics_nmf.csv", index=False)
            meta.update(nmf_k=nmf["k"], nmf_stability=nmf["stability"])
    (out / "keyness.json").write_text(json.dumps(keyness(df, qwords), indent=2))
    rb = robustness(df, q)
    if len(rb):
        rb.to_csv(out / "robustness.csv", index=False)
    summary = {"posts": len(df), "by_platform": df["platform"].value_counts().to_dict(),
               "main_headlines": [{k: h[k] for k in ("headline", "outlets", "items", "first")} for h in heads[:10]],
               "news_items": int(is_news(df).sum()), "blog_items": int(is_blog(df).sum()),
               "news_outlets": int(sl.loc[sl["type"] == "news", "domain"].nunique()) if len(sl) else 0,
               "news_countries": sorted(set(sl["country"]) - {""}) if len(sl) else [],
               "videos_transcribed": meta["videos_transcribed"],
               "by_kind": df["kind"].value_counts().to_dict(), "by_match_type": df["match_type"].value_counts().to_dict(),
               "first": str(df["created_at"].min()), "last": str(df["created_at"].max()),
               "suspect_items": int(df["suspect"].sum()), "top_terms": dict(term_counts(df, qwords).most_common(30)),
               "audit_warnings": json.loads((out / "audit.json").read_text())["warnings"]}
    for col, name in (("sent_label", "sentiment"), ("emo_label", "emotion"), ("stance_label", "stance")):
        if col in df:
            t = share_table(df, col)
            t.to_csv(out / f"shares_{name}.csv", index=False)
            summary[f"{name}_shares_with_ci"] = t.to_dict("records")
            ns = share_table(df[~df["suspect"]], col, by=None)
            summary[f"{name}_shares_without_suspect"] = ns.to_dict("records")
    if "sent_score" in df:
        summary["balanced_mean_sentiment"] = round(float(df.groupby("platform")["sent_score"].mean().mean()), 3)
    if "stance_label" in df and "sent_label" in df:
        summary["stance_by_sentiment"] = pd.crosstab(df["stance_label"], df["sent_label"], normalize="index").round(3).to_dict("index")
    if meta.get("nmf_k"):
        summary["topics_nmf"] = {"k": meta["nmf_k"], "stability": meta["nmf_stability"]}
    summary["notes"] = meta["notes"]
    meta["repro"] = reproducibility()
    (out / "summary.json").write_text(json.dumps(summary, indent=2, default=str))
    (out / "run_meta.json").write_text(json.dumps(meta, indent=2, default=str))
    df.to_parquet(out / "posts_analyzed.parquet", index=False)
    (out / PURGE_MARK).unlink(missing_ok=True)          # the outputs now reflect every purge so far
    for n in meta["notes"]:
        print("note:", n)
    print(f"outputs in {out}. Read audit.md, then write the digest and read it, then summary.json.")


def cmd_digest(a):
    """Writes outputs/reading_packet.md: the material to read before looking at any numbers."""
    require_fresh_outputs(a.data)
    out = Path(a.data) / "outputs"
    df = pd.read_parquet(out / "posts_analyzed.parquet")
    barred = ai_barred_mask(df)
    held = df.loc[barred, "url"].map(domain_of).value_counts()
    df = df[~barred].copy()
    df["created_at"] = pd.to_datetime(df["created_at"], utc=True)
    df["month"] = df["created_at"].dt.strftime("%Y-%m")
    eng = df[["like_count", "reply_count", "share_count"]].apply(pd.to_numeric, errors="coerce").fillna(0).sum(axis=1)
    df = df.assign(engagement=eng)
    news_mask = is_news(df) | is_blog(df)
    seed = random.Random(a.seed)

    def line(r):
        text = re.sub(r"\s+", " ", str(r.text)).strip()
        text = text if len(text) <= a.chars else text[: a.chars].rsplit(" ", 1)[0] + " ..."
        likes = f", engagement {int(r.engagement):,}" if r.engagement else ""
        likes += f", posted {int(r.copies)} times" if getattr(r, "copies", 1) and r.copies > 1 else ""
        who = r.author_name or r.author_handle or "unknown"
        return f"- {r.created_at:%Y-%m-%d} | {r.platform} {r.kind}{likes} | {who} | {text} | {r.url}"

    def sample(g, n):
        return g.sample(min(len(g), n), random_state=seed.randint(0, 10 ** 6)) if len(g) else g

    lines = ["# Reading packet", "",
             f"{len(df):,} posts after cleaning, {df['created_at'].min():%Y-%m-%d} to {df['created_at'].max():%Y-%m-%d}. "
             f"By source: " + ", ".join(f"{k} {v:,}" for k, v in df["platform"].value_counts().items()) + ".", "",
             "Read all of it before opening summary.json. Note storylines, news pegs, voices, positions, "
             "claims to check, surprises and absences in outputs/notes.md.", ""]
    if len(held):
        lines += [f"{int(held.sum()):,} items from outlets whose terms forbid AI use ({', '.join(held.index[:8])}) are left out "
                  "of this packet. They still count in the numbers. Don't quote or summarise them.", ""]

    heads = json.loads((out / "headlines.json").read_text()) if (out / "headlines.json").exists() else []
    for h in heads:
        h["links"] = [l for l in h.get("links", []) if (terms_entry(domain_of(l.get("url", ""))) or {}).get("ai_use") != "forbidden"]
    heads = [h for h in heads if h["links"]]
    if heads:
        lines += ["## 0. Main headlines", "", "The stories most outlets ran. Each one is a group of near-identical headlines.", ""]
        for h in heads:
            lines.append(f"- **{h['headline']}** ({h['outlets']} outlets, {h['items']} items, {h['first']} to {h['last']}"
                         + (f", {', '.join(h['countries'])}" if h.get("countries") else "") + ")")
            lines += [f"  - {l['date']} | {l['outlet']} | {l['title']} | {l['url']}" for l in h["links"]]
        lines.append("")
    if (out / "word_flow_edges.csv").exists():
        fe = pd.read_csv(out / "word_flow_edges.csv").head(25)
        if len(fe):
            lines += ["## 0b. Word flows", "", "The most frequent word sequences across all the text (A -> B: B follows A).", ""]
            lines += [f"- {r['from']} -> {r['to']}: {r['count']:,}" + (f" (and {r['reverse']:,} the other way)" if r["reverse"] else "")
                      for _, r in fe.iterrows()] + [""]
    if "has_transcript" in df and df["has_transcript"].any():
        tv = df[df["has_transcript"]]
        lines += ["## 0c. Video transcripts", "", f"{len(tv):,} posts carry an English video transcript, already in their text below.", ""]
        lines += [line(r) for r in tv.nlargest(min(10, len(tv)), "engagement").itertuples()] + [""]

    news = df[news_mask].sort_values("created_at")
    if len(news):
        lines += ["## 1. News coverage, in date order", ""]
        if len(news) > a.news:
            news = pd.concat([sample(g, max(1, a.news * len(g) // len(news))) for _, g in news.groupby("month")])
            lines += [f"(A spread sample of {len(news):,} items across the months.)", ""]
        for month, g in news.sort_values("created_at").groupby("month"):
            lines += [f"### {month}", ""] + [line(r) for r in g.itertuples()] + [""]

    social = df[~news_mask]
    lines += ["## 2. Posts by platform", ""]
    for plat, g in social.groupby("platform"):
        top = g.nlargest(min(a.top, len(g)), "engagement")
        rest = g.drop(top.index)
        months = max(rest["month"].nunique(), 1)
        spread = pd.concat([sample(m, max(2, a.per_platform // months)) for _, m in rest.groupby("month")]) if len(rest) else rest
        lines += [f"### {plat}: {len(g):,} posts", "", "Most engaged:", ""] + [line(r) for r in top.itertuples()]
        lines += ["", "Random sample across the months:", ""] + [line(r) for r in spread.sort_values("created_at").itertuples()] + [""]

    weekly = df.set_index("created_at").resample("W")["post_id"].count().sort_values(ascending=False).head(5)
    if len(weekly):
        lines += ["## 3. The busiest weeks", "", "Look for the event behind each spike.", ""]
        for wk, n in weekly.items():
            g = df[(df["created_at"] > wk - pd.Timedelta(days=7)) & (df["created_at"] <= wk)]
            lines += [f"### Week ending {wk:%Y-%m-%d}: {n:,} posts", ""] + [line(r) for r in g.nlargest(min(6, len(g)), "engagement").itertuples()] + [""]

    if "topic" in df.columns and (out / "topics.csv").exists():
        names = pd.read_csv(out / "topics.csv").set_index("Topic")["Name"].to_dict()
        lines += ["## 4. Topics found by the model", ""]
        for t, g in df[df["topic"] != -1].groupby("topic"):
            lines += [f"### Topic {t}: {names.get(t, '')} ({len(g):,} posts)", ""] + [line(r) for r in sample(g, 6).itertuples()] + [""]

    path = out / "reading_packet.md"
    path.write_text("\n".join(lines), encoding="utf-8")
    print(f"{path} ({len(lines):,} lines)")


def cmd_videos(a):
    """Lists the posts that carry a video, so the user can approve transcription. Downloads nothing."""
    data = Path(a.data)
    src = data / "outputs" / "posts_clean.parquet"
    df = pd.read_parquet(src) if src.exists() else load_posts(data)
    c = video_candidates(df)
    reg = load_registry(data)
    for i in c.index[c["can_transcribe"]]:
        ok, why = approval(reg, f"video:{domain_of(c.at[i, 'video_url'])}")
        if not ok:
            c.loc[i, ["can_transcribe", "why"]] = [False, f"host not approved for transcription: {why}"]
    folder = data / "videos"
    folder.mkdir(parents=True, exist_ok=True)
    c.to_csv(folder / "candidates.csv", index=False)
    ok, no = c[c["can_transcribe"]], c[~c["can_transcribe"]]
    print(f"{len(ok):,} videos can be transcribed, from {ok['uid'].nunique():,} posts: "
          + ", ".join(f"{k} {v:,}" for k, v in ok["platform"].value_counts().items()))
    if len(no):
        print(f"{len(no):,} videos can't be: " + "; ".join(sorted(set(no["why"]))))
    print(f"List: {folder / 'candidates.csv'}")
    if len(ok):
        print("Ask the user before transcribing. Tell them how many videos, from which platforms, that audio is read from the "
              "public video file and transcribed on this computer, and that only English videos are transcribed. "
              f"Then run: python titus_scraper.py transcribe --data {a.data} --approved")


def cmd_transcribe(a):
    """Transcribes the approved videos in videos/candidates.csv. English only."""
    data = Path(a.data)
    cpath = data / "videos" / "candidates.csv"
    if not cpath.exists():
        raise SystemExit(f"Run videos --data {a.data} first, and show the user the list.")
    if not a.approved:
        raise SystemExit("Transcription needs the user's approval. Show them the videos command's summary, ask, and rerun "
                         "with --approved only if they say yes.")
    if not os.environ.get(CONTACT_ENV, "").strip():
        raise SystemExit(f"Set {CONTACT_ENV} to your email or website first, so each request says who is asking.")
    cands = pd.read_csv(cpath)
    cands["can_transcribe"] = cands["can_transcribe"].astype(str).str.lower() == "true"
    reg = load_registry(data)
    allowed = [k.split(":", 1)[1] for k in (reg or {}) if k.startswith("video:") and approval(reg, k)[0]]
    if not allowed:
        raise SystemExit("transcribe reads video only from hosts approved in sources.csv. For each host, read its terms, "
                         "run init --video DOMAIN to add its row, then set decision=approve, date_checked and reviewer.")
    require_ethics(data, "transcribe")
    HTTP.bind(data, "transcribe")
    out = transcribe_videos(cands, data / "videos", WhisperTranscriber(a.model), max_seconds=a.max_minutes * 60,
                            min_prob=a.min_language_prob, limit=a.max_videos, allowed=allowed)
    HTTP.bind(None, "")
    print(out["status"].map(lambda v: v.split(" (")[0]).value_counts().to_string())
    print("English transcripts are added to their posts' text. Rerun audit and analyze so the analysis uses them.")


def _tasks(a) -> list[str]:
    return [t.strip() for t in a.tasks.split(",") if t.strip()]


def _posts_for_validation(data) -> pd.DataFrame:
    out = Path(data) / "outputs"
    for name in ("posts_analyzed.parquet", "posts_clean.parquet"):
        if (out / name).exists():
            return pd.read_parquet(out / name)
    raise SystemExit("Run audit (for a relevance pilot) or analyze first.")


def cmd_sample(a):
    df = _posts_for_validation(a.data)
    tasks = _tasks(a)
    for t in tasks:
        if t not in TASKS:
            raise SystemExit(f"unknown task {t}. Choose from {', '.join(TASKS)}")
        if TASKS[t][0] and TASKS[t][0] not in df:
            raise SystemExit(f"{t}: the model did not run, so there is nothing to check. Run analyze with the models first.")
    res = make_sheets(df, tasks, a.n, Path(a.data) / "validation", a.seed)
    print(json.dumps(res, indent=2))
    print("Give coder_A.csv and coder_B.csv to two people who label alone, with the codebook in references/validation.md. Then run agree.")


def cmd_agree(a):
    print(json.dumps(agreement(Path(a.data) / "validation", _tasks(a)), indent=2))
    print("Settle each blank *_gold cell in validation/adjudicate.csv together, then run score.")


def cmd_score(a):
    df = _posts_for_validation(a.data)
    for t in _tasks(a):
        print(json.dumps(score(Path(a.data) / "validation", df, t), indent=2))


PURGE_MARK = "purge_pending.json"      # in outputs/: a purge happened after the last analyze


def _purge_derived(data: Path, uids: set, urls: set, platforms: set) -> list[str]:
    """Carries a purge into everything built from the posts: cached article text, transcripts and the video
    list, the cleaned and analysed tables, the coder sheets, and the files that quote posts (the reading
    packet, the source list, the headlines). It marks the outputs as needing analyze again, and report and
    digest refuse to run until analyze has. Returns what it changed."""
    done = []
    for u in urls:
        f = data / "cache" / "articles" / f"{stable_id(u)}.txt"
        if f.exists():
            f.unlink()
            done.append(f"cache/articles/{f.name}")

    def filt(path: Path, col: str, bad: set, reader, writer):
        if not path.exists():
            return
        d = reader(path)
        if col == "uid" and "uid" not in d and {"platform", "post_id"} <= set(d.columns):
            key = d["platform"].astype(str) + ":" + d["post_id"].astype(str)
        else:
            key = d.get(col)
        if key is None:
            return
        keep = d[~key.isin(bad)]
        if len(keep) < len(d):
            writer(keep, path) if len(keep) else path.unlink()
            done.append(str(path.relative_to(data)))

    pq = (pd.read_parquet, lambda d, p: d.to_parquet(p, index=False))
    csv = (lambda p: pd.read_csv(p, dtype=str, keep_default_na=False), lambda d, p: d.to_csv(p, index=False))
    filt(data / "videos" / "transcripts.parquet", "uid", uids, *pq)
    filt(data / "videos" / "candidates.csv", "uid", uids, *csv)
    filt(data / "outputs" / "posts_clean.parquet", "uid", uids, *pq)
    filt(data / "outputs" / "posts_analyzed.parquet", "uid", uids, *pq)
    key = data / "validation" / "key.csv"
    if key.exists():
        k = pd.read_csv(key, dtype=str, keep_default_na=False)
        gone = set(k.loc[k["uid"].isin(uids), "item"])
        if gone:
            for name in ("key.csv", "coder_A.csv", "coder_B.csv", "adjudicate.csv"):
                filt(data / "validation" / name, "item", gone, *csv)
    for name in ("reading_packet.md", "sources.csv", "headlines.json"):
        f = data / "outputs" / name
        if f.exists():
            f.unlink()
            done.append(f"outputs/{name}")
    raw_resp = data / "raw_responses"
    for p in platforms:                      # a page of responses may hold a removed post among others
        folder = raw_resp / p
        if folder.exists():
            for f in folder.glob("*.gz"):
                f.unlink()
            done.append(f"raw_responses/{p}/")
    if (data / "outputs").exists():
        (data / "outputs" / PURGE_MARK).write_text(json.dumps({"time": datetime.now(timezone.utc).isoformat(), "items": len(uids)}))
    return done


def purge_rows(data, platform: str | None = None, older_than_days: int = 30, author: str | None = None, record: bool = True,
               posts: set | None = None, every_platform: bool = False) -> int:
    """Deletes stored items: one platform's items collected N or more days ago, every item by one author, or
    the posts named as (platform, post_id). Rewrites the raw files, carries the deletion into every derived
    file (_purge_derived), logs the purge in the manifest and returns how many rows went."""
    data, now, removed = Path(data), datetime.now(timezone.utc), 0
    uids, urls, plats = set(), set(), set()
    posts = {f"{p}:{i}" for p, i in (posts or set())}
    for f in sorted((data / "raw").glob("*.parquet")):
        d = pd.read_parquet(f)
        if "platform" not in d or "collected_at" not in d:
            continue
        coll = pd.to_datetime(d["collected_at"], utc=True, errors="coerce", format="ISO8601")
        drop = pd.Series(False, index=d.index)
        if platform:
            drop |= (d["platform"] == platform) & ((now - coll).dt.days >= older_than_days)
        if every_platform:
            drop |= (now - coll).dt.days >= older_than_days
        if author:
            who = author.lstrip("@").lower()
            cols = [c for c in ("author_handle", "author_id") if c in d]
            drop |= d[cols].apply(lambda c: c.fillna("").str.lstrip("@").str.lower() == who).any(axis=1)
        if posts:
            drop |= (d["platform"].astype(str) + ":" + d["post_id"].astype(str)).isin(posts)
        if drop.any():
            removed += int(drop.sum())
            gone = d[drop]
            uids |= set(gone["platform"].astype(str) + ":" + gone["post_id"].astype(str))
            urls |= set(gone["url"].dropna().astype(str)) if "url" in gone else set()
            plats |= set(gone["platform"].astype(str))
            keep = d[~drop]
            if len(keep):
                keep.to_parquet(f, index=False)
            else:
                f.unlink()
    raw_resp = data / "raw_responses"
    for folder in ([raw_resp / platform] if platform else []) + (sorted(raw_resp.glob("*")) if every_platform else []):
        for f in (folder.glob("*.gz") if folder.is_dir() else []):
            if (now - datetime.fromtimestamp(f.stat().st_mtime, timezone.utc)).days >= older_than_days:
                f.unlink()
    if every_platform:          # cached pages and transcripts of items that are gone are removed with them below
        for f in (data / "cache" / "articles").glob("*.txt") if (data / "cache" / "articles").exists() else []:
            if (now - datetime.fromtimestamp(f.stat().st_mtime, timezone.utc)).days >= older_than_days:
                f.unlink()
    changed = _purge_derived(data, uids, urls, plats if (author or posts) else set()) if uids else []
    if removed or record:
        with (data / "manifest.jsonl").open("a") as fh:
            fh.write(json.dumps({"platform": "purge", "status": "ok", "rows": removed, "search_strings": [], "error": "",
                                 "detail": f"platform={platform or ('every' if every_platform else '')} older_than_days={older_than_days} "
                                           f"author={'given' if author else ''} posts={len(posts)}", "derived_files": changed,
                                 "started": now.isoformat()}) + "\n")
    return removed


def require_fresh_outputs(data) -> None:
    """Stops report and digest after a purge until analyze has run again, so nothing removed reaches a reader."""
    mark = Path(data) / "outputs" / PURGE_MARK
    if mark.exists():
        raise SystemExit(f"Items were deleted from {data} after the last analyze. Rerun audit and analyze (and digest), and "
                         "remove any quote or link to a deleted post from the blog post, before building the report.")


YOUTUBE_DAYS = 30
STUDY_FILE = "study.json"
DEFAULT_RETAIN_DAYS = 365
ETHICS_OK = ("approved", "exempt", "not-human-subjects")


def load_study(data) -> dict:
    """study.json in the run folder: the ethics review, the retention period and where the work runs. init writes it."""
    try:
        return json.loads((Path(data) / STUDY_FILE).read_text())
    except (OSError, ValueError):
        return {}


def require_ethics(data, step: str) -> None:
    """Stops a step that collects material until the study's ethics review is recorded as approved, exempt or
    not human-subjects research, with a reference."""
    eth = load_study(data).get("ethics") or {}
    if eth.get("status") in ETHICS_OK and str(eth.get("ref", "")).strip():
        return
    now = f" It is recorded as {eth['status']}." if eth.get("status") else ""
    raise SystemExit(f"{step} needs the study's ethics review recorded first.{now} Ask the user whether the study has IRB "
                     "(or ethics board) approval, an exemption, or a determination that it is not human-subjects research, "
                     f"then run init --data {data} ... --ethics approved|exempt|not-human-subjects --ethics-ref \"the board, "
                     "the number and the date, or who decided\". Collect nothing while a review is pending.")


def enforce_retention(data) -> int:
    """Deletes every item collected more than retain_days ago (study.json), with everything built from it:
    cached pages, transcripts, saved responses, tables and coder sheets. Every command that loads the posts
    runs it first."""
    days = load_study(data).get("retain_days")
    if not days or not (Path(data) / "raw").exists():
        return 0
    n = purge_rows(data, older_than_days=int(days), record=False, every_platform=True)
    if n:
        log.warning("Deleted %d items collected %d or more days ago, the retention period in %s. Rerun analyze and report.",
                    n, int(days), STUDY_FILE)
    return n


def expire_youtube(data) -> int:
    """Deletes YouTube items collected 30 or more days ago (the YouTube API storage rule). collect and
    every command that loads the posts run it first, so expired items never reach an analysis."""
    raw = Path(data) / "raw"
    if not raw.exists():
        return 0
    n = purge_rows(data, "youtube", YOUTUBE_DAYS, record=False)
    if n:
        log.warning("Deleted %d YouTube items collected %d or more days ago (YouTube's storage rule). Rerun analyze and report.",
                    n, YOUTUBE_DAYS)
    return n


def cmd_purge(a):
    """Deletes stored items: one platform's items older than N days, or every item by one author (a
    deletion request), from the raw files and everything built from them. Rerun analyze and report afterwards."""
    if not (a.platform or a.author):
        raise SystemExit("Pass --platform with --older-than-days, or --author.")
    removed = purge_rows(a.data, a.platform, a.older_than_days, a.author)
    print(json.dumps({"removed": removed, "next": "rerun audit, analyze and digest, check the blog post for quotes of the removed "
                                                   "items, then rerun report"}, indent=2))


def post_exists(platform: str, post_id: str, url: str) -> bool | None:
    """Whether a public post can still be read: True, False (deleted, hidden, or its author opted out since),
    or None when the skill can't check this platform without a key."""
    try:
        if platform == "mastodon":
            m = re.match(r"https?://([^/]+)/@[^/]+/(\d+)", url or "")
            if not m:
                return None
            st = get_json(f"https://{m.group(1)}/api/v1/statuses/{m.group(2)}", tries=2)
            return not Mastodon.opt_out(st)
        if platform == "bluesky":
            if not str(post_id).startswith("at://"):
                return None
            got = get_json("https://public.api.bsky.app/xrpc/app.bsky.feed.getPosts", {"uris": post_id}, tries=2)
            return bool(got.get("posts"))
    except HTTPError as e:
        return False if e.status in (404, 410) else None
    return None


def cmd_recheck(a):
    """Before publishing: checks that the social posts the blog post links to (or, with --all, every social
    post in the data, up to --max) can still be read, and purges the ones that are gone, with everything built
    from them. Mastodon and Bluesky are checked without a key. Others are listed as not checked."""
    if not os.environ.get(CONTACT_ENV, "").strip():
        raise SystemExit(f"Set {CONTACT_ENV} to your email or website first, so each request says who is asking.")
    data = Path(a.data)
    df = load_posts(data)
    social = df[df["platform"].isin(sorted(SOCIAL_PLATFORMS))]
    if not a.all:
        blog = Path(a.blog) if a.blog else data / "outputs" / "blog.md"
        if not blog.exists():
            raise SystemExit(f"No blog post at {blog}. Pass --blog PATH, or --all to check every social post.")
        links = {u.rstrip(").,;]>\"'") for u in URL_RE.findall(blog.read_text(encoding="utf-8"))}
        social = social[social["url"].isin(links)]
    social = social.head(a.max)
    HTTP.bind(data, "recheck")
    res = {"checked": 0, "gone": [], "not_checked": []}
    for r in social.itertuples():
        ok = post_exists(r.platform, str(r.post_id), r.url)
        if ok is None:
            res["not_checked"].append(r.url)
            continue
        res["checked"] += 1
        if not ok:
            res["gone"].append({"platform": r.platform, "post_id": str(r.post_id), "url": r.url})
    HTTP.bind(None, "")
    if res["gone"]:
        purge_rows(data, posts={(g["platform"], g["post_id"]) for g in res["gone"]})
    (data / "outputs").mkdir(parents=True, exist_ok=True)
    (data / "outputs" / "recheck.json").write_text(json.dumps({**res, "time": datetime.now(timezone.utc).isoformat()}, indent=2))
    print(f"Checked {res['checked']:,} posts. {len(res['gone']):,} are gone and were deleted from the data. "
          f"{len(res['not_checked']):,} could not be checked without a key.")
    for g in res["gone"]:
        print(f"  remove from the blog post: {g['url']}")
    if res["gone"]:
        print("Then rerun audit, analyze and digest before report.")


PUBLIC_FILES = ("report.pdf", "report.docx", "report.md", "report.html", "report.tex")


def cmd_export(a):
    """Writes <data>/public/, the only folder meant to leave the computer: the report and aggregate tables in
    which every count below --min-count is shown as "<N", words and hashtags appear only when at least
    --min-count items by at least --min-count accounts or outlets use them, and no handle, name, post id,
    URL or post text appears. The rest of the run folder stays private."""
    import shutil
    data = Path(a.data)
    out = data / "outputs"
    require_fresh_outputs(data)
    if not (out / "posts_analyzed.parquet").exists():
        raise SystemExit("Run analyze first.")
    if not (out / "recheck.json").exists():
        raise SystemExit(f"Run recheck --data {data} first, so posts deleted since collection are out of the report.")
    k = max(1, a.min_count)
    df = pd.read_parquet(out / "posts_analyzed.parquet")
    df["created_at"] = pd.to_datetime(df["created_at"], utc=True)
    pub = data / "public"
    if pub.exists():
        shutil.rmtree(pub)
    pub.mkdir(parents=True)
    small = lambda n: int(n) if n >= k else f"<{k}"
    week = df["created_at"].dt.tz_localize(None).dt.to_period("W").dt.start_time.dt.strftime("%Y-%m-%d")
    vol = df.assign(week=week).groupby(["week", "platform"]).size().reset_index(name="items")
    vol["items"] = vol["items"].map(small)
    vol.to_csv(pub / "volume_by_week.csv", index=False)
    written = ["volume_by_week.csv"]
    for col, name in (("sent_label", "tone_by_platform.csv"), ("stance_label", "stance_by_platform.csv")):
        if col in df and df[col].fillna("").astype(str).str.len().gt(0).any():
            t = df[df[col].fillna("").astype(str) != ""].groupby(["platform", col]).size().reset_index(name="items")
            tot = t.groupby("platform")["items"].transform("sum")
            t["share"] = (t["items"] / tot).round(3).where(t["items"] >= k, "")
            t["items"] = t["items"].map(small)
            t.rename(columns={col: "label"}).to_csv(pub / name, index=False)
            written.append(name)
    who = df.get("author_key", df["author_handle"]).fillna("").astype(str)
    for name, bags in (("top_words.csv", df["text_clean"].fillna("").map(lambda t: set(tokens(t, set())))),
                       ("top_hashtags.csv", df["hashtags"].map(lambda h: set(h) if h is not None else set()))):
        items, people = Counter(), {}
        for bag, w in zip(bags, who):
            for term in bag:
                items[term] += 1
                people.setdefault(term, set()).add(w)
        rows = [{"term": t, "items": n} for t, n in items.most_common() if n >= k and len(people[t]) >= k][: a.top]
        pd.DataFrame(rows, columns=["term", "items"]).to_csv(pub / name, index=False)
        written.append(name)
    copied = []
    for f in PUBLIC_FILES + (("report_full.pdf",) if a.with_full else ()):
        if (out / f).exists():
            shutil.copy2(out / f, pub / f)
            copied.append(f)
    if (out / "report_files").is_dir() and any(f in copied for f in ("report.md", "report.tex")):
        shutil.copytree(out / "report_files", pub / "report_files")
    rc = json.loads((out / "recheck.json").read_text())
    contact = os.environ.get(CONTACT_ENV, "").strip() or "the contact named in the report"
    (pub / "README.md").write_text("\n".join([
        "# Public files", "",
        f"Written by titus-scraper export on {datetime.now(timezone.utc):%Y-%m-%d}. Linked posts were last rechecked on "
        f"{str(rc.get('time', ''))[:10]}.", "",
        "## What is here", "",
        *[f"- `{f}`" for f in copied + written], "",
        f"Counts below {k} are shown as `<{k}`. A word or hashtag is listed only when at least {k} items by at least "
        f"{k} different accounts or outlets use it. No table holds a handle, a name, a post id, a link or post text.", "",
        "## What stays private", "",
        "The collected posts and articles, the cleaned and analysed tables, cached pages, transcripts, coder sheets, "
        "the reading packet, the source lists, saved responses and the request log stay in the run folder. They are "
        "not shared.", "",
        f"To ask for an item's removal, write to {contact}.", ""]), encoding="utf-8")
    print(f"{pub}: {len(copied)} report files and {len(written)} tables. Share only this folder.")
    if not copied:
        print("No report file was found in outputs/. Run report first if the folder should include it.")


def cmd_compare(a):
    if len(a.runs) < 2 or len(a.runs) > 4:
        raise SystemExit("compare takes two to four run folders.")
    labels = a.labels or [json.loads((Path(d) / "outputs" / "run_meta.json").read_text()).get("label") or Path(d).name for d in a.runs]
    if len(labels) != len(a.runs):
        raise SystemExit("Give one --labels entry per run folder.")
    cm = compare_runs(a.runs, labels, Path(a.data), a.title or "")
    print(f"{Path(a.data) / 'outputs' / 'comparison.md'}: {sum(d['clear'] for d in cm['differences'])} clear differences of {len(cm['differences'])}.")


def cmd_report(a):
    """Writes the report in each format asked for. PDF is the default. Part 2 (--full) exists only as a PDF,
    so --full with another format also writes the PDF."""
    require_fresh_outputs(a.data)
    fmts = [f.strip().lower().lstrip(".") for f in (a.format or "").replace(" ", ",").split(",") if f.strip()]
    if not fmts:
        fmts = [Path(a.out).suffix.lstrip(".").lower()] if a.out and Path(a.out).suffix else ["pdf"]
    fmts = list(dict.fromkeys(FORMAT_ALIASES.get(f, f) for f in fmts))
    bad = [f for f in fmts if f not in REPORT_FORMATS]
    if bad:
        raise SystemExit(f"report: unknown format {', '.join(bad)}. Use one or more of: {', '.join(REPORT_FORMATS)}.")
    if a.full and "pdf" not in fmts:
        fmts.append("pdf")
        print("Part 2 (--full) is only available as a PDF, so the PDF is written too.")
    base = Path(a.out) if a.out else Path(a.data) / "outputs" / "report.pdf"
    for f in fmts:
        out = base if (a.out and len(fmts) == 1) else base.with_suffix("." + f)
        print(build_pdf(a.data, a.blog, out, a.title, a.author or "", full=a.full, max_sources=a.max_sources,
                        hide_words=a.hide_word or [], fmt=f))


class FakeWeb:
    """Canned responses for the self-test: {url prefix: (status, headers, body)}. Records every URL asked."""

    def __init__(self, routes: dict):
        self.routes, self.calls = routes, []

    def __call__(self, method, url, headers, json_body):
        self.calls.append(url)
        for prefix in sorted(self.routes, key=len, reverse=True):
            if url.startswith(prefix):
                r = self.routes[prefix]
                r = r.pop(0) if isinstance(r, list) else r
                status, hdr, body = r
                return status, hdr, body if isinstance(body, bytes) else (json.dumps(body) if not isinstance(body, str) else body).encode()
        return 404, {}, b"not found"


def _approve_for_test(folder: Path, sources: list[str], ref: str = ""):
    """A sources.csv that approves these sources, for the self-test."""
    folder.mkdir(parents=True, exist_ok=True)
    rows = [{**{c: "" for c in REGISTRY_COLUMNS}, "source": s, "decision": "approve", "reviewer": "selftest",
             "date_checked": "2026-12-03", "approval_ref": ref} for s in sources]
    pd.DataFrame(rows, columns=REGISTRY_COLUMNS).to_csv(folder / "sources.csv", index=False)
    (folder / STUDY_FILE).write_text(json.dumps({"ethics": {"status": "exempt", "ref": "selftest"}, "retain_days": DEFAULT_RETAIN_DAYS}))


def _selftest_policy(tmp: Path):
    """Site rules, robots.txt (RFC 9309, fail closed), redirects, raw capture and approvals."""
    global HTTP
    ROBOTS.clear()
    TDM.clear()
    assert site_rule("https://api.nytimes.com/svc/x")[1] == "api" and site_rule("https://www.nytimes.com/a.html")[1] == "block"
    assert policy_refusal("https://feeds.bbci.co.uk/news/rss.xml") and not policy_refusal("https://api.nytimes.com/svc/x")
    assert not policy_refusal("https://medium.com/feed/tag/x", "blogs") and policy_refusal("https://medium.com/@a/story", "fetch-text")
    saved = HTTP
    robots_r = "User-agent: *\nDisallow: /*?source=\nDisallow: /private\nAllow: /private/open\n"
    web = FakeWeb({"https://r.example/robots.txt": (200, {}, robots_r),
                   "https://r.example/feed": (200, {"content-type": "application/rss+xml"}, "<rss/>"),
                   "https://r.example/old": (301, {"Location": "/feed"}, ""),
                   "https://r.example/to-google": (302, {"Location": "https://news.google.com/rss/articles/x"}, ""),
                   "https://r.example/to-private": (302, {"Location": "https://s.example/private/x"}, ""),
                   "https://s.example/robots.txt": (200, {}, "User-agent: titus-scraper\nDisallow: /private\n"),
                   "https://down.example/robots.txt": (503, {}, "busy"), "https://gone.example/robots.txt": (404, {}, ""),
                   "https://shut.example/robots.txt": (403, {}, ""), "https://gone.example/page": (200, {}, "ok")})
    HTTP = Http(transport=web, min_interval=0)
    HTTP.bind(tmp, "feeds")
    assert HTTP.get_text("https://r.example/old") == "<rss/>"
    lines = [json.loads(l) for l in (tmp / "requests.jsonl").read_text().splitlines()]
    assert any(l.get("redirect_to") == "https://r.example/feed" for l in lines) and any(l.get("redirect_hop") == 1 for l in lines)
    assert not any(l.get("raw_file") for l in lines) and all(l.get("sha256") for l in lines if l["status"] != "refused"), "raw off by default"
    for url, kind in (("https://r.example/to-google", "policy"), ("https://r.example/to-private", "robots"),
                      ("https://r.example/a?source=rss", "robots"), ("https://r.example/private/x", "robots"),
                      ("https://down.example/page", "robots"), ("https://shut.example/page", "robots"),
                      ("https://www.reuters.com/world/", "policy")):
        try:
            HTTP.get_text(url, tries=1)
            raise AssertionError(f"{url} should have been refused")
        except Blocked as e:
            assert e.kind == kind, (url, e.kind)
    assert ROBOTS.check("https://r.example/private/open/x")[0] and HTTP.get_text("https://gone.example/page") == "ok"
    assert not any("news.google.com" in u or "reuters.com" in u or "s.example/private" in u for u in web.calls), web.calls
    assert any(l.get("status") == "refused" for l in (json.loads(x) for x in (tmp / "requests.jsonl").read_text().splitlines()))
    # credentials never follow a redirect to another host
    seen = []
    HTTP.transport = lambda m, u, h, b: (seen.append((u, dict(h))) or ((302, {"Location": "https://other.example/x"}, b"")
                                         if "first" in u else (200, {}, b"{}")))
    HTTP.bind(tmp, "unit")
    HTTP.get_json("https://api.first.example/x", headers={"Authorization": "Bearer SECRET"})
    assert "Authorization" in seen[0][1] and "Authorization" not in seen[1][1]
    # raw capture only when asked
    HTTP.transport = FakeWeb({"https://api.example/": (200, {"content-type": "application/json"}, {"items": [1]})})
    HTTP.keep_raw = True
    HTTP.get_json("https://api.example/y")
    assert list((tmp / "raw_responses" / "unit").glob("*.gz"))
    HTTP = saved
    ROBOTS.clear()
    # approvals
    _approve_for_test(tmp / "reg", ["gdelt", "reddit", "youtube", "site:bbc.com", "fulltext:ghanaweb.com", "site:citinewsroom.com"])
    reg = load_registry(tmp / "reg")
    assert approval(reg, "gdelt")[0] and not approval(reg, "bluesky")[0] and "approval_ref" in approval(reg, "reddit")[1]
    assert not approval(reg, "site:bbc.com")[0] and "headlines only" in approval(reg, "fulltext:ghanaweb.com")[1]
    assert approval(reg, "site:citinewsroom.com")[0] and "init" in approval(None, "gdelt")[1]
    assert approval(reg, "site:feeds.citinewsroom.com")[0] and not approval(reg, "site:newsroom.com")[0]
    _approve_for_test(tmp / "reg2", ["reddit"], ref="R4R-123")
    assert approval(load_registry(tmp / "reg2"), "reddit")[0]
    assert news_candidates(None, None) == [] and news_candidates(None, ["example.org"])[0][0] == "example.org"
    assert "3news.com" in [d for d, _, _ in news_candidates(["Ghana"], None)]
    # Medium is headlines only: its feed keeps the title and a short summary, never the story
    story = " ".join(f"word{i}" for i in range(400))
    md = (f'<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><item><title>A story</title>'
          f'<link>https://medium.com/@a/a-story-1</link><pubDate>Wed, 04 Mar 2026 09:00:00 GMT</pubDate>'
          f'<description>{" ".join(["intro"] * 80)}</description><content:encoded>{story}</content:encoded></item></channel></rss>').encode()
    item = parse_feed(md, "https://medium.com/feed/tag/x", "medium")[0]
    assert "word399" not in item.text and len(item.text.split()) <= SUMMARY_WORDS + 2, len(item.text.split())
    # YouTube items are deleted 30 days after collection, before any command reads the posts
    old = (datetime.now(timezone.utc) - timedelta(days=31)).isoformat()
    save_posts([Post("youtube", "yt1", "old video", "2026-01-01T00:00:00+00:00", collected_at=old),
                Post("youtube", "yt2", "new video", "2026-01-02T00:00:00+00:00"),
                Post("mastodon", "m1", "old post", "2026-01-01T00:00:00+00:00", collected_at=old)], tmp / "yt", "mix")
    assert sorted(load_posts(tmp / "yt")["post_id"]) == ["m1", "yt2"]


def _selftest_limits(tmp: Path):
    """Retry-After, private addresses, per-site budgets, daily limits, Mastodon opt-outs, purges that reach
    derived files, and the recheck before publishing."""
    global HTTP
    tmp.mkdir(parents=True, exist_ok=True)
    now = datetime(2026, 1, 1, tzinfo=timezone.utc)
    assert retry_after_seconds("120") == 120 and retry_after_seconds("Thu, 01 Jan 2026 00:01:00 GMT", now) == 60
    assert retry_after_seconds("") is None and retry_after_seconds("soon") is None
    assert retry_after_seconds("Wed, 31 Dec 2025 23:00:00 GMT", now) == 0
    assert private_address("127.0.0.1") and private_address("192.168.1.5:8080") and private_address("localhost")
    assert private_address("[::1]:80") and private_address("printer.local") and not private_address("example.org", resolve=False)
    saved = HTTP
    try:
        web = FakeWeb({"https://b.example/": (200, {}, "ok"),
                       "https://slow.example/": (429, {"Retry-After": "3600"}, ""),
                       "https://busy.example/": [(429, {"Retry-After": "0"}, ""), (200, {}, "ok")]})
        HTTP = Http(transport=web, min_interval=0)
        HTTP.bind(tmp, "unit")
        for url, kind in (("http://127.0.0.1/admin", "private"), ("http://10.0.0.8/x", "private"),
                          ("http://localhost:8080/x", "private"), ("file:///etc/passwd", "policy")):
            try:
                HTTP.get_text(url, tries=1)
                raise AssertionError(f"{url} should have been refused")
            except Blocked as e:
                assert e.kind == kind, (url, e.kind)
        assert not any("127.0.0.1" in u or "10.0.0.8" in u or "localhost" in u for u in web.calls), web.calls
        HTTP.site_budget = 2
        assert HTTP.get_text("https://b.example/1") == "ok" and HTTP.get_text("https://b.example/2") == "ok"
        try:
            HTTP.get_text("https://b.example/3")
            raise AssertionError("the per-site budget was not enforced")
        except Blocked as e:
            assert e.kind == "budget"
        HTTP.site_budget = SITE_BUDGET
        assert HTTP.get_text("https://busy.example/x", tries=3) == "ok" and "busy.example" in HTTP.cooldown
        try:
            HTTP.get_text("https://slow.example/x", tries=3)
            raise AssertionError("a one-hour Retry-After was retried")
        except HTTPError as e:
            assert "slow.example" in HTTP.down and e.status == 429
        assert web.calls.count("https://slow.example/x") == 1
        # daily limits: counted across runs in one file, and the source stops at the limit
        day = f"{datetime.now(timezone.utc):%Y-%m-%d}"
        Path(os.environ[USAGE_ENV]).write_text(json.dumps({"2020-01-01": {"guardian": 9}, day: {"guardian": DAILY_LIMITS["guardian"] - 1}}))
        HTTP.bind(tmp, "guardian")
        assert HTTP.get_text("https://b.example/g") == "ok" and USAGE.used("guardian") == DAILY_LIMITS["guardian"]
        try:
            HTTP.get_text("https://b.example/g2")
            raise AssertionError("the daily limit was not enforced")
        except DailyLimit as e:
            assert "guardian" in str(e)
        assert "2020-01-01" not in json.loads(Path(os.environ[USAGE_ENV]).read_text()), "only today's counts are kept"
        Path(os.environ[USAGE_ENV]).unlink()
        # Mastodon opt-outs
        assert Mastodon.opt_out({"account": {"noindex": True}}) == "noindex"
        assert Mastodon.opt_out({"account": {"indexable": False}}) == "indexable false"
        assert Mastodon.opt_out({"account": {"note": "<p>Teacher. No bots please #NoBot</p>"}}) == "#nobot"
        assert Mastodon.opt_out({"account": {"fields": [{"name": "Search", "value": "#nosearch"}]}}) == "#nosearch"
        assert Mastodon.opt_out({"account": {}, "content": "<p>hello</p>", "tags": [{"name": "noarchive"}]}) == "#noarchive"
        assert Mastodon.opt_out({"account": {"indexable": True, "note": "#BLM"}, "content": "<p>#BlackLivesMatter</p>"}) == ""
        HTTP = Http(transport=FakeWeb({"https://m.example/api/v1/accounts/lookup": (200, {}, {"id": "9", "acct": "quiet", "noindex": True})}),
                    min_interval=0)
        mc = Mastodon(["m.example"])
        try:
            mc.user("quiet@m.example", "2026-01-01T00:00:00Z", "2026-02-01T00:00:00Z", 10)
            raise AssertionError("an account that opted out was read")
        except NotImplementedError as e:
            assert "opted out" in str(e) and mc.opted_out["noindex"] == 1

        # purge reaches derived files, and report and digest wait for analyze
        pdir = tmp / "purge"
        posts = [Post("mastodon", "1", "kept post", "2026-01-01T00:00:00+00:00", author_handle="a", url="https://m.example/@a/1"),
                 Post("mastodon", "2", "deleted post", "2026-01-01T00:00:00+00:00", author_handle="b", url="https://m.example/@b/2"),
                 Post("bluesky", "at://did:plc:x/app.bsky.feed.post/3", "gone too", "2026-01-01T00:00:00+00:00",
                      author_handle="c", url="https://bsky.app/profile/c/post/3"),
                 Post("news", "n1", "Headline", "2026-01-01T00:00:00+00:00", url="https://paper.example/n1", kind="headline")]
        save_posts(posts, pdir, "mix")
        (pdir / "outputs").mkdir(parents=True, exist_ok=True)
        pd.DataFrame({"uid": [f"{p.platform}:{p.post_id}" for p in posts], "platform": [p.platform for p in posts],
                      "post_id": [p.post_id for p in posts]}).to_parquet(pdir / "outputs" / "posts_analyzed.parquet", index=False)
        (pdir / "outputs" / "reading_packet.md").write_text("deleted post")
        (pdir / "outputs" / "blog.md").write_text("See https://m.example/@a/1, https://m.example/@b/2 and https://bsky.app/profile/c/post/3.\n")
        (pdir / "validation").mkdir()
        pd.DataFrame({"item": ["i0001", "i0002"], "uid": ["mastodon:1", "mastodon:2"]}).to_csv(pdir / "validation" / "key.csv", index=False)
        pd.DataFrame({"item": ["i0002", "i0001"], "text": ["deleted post", "kept post"]}).to_csv(pdir / "validation" / "coder_A.csv", index=False)
        (pdir / "cache" / "articles").mkdir(parents=True)
        (pdir / "cache" / "articles" / f"{stable_id('https://paper.example/n1')}.txt").write_text("story")
        assert purge_rows(pdir, posts={("news", "n1")}) == 1
        assert not list((pdir / "cache" / "articles").glob("*.txt")) and not (pdir / "outputs" / "reading_packet.md").exists()
        try:
            require_fresh_outputs(pdir)
            raise AssertionError("report would have used outputs built before the purge")
        except SystemExit as e:
            assert "analyze" in str(e)
        (pdir / "outputs" / PURGE_MARK).unlink()
        # recheck: one Mastodon post deleted since collection, one Bluesky post gone, one still there
        HTTP = Http(transport=FakeWeb({"https://m.example/api/v1/statuses/1": (200, {}, {"id": "1", "account": {"indexable": True}}),
                                       "https://m.example/api/v1/statuses/2": (404, {}, {"error": "Record not found"}),
                                       "https://public.api.bsky.app/xrpc/app.bsky.feed.getPosts": (200, {}, {"posts": []})}),
                    min_interval=0)
        cmd_recheck(argparse.Namespace(data=str(pdir), blog=None, all=False, max=500))
        rc = json.loads((pdir / "outputs" / "recheck.json").read_text())
        assert rc["checked"] == 3 and sorted(g["post_id"] for g in rc["gone"]) == ["2", "at://did:plc:x/app.bsky.feed.post/3"], rc
        assert sorted(load_posts(pdir)["post_id"]) == ["1"]
        left = pd.read_parquet(pdir / "outputs" / "posts_analyzed.parquet")
        assert sorted(left["uid"]) == ["mastodon:1"], left["uid"].tolist()
        assert pd.read_csv(pdir / "validation" / "key.csv")["item"].tolist() == ["i0001"]
        assert pd.read_csv(pdir / "validation" / "coder_A.csv")["item"].tolist() == ["i0001"]
        assert (pdir / "outputs" / PURGE_MARK).exists()
        _selftest_optouts(tmp / "optouts")
    finally:
        HTTP = saved


def _selftest_optouts(tmp: Path):
    """Terms register, AI-use flag, TDMRep, RSL licences, page opt-outs, the ethics gate and retention."""
    global HTTP
    tmp.mkdir(parents=True, exist_ok=True)
    # the terms register
    assert terms_entry("apnews.com")["ai_use"] == "forbidden" and terms_entry("feeds.bbci.co.uk")["verdict"] == "blocked"
    assert terms_entry("3news.com")["verdict"] == "unreviewed" and terms_entry("example.org") is None
    gh = _registry_row("site:ghanaweb.com")
    assert gh["terms_url"].startswith("https://www.ghanaweb.com/") and "Terms register (2026-12-03): headlines" in gh["notes"]
    assert "not in references/terms_register.csv" in _registry_row("site:3news.com")["notes"]
    mix = pd.DataFrame({"url": ["https://apnews.com/article/x", "https://www.citinewsroom.com/a", "https://bsky.app/profile/a/post/1", ""],
                        "author_handle": ["", "", "a", "medium.com"]})
    assert ai_barred_mask(mix).tolist() == [True, False, False, True]
    # page signals
    assert page_opt_out({"x-robots-tag": "noai"}, "") and not page_opt_out({"x-robots-tag": "googlebot: noindex"}, "")
    assert "noarchive" in page_opt_out({"x-robots-tag": "otherbot: noindex, titus-scraper: noarchive"}, "")
    assert page_opt_out({}, '<meta name="robots" content="noindex, follow">') and page_opt_out({}, '<meta name="tdm-reservation" content="1">')
    assert not page_opt_out({"x-robots-tag": "max-snippet: 50"}, '<meta name="robots" content="index, follow">')
    assert _tdm_match("/news/*", "/news/a") and not _tdm_match("/news/*", "/sport/a") and _tdm_match("*", "/x")
    # TDMRep file and header, and an RSL licence, through Http and fetch-text
    ROBOTS.clear()
    TDM.clear()
    long = "<html><article>" + "".join(f"<p>Paragraph {i} about the march and the council vote in the city today.</p>" for i in range(12)) + "</article></html>"
    web = FakeWeb({"https://tdm.example/.well-known/tdmrep.json": (200, {}, [{"location": "/news/*", "tdm-reservation": 1,
                                                                                "tdm-policy": "https://tdm.example/policy.json"}]),
                   "https://tdm.example/": (200, {}, long),
                   "https://hdr.example/": (200, {"tdm-reservation": "1"}, long),
                   "https://lic.example/robots.txt": (200, {}, "User-agent: *\nAllow: /\nLicense: https://lic.example/license.xml\n"),
                   "https://lic.example/": (200, {}, long),
                   "https://opt.example/a": (200, {}, long.replace("<html>", '<html><meta name="robots" content="noai">')),
                   "https://opt.example/b": (200, {"X-Robots-Tag": "noarchive"}, long),
                   "https://fine.example/": (200, {}, long)})
    HTTP = Http(transport=web, min_interval=0)
    HTTP.bind(tmp, "news")
    for url in ("https://tdm.example/news/a", "https://hdr.example/x"):
        try:
            HTTP.get_text(url)
            raise AssertionError(f"{url} reserved text and data mining and was read")
        except Blocked as e:
            assert e.kind == "tdm", (url, e.kind)
    assert HTTP.get_text("https://tdm.example/about") == long
    assert ROBOTS.license("https://lic.example/x") == ["https://lic.example/license.xml"]
    urls = ["https://tdm.example/news/b", "https://lic.example/s", "https://opt.example/a", "https://opt.example/b", "https://fine.example/s"]
    rows = pd.DataFrame([dict(Post(platform="news", post_id=str(i), text=f"Headline {i}", created_at="2026-03-04T00:00:00+00:00",
                                    url=u, kind="headline", fulltext_status="metadata-only").row()) for i, u in enumerate(urls)])
    HTTP.bind(tmp, "fetch-text")
    upd, rep = fetch_fulltext(rows, ["tdm.example", "lic.example", "opt.example", "fine.example"], tmp / "cache", min_interval=0)
    st_ = {r["url"]: r["fulltext_status"] for r in upd}
    assert st_ == {"https://tdm.example/news/b": "blocked:tdm-reservation", "https://lic.example/s": "blocked:rsl-licence",
                   "https://opt.example/a": "blocked:opt-out", "https://opt.example/b": "blocked:opt-out",
                   "https://fine.example/s": "fetched"}, st_
    assert "license.xml" in rep["lic.example"]["why"] and "asks not to be stored" in rep["opt.example"]["why"]
    assert "TDMRep" in rep["tdm.example"]["why"] and len(list((tmp / "cache").glob("*.txt"))) == 1, "only the allowed page is cached"
    ROBOTS.clear()
    TDM.clear()
    # the ethics gate and the retention period
    try:
        require_ethics(tmp, "collect")
        raise AssertionError("collect would run with no ethics review recorded")
    except SystemExit as e:
        assert "--ethics" in str(e)
    (tmp / STUDY_FILE).write_text(json.dumps({"ethics": {"status": "pending", "ref": "IRB-1"}}))
    try:
        require_ethics(tmp, "collect")
        raise AssertionError("collect would run while the review is pending")
    except SystemExit as e:
        assert "pending" in str(e)
    (tmp / STUDY_FILE).write_text(json.dumps({"ethics": {"status": "exempt", "ref": "IRB-1"}, "retain_days": 30}))
    require_ethics(tmp, "collect")
    old = (datetime.now(timezone.utc) - timedelta(days=31)).isoformat()
    save_posts([Post("mastodon", "old", "an old post", "2026-01-01T00:00:00+00:00", collected_at=old, url="https://old.example/1"),
                Post("bluesky", "new", "a new post", "2026-01-02T00:00:00+00:00")], tmp, "ret")
    (tmp / "outputs").mkdir(exist_ok=True)
    assert load_posts(tmp)["post_id"].tolist() == ["new"] and (tmp / "outputs" / PURGE_MARK).exists()
    last = json.loads((tmp / "manifest.jsonl").read_text().splitlines()[-1])
    assert last["platform"] == "purge" and "every" in last["detail"], last


def _selftest_units(tmp: Path):
    global HTTP


def _selftest_units(tmp: Path):
    global HTTP
    _selftest_policy(tmp / "policy")
    _selftest_limits(tmp / "limits")
    q = Query("hashtag", "BlackLivesMatter", ["#BLM"], ["bureau of land management"], ["#AllLivesMatter"])
    assert q.hashtags() == ["blacklivesmatter", "blm"] and q.phrases() == ["black lives matter"]
    assert q.matches("Marching today #BlackLivesMatter") == "#blacklivesmatter"
    assert q.match("black-lives matter, said the sign") == ("phrase", "black lives matter")
    # --max-posts: one budget shared evenly across the sources, and posts spread across the window
    assert [share_of(100, 3), share_of(66, 2), share_of(33, 1), share_of(0, 2), share_of(5, 0)] == [34, 33, 33, 0, 0]
    assert has_synthesis(["# T", "## What it all adds up to"]) and not has_synthesis(["# T", "## The storylines", "## Sources"])
    mk = lambda pl, i, day: Post(pl, f"{pl}{i}", f"#BlackLivesMatter post {i}", f"2026-01-{day:02d}T00:00:00+00:00")
    thin = thin_evenly([mk("x", i, i + 1) for i in range(20)], 5)
    assert [p.post_id for p in thin] == ["x0", "x5", "x10", "x14", "x19"], [p.post_id for p in thin]
    assert len(thin_evenly([mk("x", 1, 1), mk("x", 1, 1)], 5)) == 1 and thin_evenly([mk("x", 1, 1)], 0) == []

    class _Few(Collector):
        platform = "few"

        def hashtag(self, tags, since, until, limit):
            return [mk("few", i, i + 1) for i in range(min(3, limit))]

    class _Many(Collector):
        platform = "many"

        def hashtag(self, tags, since, until, limit):
            return [mk("many", i, i % 28 + 1) for i in range(min(6000, limit))]

    saved = dict(COLLECTORS)
    COLLECTORS.update({"few": _Few, "many": _Many})
    try:
        args = ["collect", "--type", "hashtag", "--value", "BlackLivesMatter", "--platforms", "few,many",
                "--since", "2026-01-01", "--until", "2026-02-01"]
        for name in ("maxposts", "default", "override", "explicit"):
            _approve_for_test(tmp / name, ["few", "many"])
        _approve_for_test(tmp / "half", ["few"])
        try:
            main(["collect", "--type", "user", "--value", "someone", "--platforms", "few", "--since", "2026-01-01",
                  "--until", "2026-02-01", "--data", str(tmp / "half")])
            raise AssertionError("an account was collected without --public-figure")
        except SystemExit as e:
            assert "--public-figure" in str(e)
        contact = os.environ.pop(CONTACT_ENV, None)
        try:
            main(args + ["--data", str(tmp / "half")])
            raise AssertionError("collect ran without a contact")
        except SystemExit as e:
            assert CONTACT_ENV in str(e)
        finally:
            if contact is not None:
                os.environ[CONTACT_ENV] = contact
        main(args + ["--data", str(tmp / "half")])
        st = {json.loads(l)["platform"]: json.loads(l)["status"] for l in (tmp / "half" / "manifest.jsonl").read_text().splitlines()}
        assert st == {"few": "ok", "many": "not approved"} and "Not approved in sources.csv" in (tmp / "half" / "access_report.md").read_text(), st
        try:
            main(args + ["--data", str(tmp / "noregistry")])
            raise AssertionError("collect ran without sources.csv")
        except SystemExit as e:
            assert "sources.csv" in str(e)
        main(args + ["--platforms", "few,news,reddit", "--dry-run", "--data", str(tmp / "half")])
        _approve_for_test(tmp / "nonews", ["news"])
        main(["collect", "--type", "hashtag", "--value", "x", "--platforms", "news", "--since", "2026-01-01", "--until", "2026-02-01",
              "--data", str(tmp / "nonews")])
        nn = json.loads((tmp / "nonews" / "manifest.jsonl").read_text().splitlines()[-1])
        assert nn["status"] == "not available" and "--country" in nn["error"], nn
        main(args + ["--max-posts", "10", "--data", str(tmp / "maxposts")])
        got = load_posts(tmp / "maxposts")
        assert len(got) == 10 and int((got["platform"] == "few").sum()) == 3, got["platform"].value_counts().to_dict()
        main(args + ["--data", str(tmp / "default")])
        assert len(load_posts(tmp / "default")) == 3 + DEFAULT_PER_SEARCH, "no --max-posts: the default cap of 5,000 per search applies"
        main(args + ["--max-posts", "6003", "--data", str(tmp / "override")])
        assert len(load_posts(tmp / "override")) == 6003, "--max-posts replaces the default cap"
        main(args + ["--limit", "50", "--data", str(tmp / "explicit")])
        assert len(load_posts(tmp / "explicit")) == 53, "an explicit --limit sets the per-search cap"
    finally:
        COLLECTORS.clear()
        COLLECTORS.update(saved)
    mg = Query("hashtag", "#MakeAmericaGreatAgain,#MakeAmericanGreatAgain,#MAGA,#maga,#makeamericagreatagain,#MAKEAMERICAGREATAGAIN")
    assert sorted(mg.hashtags()) == ["maga", "makeamericagreatagain", "makeamericangreatagain"], mg.hashtags()
    assert sorted(mg.phrases()) == ["make america great again", "make american great again"] and mg.label() == "#MakeAmericaGreatAgain"
    assert mg.matches("Rally tonight #MAGA") == "#maga" and mg.matches("we will make america great again") == "make america great again"
    assert mg.matches("#MAKEAMERICAGREATAGAIN!") == "#makeamericagreatagain" and not mg.matches("a magazine article")
    assert any("given as #MAGA, #maga" in v["variant"] for v in mg.variant_table())
    lo, hi = diff_ci(60, 100, 40, 100)[1:]
    assert 0.05 < lo < 0.08 and 0.31 < hi < 0.34, (lo, hi)
    assert q.match("#AllLivesMatter is the answer") == ("counter", "#alllivesmatter")
    assert q.matches("#BLMX is another tag") == "" and q.matches("#BLM rangers at the Bureau of Land Management") == ""
    assert Query("topic", "Make America Great Again").hashtags() == ["makeamericagreatagain"]
    assert normalise("Check this\u200b out @someone https://t.co/x #BLM") == "Check this out @user http #BLM"
    assert dedup_key("Same text! #BLM") == dedup_key("same text #blm https://x.y")
    assert "SECRET" not in redact("https://api.x/y?api-key=SECRET&q=a&access_token=SECRET")
    p, lo, hi = wilson(5, 10)
    assert abs(p - 0.5) < 1e-9 and abs(lo - 0.2366) < 1e-3 and abs(hi - 0.7634) < 1e-3
    assert abs(cohen_kappa(list("xxyy"), list("xyyy")) - 0.5) < 1e-9
    assert abs(krippendorff_alpha_nominal([["a", "a"], ["b", "b"], ["a", "a"], ["b", "b"]]) - 1.0) < 1e-9
    lo_ = log_odds(["police"] * 30 + ["vote"] * 5, ["vote"] * 30 + ["police"] * 5)
    assert lo_.iloc[0]["word"] == "police" and lo_.iloc[-1]["word"] == "vote"
    nd = near_duplicates(["The council voted to fund new police oversight board today in Riverton city",
                          "The council voted to fund new police oversight board today in Riverton city!!",
                          "Completely different words about a bakery opening on Main Street this week"])
    assert nd == [-1, 0, -1], nd

    # polite client: retry on 429, request log without secrets, raw response kept when asked
    web = FakeWeb({"https://api.example/": [(429, {"Retry-After": "0"}, "slow down"), (200, {"content-type": "application/json"}, {"items": [1, 2]})]})
    saved, HTTP = HTTP, Http(transport=web, min_interval=0)
    HTTP.keep_raw = True
    HTTP.bind(tmp, "unit")
    assert get_json("https://api.example/x", {"api-key": "SECRET", "q": "a"}) == {"items": [1, 2]}
    log_lines = [json.loads(l) for l in (tmp / "requests.jsonl").read_text().splitlines()]
    assert [l["status"] for l in log_lines] == [429, 200] and log_lines[1]["records"] == 2
    assert "SECRET" not in (tmp / "requests.jsonl").read_text() and (tmp / log_lines[1]["raw_file"]).exists()

    # Mastodon: two servers, the same post on both, one server closed, a boost skipped
    st = {"id": "9", "uri": "https://m.one/users/a/statuses/9", "url": "https://m.one/@a/9", "created_at": "2026-03-02T10:00:00Z",
          "content": "<p>Marching for <a>#BlackLivesMatter</a> &amp; justice</p>", "account": {"acct": "a", "url": "https://m.one/@a"},
          "favourites_count": 3, "reblogs_count": 1, "replies_count": 0, "in_reply_to_id": None, "reblog": None}
    boost = {"id": "10", "uri": "u10", "created_at": "2026-03-02T11:00:00Z", "account": {"acct": "b"}, "reblog": st}
    HTTP.transport = FakeWeb({"https://m.one/api/v1/timelines/tag/": [(200, {}, [st, boost]), (200, {}, [])],
                              "https://m.two/api/v1/timelines/tag/": [(200, {}, [st]), (200, {}, [])],
                              "https://m.three/": (401, {}, "login required")})
    got = Mastodon(["m.one", "m.two", "m.three"]).hashtag(["blacklivesmatter"], "2026-01-01T00:00:00Z", "2026-12-31T00:00:00Z", 100)
    assert len(got) == 1 and got[0].text == "Marching for #BlackLivesMatter & justice" and got[0].author_handle == "a@m.one"
    rb = Mastodon.to_post(boost, "m.one", "user", "b@m.one", "x")
    assert rb.kind == "repost" and rb.parent_id == st["uri"] and rb.author_handle == "b"

    # Sitemaps: robots.txt lists an index; one child is disallowed; news:title is used
    robots = "User-agent: *\nDisallow: /private\nSitemap: https://news.example/sitemap_index.xml\n"
    index = ('<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'
             '<sitemap><loc>https://news.example/news-sitemap.xml</loc><lastmod>2026-03-05</lastmod></sitemap>'
             '<sitemap><loc>https://news.example/private/sm.xml</loc></sitemap>'
             '<sitemap><loc>https://news.example/old.xml</loc><lastmod>2020-01-01</lastmod></sitemap></sitemapindex>')
    news_sm = ('<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:news="http://www.google.com/schemas/sitemap-news/0.9">'
               '<url><loc>https://news.example/2026/03/a-1.html</loc><news:news><news:publication><news:name>Example News</news:name></news:publication>'
               '<news:publication_date>2026-03-04T08:00:00Z</news:publication_date><news:title>Black Lives Matter march fills city centre</news:title></news:news></url>'
               '<url><loc>https://news.example/2026/03/black-lives-matter-mural-unveiled-77.html</loc><lastmod>2026-03-05</lastmod></url>'
               '<url><loc>https://news.example/2026/03/football-results-12.html</loc><lastmod>2026-03-05</lastmod></url></urlset>')
    web = FakeWeb({"https://news.example/robots.txt": (200, {}, robots), "https://news.example/sitemap_index.xml": (200, {}, index),
                   "https://news.example/news-sitemap.xml": (200, {}, news_sm)})
    HTTP.transport = web
    sm = Sitemaps(["news.example"], query=q).hashtag(q.hashtags() + q.phrases(), "2026-03-01T00:00:00Z", "2026-04-01T00:00:00Z", 100)
    assert sorted(p.text for p in sm) == ["Black Lives Matter march fills city centre", "black lives matter mural unveiled"], [p.text for p in sm]
    assert not any("/private/" in u or "old.xml" in u for u in web.calls)

    # NYT archive mode: one call a month, filtered with the query dictionary
    os.environ.setdefault("NYT_API_KEY", "test-key")
    docs = [{"_id": "1", "web_url": "https://www.nytimes.com/a.html", "pub_date": "2026-03-04T05:00:00+0000",
             "headline": {"main": "Black Lives Matter at 13"}, "abstract": "A look back."},
            {"_id": "2", "web_url": "https://www.nytimes.com/b.html", "pub_date": "2026-03-05T05:00:00+0000",
             "headline": {"main": "Weather"}, "abstract": "Rain."}]
    HTTP.transport = FakeWeb({"https://api.nytimes.com/svc/archive/v1/2026/3.json": (200, {}, {"response": {"docs": docs}})})
    HTTP.host_interval = {}
    nyt = NYTimes("archive", q)
    HTTP.host_interval = {}
    arch = nyt.hashtag(q.hashtags(), "2026-03-01T00:00:00Z", "2026-04-01T00:00:00Z", 100)
    assert [p.post_id for p in arch] == ["1"] and arch[0].fulltext_status == "summary"

    # Google News items: outlet from <source>, title suffix removed, headline only
    gn = (b'<rss version="2.0"><channel><item><title>March fills city - Example Daily</title><link>https://news.google.com/rss/articles/x</link>'
          b'<pubDate>Wed, 04 Mar 2026 09:00:00 GMT</pubDate><description>&lt;a href="x"&gt;March fills city&lt;/a&gt;</description>'
          b'<source url="https://www.exampledaily.com">Example Daily</source></item></channel></rss>')
    g = parse_feed(gn, "https://news.google.com/rss/search?q=x", "news")[0]
    assert g.text == "March fills city" and g.author_handle == "exampledaily.com" and g.kind == "headline" and g.fulltext_status == "metadata-only"

    # full text: allowed and fetched, NYT refused by its terms, robots.txt refusal, paywall, 403 stops the domain
    body = "<html><body><article>" + "".join(f"<p>Paragraph {i} about the march and the council vote in the city today.</p>" for i in range(12)) + "</article></body></html>"
    pay = '<html><script type="application/ld+json">{"isAccessibleForFree": false}</script><article><p>' + "word " * 200 + "</p></article></html>"
    text, paywalled = extract_text(body)
    assert "Paragraph 3" in text and not paywalled and extract_text(pay)[1]
    HTTP.transport = FakeWeb({"https://ok.example/robots.txt": (200, {}, "User-agent: *\nDisallow: /members\n"),
                              "https://ok.example/story": (200, {"content-type": "text/html"}, body),
                              "https://ok.example/pay": (200, {"content-type": "text/html"}, pay),
                              "https://shut.example/robots.txt": (404, {}, ""),
                              "https://shut.example/": (403, {}, "forbidden")})
    rows = pd.DataFrame([dict(Post(platform="news", post_id=str(i), text=f"Headline {i}", created_at="2026-03-04T00:00:00+00:00",
                                    url=u, kind="headline", fulltext_status="metadata-only").row())
                         for i, u in enumerate(["https://ok.example/story", "https://ok.example/members/x", "https://ok.example/pay",
                                                "https://www.nytimes.com/a.html", "https://shut.example/1", "https://shut.example/2",
                                                "https://other.example/x"])])
    HTTP.host_interval = {}
    (tmp / "cache").mkdir(parents=True, exist_ok=True)       # text cached earlier is reused only when robots.txt still allows the page
    (tmp / "cache" / f"{stable_id('https://ok.example/members/x')}.txt").write_text("cached " * 100, encoding="utf-8")
    upd, report = fetch_fulltext(rows, ["ok.example", "shut.example", "nytimes.com"], tmp / "cache", min_interval=0)
    st_ = {r["url"]: r["fulltext_status"] for r in upd}
    assert st_["https://ok.example/story"] == "fetched" and st_["https://ok.example/members/x"] == "blocked:robots.txt"
    assert st_["https://ok.example/pay"] == "blocked:paywall-or-too-short" and st_["https://www.nytimes.com/a.html"] == "blocked:site-policy"
    assert st_["https://shut.example/1"] == "blocked:http-403" and "https://shut.example/2" not in st_ and "https://other.example/x" not in st_
    assert report["ok.example"]["fetched"] == 1

    # News: one outlet read through its news sitemap and its announced feed, one dead outlet, one item found twice
    HTTP.host_interval = {}
    robots_p = "User-agent: *\nDisallow: /admin\nSitemap: https://paper.example/sitemap.xml\nSitemap: https://paper.example/news-sitemap.xml\n"
    nsm = ('<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:news="http://www.google.com/schemas/sitemap-news/0.9">'
           '<url><loc>https://paper.example/2026/03/march.html</loc><news:news><news:publication><news:name>The Paper</news:name></news:publication>'
           '<news:publication_date>2026-03-04T08:00:00Z</news:publication_date><news:title>Black Lives Matter march reaches parliament</news:title></news:news></url>'
           '<url><loc>https://paper.example/2026/03/budget.html</loc><news:news><news:publication_date>2026-03-04T08:00:00Z</news:publication_date>'
           '<news:title>Budget passes</news:title></news:news></url></urlset>')
    home = '<html><head><link rel="alternate" type="application/rss+xml" href="/rss/latest.xml"><link rel="alternate" type="application/rss+xml" href="/comments/feed"></head></html>'
    feed = ('<rss version="2.0"><channel><item><title>Black Lives Matter march reaches parliament</title><link>https://paper.example/2026/03/march.html</link>'
            '<guid>https://paper.example/2026/03/march.html</guid><pubDate>Wed, 04 Mar 2026 09:00:00 GMT</pubDate><description>Thousands walked.</description></item>'
            '<item><title>Organisers of #BLM vigil speak</title><link>https://paper.example/2026/03/vigil.html</link><pubDate>Thu, 05 Mar 2026 09:00:00 GMT</pubDate>'
            '<description>A vigil.</description></item></channel></rss>')
    web = FakeWeb({"https://paper.example/robots.txt": (200, {}, robots_p), "https://paper.example/news-sitemap.xml": (200, {}, nsm),
                   "https://paper.example/sitemap.xml": (404, {}, ""), "https://paper.example/rss/latest.xml": (200, {}, feed),
                   "https://paper.example/": (200, {"content-type": "text/html"}, home),
                   "https://dead.example/": (403, {}, "no robots here")})
    HTTP.transport = web
    assert discover_feeds(home, "https://paper.example/") == ["https://paper.example/rss/latest.xml", "https://paper.example/comments/feed"]
    nc = News(q, registry=[("paper.example", "The Paper", "Ghana"), ("dead.example", "Dead News", "Kenya"), ("bbc.com", "BBC News", "UK")], workers=2)
    assert "bbc.com" not in nc.sites
    got = nc.hashtag(q.hashtags() + q.phrases(), "2026-03-01T00:00:00Z", "2026-04-01T00:00:00Z", 100)
    assert sorted(p.url for p in got) == ["https://paper.example/2026/03/march.html", "https://paper.example/2026/03/vigil.html"], [p.url for p in got]
    assert all(p.platform == "news" and p.author_name == "The Paper" for p in got) and web.calls.index("https://paper.example/news-sitemap.xml") < web.calls.index("https://paper.example/sitemap.xml")
    assert nc.site_report["paper.example"]["status"] == "ok" and nc.site_report["dead.example"]["status"] == "nothing readable"
    assert len(News(None, countries=["Ghana"]).sites) >= 5 and "3news.com" in News(None, countries=["ghana"]).sites
    assert Blogs.slugs(["blacklivesmatter"], ["black lives matter"]) == ["blacklivesmatter", "black-lives-matter"]
    (tmp / "manifest.jsonl").write_text(json.dumps({"platform": "bluesky", "status": "no key", "rows": 0, "error": "missing environment variable BSKY_HANDLE"}) + "\n"
                                       + json.dumps({"platform": "news", "status": "ok", "rows": 2, "error": "", "sites": nc.site_report}) + "\n")
    ar = access_report(tmp)
    assert "BSKY_APP_PASSWORD" in ar and "bsky.app/settings/app-passwords" in ar and "dead.example" in ar and "1 of 2 sites" in ar, ar

    # directed word network from all the text, main headlines across outlets, the source list
    fdf = pd.DataFrame({"text_clean": ["police reform now"] * 6 + ["reform the police budget"] + ["school budget vote"] * 3})
    fg = word_flow_network(fdf, set(), window=1, min_count=2)
    assert fg.has_edge("police", "reform") and fg["police"]["reform"]["weight"] == 6 and not fg.has_edge("reform", "police") and fg.is_directed()
    hd = pd.DataFrame({"platform": "news", "kind": "headline", "fulltext_status": "metadata-only", "author_name": "",
                       "text": ["Police reform bill passes city council vote", "City council vote passes police reform bill",
                                "Police reform bill passes council after long vote", "Football club wins the cup final again"],
                       "author_handle": ["ghanaweb.com", "bbc.co.uk", "aljazeera.com", "bbc.co.uk"],
                       "url": ["https://www.ghanaweb.com/a", "https://www.bbc.co.uk/b", "https://www.aljazeera.com/c", "https://www.bbc.co.uk/d"],
                       "created_at": pd.to_datetime(["2026-03-01", "2026-03-02", "2026-03-03", "2026-03-02"], utc=True)})
    mh = main_headlines(hd)
    assert mh[0]["outlets"] == 3 and mh[0]["items"] == 3 and {"Ghana", "Qatar", "United Kingdom"} == set(mh[0]["countries"]), mh[0]
    sl_ = source_list(hd)
    assert len(sl_) == 4 and set(sl_["outlet"]) == {"GhanaWeb", "BBC News", "Al Jazeera"} and sl_["url"].str.startswith("https").all()

    # videos: found in posts, transcribed only after approval and only when English, then joined to the post text
    vp = pd.DataFrame([dict(Post(platform="mastodon", post_id="v1", text="Watch the march #BLM", created_at="2026-03-04T00:00:00+00:00",
                                 media_urls=["https://files.example/v1.mp4"]).row()),
                       dict(Post(platform="bluesky", post_id="v2", text="Video from Paris #BLM", created_at="2026-03-04T00:00:00+00:00",
                                 media_urls=["https://video.bsky.app/watch/abc/playlist.m3u8"]).row()),
                       dict(Post(platform="youtube", post_id="v3", text="A YouTube video", kind="video", url="https://youtube.com/watch?v=x",
                                 created_at="2026-03-04T00:00:00+00:00").row())])
    vc = video_candidates(vp)
    assert vc["can_transcribe"].tolist() == [True, True, False] and "terms" in vc.iloc[2]["why"]
    fake_lang = {"v1": ("en", 0.97, "we marched for justice and police reform"), "v2": ("fr", 0.95, "")}
    fake = lambda wav, min_prob: fake_lang[wav.read_text()]
    fake_audio = lambda url, path, secs: path.write_text("v1" if "v1" in url else "v2")
    vdir = tmp / "vrun" / "videos"
    HTTP.transport = FakeWeb({"https://video.bsky.app/watch/abc/playlist.m3u8": (200, {}, "#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=1\n360p/video.m3u8\n"),
                              "https://video.bsky.app/watch/abc/360p/video.m3u8": (200, {}, "#EXTM3U\n#EXTINF:6,\nseg1.ts\n"),
                              "https://video.bsky.app/watch/bad/playlist.m3u8": (200, {}, "#EXTM3U\n#EXTINF:6,\nhttps://cdn.other.example/seg1.ts\n")})
    assert stream_refusal("https://files.example/v1.mp4", []) and "not approved" in stream_refusal("https://files.example/v1.mp4", ["other.example"])
    assert stream_refusal("https://video.bsky.app/watch/abc/playlist.m3u8", ["video.bsky.app"]) == ""
    assert "cdn.other.example" in stream_refusal("https://video.bsky.app/watch/bad/playlist.m3u8", ["video.bsky.app"])
    tr_ = transcribe_videos(vc, vdir, fake, fetch_audio=fake_audio, allowed=["files.example", "video.bsky.app"])
    assert tr_.set_index("uid")["status"].to_dict() == {"mastodon:v1": "ok", "bluesky:v2": "skipped: not English (fr, p=0.95)"}
    assert not [w for w in vdir.glob("*.wav") if w.stat().st_size]
    joined = attach_transcripts(vp, tmp / "vrun")
    assert joined.loc[0, "has_transcript"] and "police reform" in joined.loc[0, "text"] and not joined.loc[1, "has_transcript"]
    vc.to_csv(vdir / "candidates.csv", index=False)
    try:
        cmd_transcribe(argparse.Namespace(data=str(tmp / "vrun"), approved=False))
        raise AssertionError("transcribe ran without approval")
    except SystemExit as e:
        assert "approval" in str(e)
    HTTP = saved
    return q


def _selftest_compare(root: Path):
    """Two small topics, collected into their own run folders, then compared and turned into one PDF."""
    rnd = random.Random(11)
    shared = [Post(platform="bluesky", post_id=f"x{i}", text=f"#BLM and #MAGA rallies met on the same street {i} police vote",
                   created_at=f"2026-0{1 + i % 6}-15T12:00:00+00:00", author_handle=f"both{i % 4}") for i in range(12)]
    topics = {"blm": ("#BlackLivesMatter,#BLM", ["#BlackLivesMatter", "#BLM", "black lives matter"],
                      ["police", "justice", "reform", "march", "mural", "community", "rights", "court"]),
              "maga": ("#MakeAmericaGreatAgain,#MAGA,#maga,#MAKEAMERICAGREATAGAIN",
                       ["#MAGA", "#maga", "#MakeAmericaGreatAgain", "make america great again"],
                       ["border", "economy", "rally", "vote", "jobs", "taxes", "freedom", "court"])}
    dirs = []
    for name, (value, tags, words) in topics.items():
        d = root / name
        posts = [Post(platform=rnd.choice(["bluesky", "mastodon", "youtube"]), post_id=f"{name}{i}",
                      text=f"{rnd.choice(tags)} " + " ".join(rnd.choices(words, k=8)) + f" #{rnd.choice(words)} note {i}",
                      created_at=f"2026-0{1 + i % 6}-{10 + i % 15}T10:00:00+00:00", author_handle=f"{name}user{rnd.randint(1, 40)}",
                      kind=rnd.choice(["post", "post", "comment"])) for i in range(160)]
        save_posts(posts + shared, d, "synthetic")
        args = ["--type", "hashtag", "--value", value, "--data", str(d), "--since", "2026-01-01", "--until", "2026-12-31"]
        main(["analyze"] + args + ["--lexical-only", "--near-dup", "0"])
        meta = json.loads((d / "outputs" / "run_meta.json").read_text())
        assert meta["label"] == value.split(",")[0], meta["label"]
        out = d / "outputs"
        df = pd.read_parquet(out / "posts_analyzed.parquet")
        lean = {"blm": ["positive", "positive", "neutral", "negative"], "maga": ["negative", "negative", "neutral", "positive"]}[name]
        df["sent_label"] = [rnd.choice(lean) for _ in range(len(df))]
        df["sent_score"] = df["sent_label"].map({"negative": -0.6, "neutral": 0.0, "positive": 0.6})
        df["stance_label"] = [rnd.choice(["favor", "favor", "none", "against"]) for _ in range(len(df))]
        df["emo_label"] = [rnd.choice(["anger", "joy", "neutral"]) for _ in range(len(df))]
        df.to_parquet(out / "posts_analyzed.parquet", index=False)
        dirs.append(str(d))
    cmp_dir = root / "blm-vs-maga"
    main(["compare", "--runs", *dirs, "--labels", "Black Lives Matter", "Make America Great Again", "--data", str(cmp_dir)])
    cm = json.loads((cmp_dir / "outputs" / "comparison.json").read_text())
    ov = cm["overlap"]["Black Lives Matter and Make America Great Again"]
    assert ov["items_in_both"] == 12 and ov["accounts_posting_on_both"] == 4, ov
    pos = [d for d in cm["differences"] if d["measure"] == "sentiment" and d["label"] == "positive" and d["platform"] == "all platforms"][0]
    assert pos["diff"] > 0.05 and pos["clear"], pos
    assert "Black Lives Matter vs Make America Great Again" in cm["keyness"] and Path(cm["figures"]["compare_volume"]).exists()
    md = (cmp_dir / "outputs" / "comparison.md").read_text()
    assert "## Overlap" in md and "rallies met on the same street" in md
    blog = cmp_dir / "blog.md"
    blog.write_text("# Two movements, one feed\n\nA synthetic comparison to test the layout.\n\n"
                    "{{figure:compare_volume|Posts per week for each topic.}}\n\n{{figure:t2.wordcloud|Words in the second topic.}}\n")
    pdf = build_pdf(cmp_dir, blog, cmp_dir / "outputs" / "report.pdf")
    assert pdf.exists() and pdf.stat().st_size > 80_000
    print(f"compare check passed. Sample comparison PDF: {pdf}")


def cmd_selftest(a):
    """Synthetic data through every offline step, ending with a sample PDF. It sets a test contact and keeps
    its daily call counts in the run folder, so it never touches the real usage file."""
    import tempfile
    tmp = Path(a.data or tempfile.mkdtemp(prefix="titus_scraper_"))
    tmp.mkdir(parents=True, exist_ok=True)
    saved_env = {k: os.environ.get(k) for k in (CONTACT_ENV, USAGE_ENV)}
    os.environ[CONTACT_ENV] = "selftest@example.org"
    os.environ[USAGE_ENV] = str(tmp / "usage.json")
    try:
        _selftest_run(tmp)
    finally:
        for k, v in saved_env.items():
            if v is None:
                os.environ.pop(k, None)
            else:
                os.environ[k] = v


def _selftest_run(tmp: Path):
    q = _selftest_units(tmp / "units")
    print("unit checks passed")
    rnd = random.Random(3)
    words = ["police", "justice", "protest", "reform", "vote", "community", "violence", "peace", "rights", "march",
             "council", "budget", "school", "mural", "court"]
    posts = []
    for i in range(420):
        plat = rnd.choice(["bluesky", "mastodon", "youtube", "news"])
        tag = rnd.choice(["#BlackLivesMatter", "#BLM", "black lives matter", "#AllLivesMatter"])
        extra = " #" + rnd.choice(["justice", "vote", "police", "community"]) + " #" + rnd.choice(["march", "reform", "peace"])
        posts.append(Post(platform=plat, post_id=str(i), text=f"{tag} " + " ".join(rnd.choices(words, k=9)) + extra + f" in town number {i % 17}",
                          created_at=f"2026-{1 + i % 9:02d}-{10 + i % 9}T10:00:00+00:00", author_handle=f"user{rnd.randint(1, 60)}",
                          kind="headline" if plat == "news" else rnd.choice(["post", "post", "comment"]),
                          author_id="", like_count=rnd.randint(0, 50),
                          url=f"https://news{i % 13}.example/story-{i}" if plat == "news" else ""))
    posts += [Post(platform="bluesky", post_id=f"loud{i}", text=f"#BLM spam blast {i} " + " ".join(rnd.choices(words, k=6)),
                   created_at=f"2026-0{1 + i % 8}-01T00:00:00+00:00", author_handle="loudaccount") for i in range(40)]
    posts.append(Post(platform="bluesky", post_id="off", text="Nothing to do with the topic at all here", created_at="2026-05-01T00:00:00+00:00"))
    posts.append(Post(platform="bluesky", post_id="near", text=posts[0].text + " today", created_at="2026-05-02T00:00:00+00:00"))
    posts.append(Post(platform="bluesky", post_id="rp", text=posts[1].text, kind="repost", parent_id="1", created_at="2026-05-03T00:00:00+00:00"))
    save_posts(posts, tmp, "synthetic")
    (tmp / "manifest.jsonl").write_text(json.dumps({"platform": "bluesky", "status": "ok", "rows": 460,
                                                    "search_strings": q.search_strings(), "error": ""}) + "\n" +
                                        json.dumps({"platform": "x", "status": "not available", "rows": 0, "search_strings": [],
                                                    "error": CLOSED["x"]}) + "\n")
    base = ["--type", "hashtag", "--value", "BlackLivesMatter", "--alias", "#BLM", "--counter", "#AllLivesMatter", "--data", str(tmp)]
    main(["init"] + base + ["--platforms", "bluesky,mastodon,sitemaps", "--site", "ghanaweb.com", "--since", "2026-01-01", "--until", "2026-12-31"])
    assert (tmp / "protocol.md").exists() and "ghanaweb.com/robots.txt" in (tmp / "sources.csv").read_text()
    st = load_study(tmp)
    assert st["ethics"]["status"] == "not recorded" and st["retain_days"] == DEFAULT_RETAIN_DAYS and "## Ethics review" in (tmp / "protocol.md").read_text()
    try:
        main(["init"] + base + ["--ethics", "approved"])
        raise AssertionError("an approval was recorded without a reference")
    except SystemExit as e:
        assert "--ethics-ref" in str(e)
    main(["init"] + base + ["--ethics", "exempt", "--ethics-ref", "Self Test IRB, exemption 2026-001, 2026-12-01", "--retain-days", "400",
                            "--compute", "a test machine"])
    st = load_study(tmp)
    assert st["ethics"]["status"] == "exempt" and st["retain_days"] == 400 and st["compute"] == "a test machine"
    assert "ethics review recorded: exempt" in (tmp / "protocol.md").read_text()
    require_ethics(tmp, "collect")
    # ready-made approvals, a rerun keeps decisions, blocked sites can't be approved, other sources are approved by hand
    main(["init"] + base + ["--platforms", "gdelt,reddit", "--country", "Ghana", "--site", "bbc.com", "--fulltext", "myjoyonline.com",
                            "--approve", "gdelt,mastodon", "--reviewer", "Self Test"])
    reg = load_registry(tmp)
    assert approval(reg, "gdelt")[0] and approval(reg, "mastodon")[0] and not approval(reg, "bluesky")[0] and "site:3news.com" in reg
    assert reg["site:bbc.com"]["decision"] == "blocked" and reg["fulltext:myjoyonline.com"]["decision"] == "blocked"
    assert not approval(reg, "reddit")[0] and "site:ghanaweb.com" in reg
    for bad in (["--approve", "reddit", "--reviewer", "x"], ["--approve", "gdelt"]):
        try:
            main(["init"] + base + bad)
            raise AssertionError(f"init accepted {bad}")
        except SystemExit:
            pass
    main(["audit"] + base + ["--since", "2026-01-01", "--until", "2026-12-31"])
    main(["analyze"] + base + ["--since", "2026-01-01", "--until", "2026-12-31", "--lexical-only"])
    out = tmp / "outputs"
    steps = json.loads((out / "cleaning_log.json").read_text())
    assert steps["collected"] == 463 and steps["after_relevance_filter"] == 462, steps
    assert steps["after_reposts_set_aside"] == 461 and steps["after_near_dedup"] < steps["after_exact_dedup"], steps
    au = json.loads((out / "audit.json").read_text())
    assert au["match_type"].get("counter") and au["posts_per_author"]["bluesky"]["max"] >= 40
    df = pd.read_parquet(out / "posts_analyzed.parquet")
    assert df.loc[df["author_handle"] == "loudaccount", "suspect"].all()
    # stand-in model columns so the later steps and the PDF run without downloading models
    rs = random.Random(5)
    df["sent_label"] = [rs.choice(["negative", "neutral", "positive"]) for _ in range(len(df))]
    df["sent_score"] = df["sent_label"].map({"negative": -0.7, "neutral": 0.0, "positive": 0.6}) + [rs.uniform(-0.2, 0.2) for _ in range(len(df))]
    df["emo_label"] = [rs.choice(["anger", "joy", "neutral", "sadness", "fear"]) for _ in range(len(df))]
    df["stance_label"] = ["against" if m == "counter" else rs.choice(["favor", "favor", "none"]) for m in df["match_type"]]
    df.to_parquet(out / "posts_analyzed.parquet", index=False)
    qwords = query_stopwords("BlackLivesMatter", ["#BLM", "#AllLivesMatter"])
    (out / "keyness.json").write_text(json.dumps(keyness(df, qwords), indent=2))
    robustness(df, q).to_csv(out / "robustness.csv", index=False)
    assert "favor vs against" in json.loads((out / "keyness.json").read_text())
    assert (out / "topics_nmf.csv").exists() and (out / "hashtag_neighbours.csv").exists() and (out / "audit.md").exists()
    assert (out / "word_flow_edges.csv").exists() and (out / "sources.csv").exists() and (out / "headlines.json").exists()
    assert json.loads((out / "run_meta.json").read_text())["network"] == "flow"
    # two coders: A copies the model, B disagrees on every fifth item; then settle and score
    main(["sample", "--data", str(tmp), "--tasks", "stance,sentiment,relevance", "--n", "60"])
    v = tmp / "validation"
    key = pd.read_csv(v / "key.csv")
    for coder in ("A", "B"):
        sh = pd.read_csv(v / f"coder_{coder}.csv").merge(key[["item", "model_stance", "model_sentiment"]], on="item")
        flip = (sh.index % 5 == 0) if coder == "B" else pd.Series(False, index=sh.index)
        sh["stance"] = sh["model_stance"].where(~flip, "none")
        sh["sentiment"] = sh["model_sentiment"]
        sh["relevance"] = ["relevant" if int(it[1:]) % 10 else "partly" for it in sh["item"]]
        sh.drop(columns=["model_stance", "model_sentiment"]).to_csv(v / f"coder_{coder}.csv", index=False)
    main(["agree", "--data", str(tmp), "--tasks", "stance,sentiment,relevance"])
    ag = json.loads((v / "agreement.json").read_text())
    assert ag["sentiment"]["cohen_kappa"] == 1.0 and ag["stance"]["cohen_kappa"] < 1.0
    adj = pd.read_csv(v / "adjudicate.csv", dtype=str).fillna("")
    adj["stance_gold"] = adj["stance_gold"].where(adj["stance_gold"] != "", adj["stance_A"])
    adj.to_csv(v / "adjudicate.csv", index=False)
    main(["score", "--data", str(tmp), "--tasks", "stance,sentiment,relevance"])
    sc = json.loads((v / "validation_stance.json").read_text())
    assert sc["macro_f1"] == 1.0 and abs(sum(sc["corrected_shares"].values()) - 1) < 0.01
    assert json.loads((v / "validation_relevance.json").read_text())["precision_strict"][0] == 0.9
    blog = tmp / "blog.md"
    blog.write_text("# Synthetic test post\n\nThis post uses **synthetic** data to test the PDF layout.\n\n"
                    "## What people said\n\n- Police and justice came up most\n- Tone stayed mixed\n\n"
                    "{{figure:wordcloud|The words used most often.}}\n\nA closing paragraph with a [link](https://example.com).\n")
    pdf = build_pdf(tmp, blog, out / "report.pdf")
    assert pdf.exists() and pdf.stat().st_size > 50_000
    try:
        from pypdf import PdfReader
        txt = "\n".join(pg.extract_text() or "" for pg in PdfReader(str(pdf)).pages)
        assert "Part 2. Analysis report" not in txt and "Key figures" in txt and "Hashtag network" in txt, "default PDF layout"
        assert "Sentiment over time" in txt and "The most used words" in txt and "About the data" in txt
        assert "Posts over time" in txt and "Word network" in txt and "Tone of coverage" in txt, "the three added key figures"
        fullpdf = build_pdf(tmp, blog, out / "report_full.pdf", full=True)
        assert "Part 2. Analysis report" in "\n".join(pg.extract_text() or "" for pg in PdfReader(str(fullpdf)).pages)
    except ImportError:
        pass
    # the same Part 1 in the other formats
    md = build_pdf(tmp, blog, out / "report.md", fmt="md")
    mtxt = md.read_text(encoding="utf-8")
    assert "Key figures" in mtxt and "About the data" in mtxt and "Word network" in mtxt and "Tone of coverage" in mtxt
    imgs = re.findall(r"!\[[^\]]*\]\(([^)]+)\)", mtxt)
    assert len(imgs) >= len(REQUIRED_FIGURES) and all((md.parent / i).exists() for i in imgs), imgs
    hp = build_pdf(tmp, blog, out / "report.html", fmt="html")
    htxt = hp.read_text(encoding="utf-8")
    assert htxt.startswith("<!DOCTYPE html>") and htxt.count("data:image/png;base64,") >= len(REQUIRED_FIGURES)
    assert "<a href=\"https://example.com\">link</a>" in htxt and "<strong>synthetic</strong>" in htxt
    tx = build_pdf(tmp, blog, out / "report.tex", fmt="tex")
    ttxt = tx.read_text(encoding="utf-8")
    assert "\\documentclass" in ttxt and ttxt.rstrip().endswith("\\end{document}")
    tex_figs = re.findall(r"\\includegraphics\[[^\]]*\]\{([^}]+)\}", ttxt)
    assert len(tex_figs) >= len(REQUIRED_FIGURES) and all((tx.parent / f).exists() for f in tex_figs), tex_figs
    assert "\\href{https://example.com}{link}" in ttxt and "\\textbf{synthetic}" in ttxt and "\\section*{Synthetic test post}" in ttxt
    assert "\\subsection*{Key figures}" in ttxt and "\\subsection*{About the data}" in ttxt and " \\\\ \\hline" in ttxt
    for env in ("itemize", "center", "tabular"):
        assert ttxt.count("\\begin{" + env + "}") == ttxt.count("\\end{" + env + "}") > 0, env
    try:
        import docx
        dx = build_pdf(tmp, blog, out / "report.docx", fmt="docx")
        dd = docx.Document(str(dx))
        dtxt = "\n".join(p.text for p in dd.paragraphs)
        assert "Key figures" in dtxt and "About the data" in dtxt and "Synthetic test post" in dtxt
        assert len(dd.inline_shapes) >= len(REQUIRED_FIGURES) and len(dd.tables) >= 1
    except ImportError:
        pass
    hid = build_pdf(tmp, blog, out / "report_hidden.pdf", hide_words=["Town Number"])
    try:
        from pypdf import PdfReader
        assert "town" not in " ".join(pg.extract_text() or "" for pg in PdfReader(str(hid)).pages).lower().split("synthetic test post")[-1].split("about the data")[0].replace("in town number", "")
    except ImportError:
        pass
    df_rs = pd.read_parquet(out / "posts_analyzed.parquet")
    df_rs["created_at"] = pd.to_datetime(df_rs["created_at"], utc=True)
    rs = relevant_sources(df_rs, json.loads((out / "run_meta.json").read_text()), 10)
    assert 0 < len(rs) <= 10 and (len(rs) == 0 or rs["outlet"].nunique() == min(len(rs), source_list(df_rs)["outlet"].nunique()))
    assert sentiment_bin(pd.DataFrame({"created_at": pd.to_datetime(["2020-01-01", "2020-12-01"])}))[1] == "month"
    rss = (b'<?xml version="1.0"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" '
           b'xmlns:dc="http://purl.org/dc/elements/1.1/"><channel><item><title>Why I marched</title>'
           b'<link>https://blog.example/marched</link><guid>p1</guid><dc:creator>A. Writer</dc:creator>'
           b'<pubDate>Tue, 03 Jun 2026 10:00:00 GMT</pubDate><description>Short</description>'
           b'<content:encoded><![CDATA[<p>We walked for <b>#BlackLivesMatter</b> &amp; justice.</p>]]></content:encoded>'
           b'</item></channel></rss>')
    atom = (b'<feed xmlns="http://www.w3.org/2005/Atom"><entry><title>Notes</title><id>e1</id>'
            b'<link rel="alternate" href="https://site.example/notes"/><published>2026-02-01T09:00:00Z</published>'
            b'<author><name>B. Author</name></author><summary>black lives matter rally</summary></entry></feed>')
    fr, fa = parse_feed(rss, "https://blog.example/feed", "web"), parse_feed(atom, "https://site.example/feed", "web")
    assert fr[0].text == "Why I marched\nWe walked for #BlackLivesMatter & justice." and fr[0].author_name == "A. Writer"
    assert fr[0].created_at.startswith("2026-06-03T10:00") and fa[0].url == "https://site.example/notes"
    assert fa[0].author_name == "B. Author" and q.matches(fa[0].text) == "black lives matter"
    nyt = NYTimes.to_post({"_id": "nyt://a/1", "web_url": "https://www.nytimes.com/x.html", "pub_date": "2026-03-04T05:00:00+0000",
                           "headline": {"main": "Protests grow"}, "abstract": "Marchers returned.", "lead_paragraph": "Marchers returned.",
                           "byline": {"original": "By A Reporter"}}, "topic", "black lives matter")
    assert nyt.text == "Protests grow\nMarchers returned." and nyt.created_at.startswith("2026-03-04T05:00")
    cmd_digest(argparse.Namespace(data=str(tmp), per_platform=20, top=5, news=30, chars=200, seed=1))
    ai_dir = tmp / "aiuse" / "outputs"
    ai_dir.mkdir(parents=True)
    pa = pd.read_parquet(out / "posts_analyzed.parquet")
    first_news = pa.index[pa["platform"] == "news"][0]
    pa.loc[first_news, "url"] = "https://apnews.com/article/held-out"
    pa.to_parquet(ai_dir / "posts_analyzed.parquet", index=False)
    cmd_digest(argparse.Namespace(data=str(tmp / "aiuse"), per_platform=20, top=5, news=500, chars=200, seed=1))
    ai_packet = (ai_dir / "reading_packet.md").read_text()
    assert "forbid AI use (apnews.com)" in ai_packet and "held-out" not in ai_packet
    try:
        main(["export", "--data", str(tmp)])
        raise AssertionError("export ran before recheck")
    except SystemExit as e:
        assert "recheck" in str(e)
    cmd_recheck(argparse.Namespace(data=str(tmp), blog=str(blog), all=False, max=500))
    main(["export", "--data", str(tmp), "--min-count", "5"])
    pub = tmp / "public"
    names = {p.name for p in pub.iterdir()}
    assert {"README.md", "volume_by_week.csv", "tone_by_platform.csv", "top_words.csv", "top_hashtags.csv", "report.pdf"} <= names, names
    for f in pub.glob("*.csv"):
        t_ = f.read_text()
        assert "http" not in t_ and "loudaccount" not in t_ and "user1" not in t_, f
    tw = pd.read_csv(pub / "top_words.csv")
    assert len(tw) and (tw["items"] >= 5).all()
    vb = pd.read_csv(pub / "volume_by_week.csv", dtype=str)
    assert set(vb.columns) == {"week", "platform", "items"}
    packet = (out / "reading_packet.md").read_text()
    assert "## 1. News coverage" in packet and "## 2. Posts by platform" in packet and "## 3. The busiest weeks" in packet
    _selftest_compare(tmp / "compare")
    # purge: a deletion request for one author
    n_before = len(load_posts(tmp))
    main(["purge", "--data", str(tmp), "--author", "loudaccount"])
    assert len(load_posts(tmp)) == n_before - 40
    try:
        main(["export", "--data", str(tmp)])
        raise AssertionError("export ran on outputs built before a purge")
    except SystemExit as e:
        assert "analyze" in str(e)
    print(f"selftest passed. Sample PDF: {pdf}")


def main(argv=None):
    logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
    p = argparse.ArgumentParser(prog="titus_scraper", description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    sub = p.add_subparsers(dest="cmd", required=True)
    sub.add_parser("check").set_defaults(fn=cmd_check)

    def query_args(s):
        s.add_argument("--type", choices=["hashtag", "topic", "user"], required=True)
        s.add_argument("--value", required=True, help="BlackLivesMatter, 'Make America Great Again', or an account")
        s.add_argument("--alias", action="append", help="extra '#tag' or phrase, repeatable")
        s.add_argument("--exclude", action="append", help="phrase that marks a false match, repeatable")
        s.add_argument("--counter", action="append", help="opposing '#tag' or phrase, kept and reported apart, repeatable")
        s.add_argument("--data", required=True, help="run folder, e.g. runs/blm")

    i = sub.add_parser("init", help="write protocol.md and sources.csv")
    query_args(i)
    i.add_argument("--platforms", default=DEFAULT_PLATFORMS, help="sources to list in sources.csv")
    i.add_argument("--site", action="append", help="a news site to list as site:<domain>, repeatable")
    i.add_argument("--country", action="append", help="news: list every outlet of this country as site:<domain>, repeatable")
    i.add_argument("--fulltext", action="append", help="a domain fetch-text may read, listed as fulltext:<domain>, repeatable")
    i.add_argument("--video", action="append", help="a host transcribe may read video from, listed as video:<domain>, repeatable")
    i.add_argument("--ethics", choices=["approved", "exempt", "not-human-subjects", "pending"],
                   help="the study's ethics review. collect, fetch-text and transcribe run only after approved, exempt or not-human-subjects")
    i.add_argument("--ethics-ref", help="the board, the protocol number and the date, or who decided and when")
    i.add_argument("--retain-days", type=int, help=f"delete items this many days after collection (default {DEFAULT_RETAIN_DAYS})")
    i.add_argument("--compute", help="where the commands run and the data is stored, e.g. 'my laptop, encrypted disk'")
    i.add_argument("--approve", help=f"write the ready-made approvals for these sources, comma-separated: {', '.join(PRESET_APPROVALS)}")
    i.add_argument("--reviewer", help="who read the terms and approves (needed with --approve)")
    i.add_argument("--since")
    i.add_argument("--until")
    i.add_argument("--force", action="store_true", help="replace protocol.md and sources.csv, dropping every decision in them")
    i.set_defaults(fn=cmd_init)

    c = sub.add_parser("collect")
    query_args(c)
    c.add_argument("--platforms", default=None, help=f"comma-separated sources (default: {DEFAULT_PLATFORMS}, plus feeds or "
                   "sitemaps when their options are given). Each needs an approved row in sources.csv")
    c.add_argument("--country", action="append", help="news: the outlets of this country, repeatable. news needs --country or --site")
    c.add_argument("--dry-run", action="store_true", help="list each source, whether it is approved and the hosts it would contact, then stop")
    c.add_argument("--public-figure", help="with --type user: why the account is a public figure, organisation or outlet (required)")
    c.add_argument("--max-requests-per-site", type=int, default=SITE_BUDGET, help=f"most requests to one host in this run (default {SITE_BUDGET})")
    c.add_argument("--keep-raw", action="store_true", help="also keep every response body in raw_responses/ (off by default; "
                   "requests.jsonl always keeps each body's SHA-256)")
    c.add_argument("--sitemaps-per-site", type=int, default=6, help="news: most sitemap files read per site")
    c.add_argument("--workers", type=int, default=8, help="news: sites read at the same time")
    c.add_argument("--since", required=True)
    c.add_argument("--until", required=True)
    c.add_argument("--max-posts", type=int, default=None, help="most posts to collect in total, across all sources together. "
                   "It replaces the default cap of 5,000 per search string, and the budget is shared evenly among the sources that can run")
    c.add_argument("--limit", type=int, default=None, help="most posts per search string on each source (default: 5,000, "
                   "or no per-search cap when --max-posts is given)")
    c.add_argument("--feed", action="append", help="RSS or Atom feed URL, as URL or label=URL, repeatable")
    c.add_argument("--outlet", action="append", help=f"named outlet feed for feeds: {', '.join(sorted(OUTLET_FEEDS))}")
    c.add_argument("--site", action="append", help="news site domain for news and sitemaps, repeatable. Needs an approved site:<domain> row")
    c.add_argument("--sitemap", action="append", help="sitemap URL for the sitemaps source, repeatable")
    c.add_argument("--max-sitemaps", type=int, default=60, help="most sitemap files read per run")
    c.add_argument("--nyt-mode", choices=["search", "archive"], default="search")
    c.add_argument("--mastodon-server", action="append", help="Mastodon server to read, repeatable (default: five large servers)")
    c.set_defaults(fn=cmd_collect)

    f = sub.add_parser("fetch-text", help="fill in article text from public news and blog pages")
    f.add_argument("--data", required=True)
    f.add_argument("--domains", nargs="+", help="read only these of the approved domains (default: every fulltext:<domain> "
                   "row approved in sources.csv)")
    f.add_argument("--keep-raw", action="store_true", help="also keep every page in raw_responses/ (off by default)")
    f.add_argument("--max-requests-per-site", type=int, default=SITE_BUDGET, help=f"most requests to one host in this run (default {SITE_BUDGET})")
    f.add_argument("--workers", type=int, default=8, help="sites read at the same time, each one slowly")
    f.add_argument("--since")
    f.add_argument("--until")
    f.add_argument("--min-interval", type=float, default=10.0, help="seconds between requests to one site (robots.txt can raise it)")
    f.add_argument("--max-per-domain", type=int, default=200)
    f.set_defaults(fn=cmd_fetch_text)

    for name, fn in (("audit", cmd_audit), ("analyze", cmd_analyze)):
        an = sub.add_parser(name)
        query_args(an)
        an.add_argument("--since")
        an.add_argument("--until")
        an.add_argument("--all-languages", action="store_true")
        an.add_argument("--near-dup", type=float, default=0.85, help="Jaccard threshold for near-duplicates, 0 turns it off")
        an.add_argument("--network", choices=["flow", "post"], default="flow",
                        help="flow: directed word network from all text pooled (default). post: words used in the same post")
        an.add_argument("--flow-window", type=int, default=3, help="flow network: how many following words count as following")
        if name == "analyze":
            an.add_argument("--stance-target", help="e.g. 'the Black Lives Matter movement'")
            an.add_argument("--min-edge", type=int, default=5)
            an.add_argument("--min-tag-edge", type=int, default=3)
            an.add_argument("--lexical-only", action="store_true", help="counts, networks, NMF topics and keyness only, no models")
            an.add_argument("--skip-stance", action="store_true")
            an.add_argument("--skip-topics", action="store_true")
        an.set_defaults(fn=fn)

    d = sub.add_parser("digest", help="write the reading packet")
    d.add_argument("--data", required=True)
    d.add_argument("--per-platform", type=int, default=60, help="random posts per platform, spread over the months")
    d.add_argument("--top", type=int, default=15, help="most engaged posts per platform")
    d.add_argument("--news", type=int, default=150, help="most news items to include")
    d.add_argument("--chars", type=int, default=500, help="characters kept per item")
    d.add_argument("--seed", type=int, default=1)
    d.set_defaults(fn=cmd_digest)

    for name, fn in (("sample", cmd_sample), ("agree", cmd_agree), ("score", cmd_score)):
        s = sub.add_parser(name)
        s.add_argument("--data", required=True)
        s.add_argument("--tasks", default="stance,sentiment", help="comma list of: " + ", ".join(TASKS))
        if name == "sample":
            s.add_argument("--n", type=int, default=200)
            s.add_argument("--seed", type=int, default=42)
        s.set_defaults(fn=fn)

    pg = sub.add_parser("purge", help="delete stored items")
    pg.add_argument("--data", required=True)
    pg.add_argument("--platform", help="e.g. youtube")
    pg.add_argument("--older-than-days", type=int, default=30)
    pg.add_argument("--author", help="delete every item by this handle or id")
    pg.set_defaults(fn=cmd_purge)

    rc = sub.add_parser("recheck", help="before publishing: check that linked posts still exist, and purge the ones that are gone")
    rc.add_argument("--data", required=True)
    rc.add_argument("--blog", help="the blog post whose links to check (default: <data>/outputs/blog.md)")
    rc.add_argument("--all", action="store_true", help="check every Mastodon and Bluesky post in the data, not only the linked ones")
    rc.add_argument("--max", type=int, default=500, help="most posts to check")
    rc.set_defaults(fn=cmd_recheck)

    ex = sub.add_parser("export", help="write public/: the report and aggregate tables with small counts hidden")
    ex.add_argument("--data", required=True)
    ex.add_argument("--min-count", type=int, default=10, help="hide counts below this, and words or hashtags used by fewer items or accounts")
    ex.add_argument("--top", type=int, default=100, help="most words and hashtags listed")
    ex.add_argument("--with-full", action="store_true", help="also copy report_full.pdf (Part 2)")
    ex.set_defaults(fn=cmd_export)

    vd = sub.add_parser("videos", help="list posts with a video, for the user to approve transcription")
    vd.add_argument("--data", required=True)
    vd.set_defaults(fn=cmd_videos)
    tr = sub.add_parser("transcribe", help="transcribe approved English videos on this computer (faster-whisper)")
    tr.add_argument("--data", required=True)
    tr.add_argument("--approved", action="store_true", help="the user approved transcribing the videos listed by the videos command")
    tr.add_argument("--model", default="small", help="faster-whisper model: tiny, base, small, medium, large-v3")
    tr.add_argument("--max-videos", type=int, default=200)
    tr.add_argument("--max-minutes", type=int, default=15, help="read at most this much of each video")
    tr.add_argument("--min-language-prob", type=float, default=0.6, help="transcribe only when English is detected at least this surely")
    tr.set_defaults(fn=cmd_transcribe)

    cp = sub.add_parser("compare", help="compare two to four topics, each analysed in its own run folder")
    cp.add_argument("--runs", nargs="+", required=True, help="the run folders, e.g. runs/blm runs/maga")
    cp.add_argument("--labels", nargs="+", help="a short name for each topic, in the same order")
    cp.add_argument("--data", required=True, help="the comparison folder, e.g. runs/blm-vs-maga")
    cp.add_argument("--title")
    cp.set_defaults(fn=cmd_compare)

    r = sub.add_parser("report")
    r.add_argument("--data", required=True)
    r.add_argument("--blog", required=True, help="the blog post in simple Markdown")
    r.add_argument("--out", help="output path (default: <data>/outputs/report.<format>). With several formats, each one "
                   "takes this name with its own extension")
    r.add_argument("--format", help="pdf (default), docx (Microsoft Word), md (Markdown) or html, or several "
                   "separated by commas, such as pdf,docx")
    r.add_argument("--title")
    r.add_argument("--author")
    r.add_argument("--full", action="store_true", help="add Part 2, the full analysis report (left out by default)")
    r.add_argument("--max-sources", type=int, default=10, help="most sources listed, ranked by relevance (0 lists them all)")
    r.add_argument("--hide-word", action="append", help="a name or word to keep out of the word cloud, word lists and networks, repeatable")
    r.set_defaults(fn=cmd_report)

    t = sub.add_parser("selftest")
    t.add_argument("--data", help="folder for the test run (default: a temp folder)")
    t.set_defaults(fn=cmd_selftest)

    a = p.parse_args(argv)
    a.fn(a)


if __name__ == "__main__":
    main()
