#!/usr/bin/env python3
"""Who AI recommends when you ask for an AEO agency: StartupCookie study, Dec 2026.

Recomputes every number in the study from the raw Promptwatch exports. Standard library only;
nothing here calls the network.

    python3 -I analyze.py            # writes out/results.json, out/tables.md and out/*.csv

Inputs (all saved under raw/):
  raw/pull-2026-12-04T2340Z/responses_*.json   GET /responses, one file per page, per question
  raw/pull-2026-12-04T2340Z/fanouts_*.json     GET /query-fanouts (3 AEO-agency questions)
  raw/pull-2026-12-05T0050Z/fanouts_*.json     GET /query-fanouts (GEO early-stage question)
Rules (hand-maintained, read by this script):
  rules/entities.txt   names and aliases, each with a kind; only [agency] entries count as agencies
  rules/domains.txt    who publishes each cited domain
"""
import collections
import csv
import glob
import json
import os
import re
import statistics
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import aeo_lib as L  # noqa: E402

WINDOW = ("2026-11-04", "2026-12-04")  # inclusive UTC dates of the answer's createdAt
RESP_DIR = os.path.join(HERE, "raw", "pull-2026-12-04T2340Z")
FANOUT_GLOB = os.path.join(HERE, "raw", "pull-*", "fanouts_*.json")
OUT = os.path.join(HERE, "out")

# Promptwatch names the ChatGPT model differently in /query-fanouts
FANOUT_MODEL = {"gpt-4o-search": "gpt-search", "claude-code-cli": "claude-code-cli"}

# ---------------------------------------------------------------- StartupCookie
SC_NAME_RE = re.compile(r"startup\s?cookie", re.I)
SC_DOMAIN = "startupcookie.com"

# ---------------------------------------------------------------- self-ranking warning
# Counted when one sentence of the answer's own prose (citations removed) refers to the
# published rankings/lists and says agencies write them, or rank themselves in them.
LIST_WORD = re.compile(r"\b(rankings?|ranked|lists?|listicles?|round-?ups?|comparisons?|articles?|reviews?|guides?|"
                       r"best-of|top[- ]\d+|shortlists?|directories)\b", re.I)
# Claims about who wrote the rankings. ORDERED claims count only when a list word starts before the
# claim ends, in the same sentence (so "pricing comes from an agency comparison" is not counted); SELF_CONTAINED
# claims carry their own list word ("agency-written listicles", "agencies' own lists").
ORDERED_CLAIMS = [
    # "written by the agencies they rank", "published by agencies selling", "are from agencies that"
    re.compile(r"\b(written|published|produced|authored|compiled|created|run|put out|come|comes|coming)\b"
               r"[^.;:]{0,30}\b(by|from)\b[^.;:]{0,25}\b(agenc\w*|vendors?|firms?|competitors?|providers?)\b", re.I),
    # "agencies ranking themselves", "ranks itself first", "put themselves at the top"
    re.compile(r"\b(rank|ranks|ranking|ranked|list|lists|listing|put|puts|putting|place|places|placing|name|names|naming|"
               r"include|includes|including|feature|features|featuring|market|markets|marketing|promote|promotes|promoting)\s+(itself|themselves)\b", re.I),
    re.compile(r"\bself[- ](published|serving|promotional|promoting|ranked|ranking|interested|authored)\b", re.I),
    re.compile(r"\bconflicts? of interest\b", re.I),
    re.compile(r"\bagencies\s+(that|who)\s+(also\s+)?(sell|offer|compete)", re.I),
]
SELF_CONTAINED_CLAIMS = [
    re.compile(r"\b(agency|vendor|competitor|self)[- ](written|published|authored|produced|run|created|made)\s+(\S+\s+){0,2}"
               r"[\"“]?(lists?|listicles?|rankings?|comparisons?|round-?ups?|best[- ]of|top[- ]\d+)", re.I),
    re.compile(r"\b(agencies|vendors|firms)['’]\s+own\b", re.I),
    re.compile(r"\b(rank|ranks|ranking|list|lists|listing|put|puts)\s+(their|its)\s+own\b", re.I),
    re.compile(r"\b(its|their)\s+own\s+(lists?|rankings?|comparisons?|articles?|round-?ups?|listicles?|blog)\b", re.I),
]
SENT_SPLIT = re.compile(r"(?<=[.!?])\s+|\n+")


def warning_sentences(prose):
    """Sentences of the answer's own prose that warn the rankings are written by agencies in the market."""
    hits = []
    for s in SENT_SPLIT.split(prose):
        if any(p.search(s) for p in SELF_CONTAINED_CLAIMS):
            hits.append(s.strip())
            continue
        lw = LIST_WORD.search(s)
        if lw and any(lw.start() < m.end() for p in ORDERED_CLAIMS for m in p.finditer(s)):
            hits.append(s.strip())
    return hits


# ---------------------------------------------------------------- source-credit mentions
# An agency named only as the author of a source ("NoGood's AEO agencies guide", "see LoudFace's
# list", "published by Blend") is mentioned, not recommended. An answer counts as naming an
# agency when at least one mention is outside such a credit.
CREDIT_BEFORE = re.compile(r"(\bsee|\bper|according to|\bby|\bvia|\bfrom|\bcites?|\bciting|\bin|\bon|\bat|"
                           r"published by|written by|compiled by)\s+(the\s+|an?\s+)?$", re.I)
CREDIT_AFTER = re.compile(r"^(['’]s)?\s+(?:(?:own|AEO|GEO|SEO|AI|LLM|agency|agencies|best|top|fintech|SaaS|B2B|startups?|"
                          r"2026|2027|\d+|search|vendor|comparison|&|and|/|-|GEO/AEO|AEO/GEO)\s+){0,5}"
                          r"(lists?|listicles?|guides?|round-?ups?|rankings?|articles?|blog|posts?|comparisons?|piece|study|"
                          r"report|breakdown|analysis|research|survey)\b", re.I)


def mention_kinds(prose, ent):
    """Return (named_outside_credit, mentioned_at_all) for one entity in one answer."""
    any_hit = False
    for p in ent["patterns"]:
        for m in p.finditer(prose):
            any_hit = True
            before = prose[max(0, m.start() - 40):m.start()]
            after = prose[m.end():m.end() + 80]
            if not (CREDIT_BEFORE.search(before) or CREDIT_AFTER.search(after)):
                return True, True
    return False, any_hit


# ---------------------------------------------------------------- prices
# A price is a dollar amount in the answer's own prose: $5,000, $5k, $5K, $1.5M, $5,000–$10,000.
PRICE_RE = re.compile(r"(?<![\w$])\$\s?(\d{1,3}(?:,\d{3})+|\d+(?:\.\d+)?)\s?([kKmM])?(?![\w])")
NOT_PRICE_RE = re.compile(r"^\s*(?:[-–]\s*\$?[\d.,]+\s?[kKmM]?\s*)?(?:\+\s*)?(ARR|MRR|in (?:annual )?revenue|revenue|in funding|funding|raised|valuation|in pipeline|pipeline|in sales|in closed|of pipeline|seed round|round)\b", re.I)
MONTHLY_RE = re.compile(r"^[^.;\n]{0,40}?(/\s?mo\b|/\s?month|per month|a month|monthly|each month|every month|mo\.|/mo)", re.I)


def amounts(prose):
    """Every dollar amount in the prose, as (value_in_dollars, is_monthly)."""
    out = []
    for m in PRICE_RE.finditer(prose):
        v = float(m.group(1).replace(",", ""))
        mult = {"k": 1e3, "m": 1e6}.get((m.group(2) or "").lower(), 1)
        v *= mult
        tail = prose[m.end():m.end() + 45]
        # company size, funding or results, not a price: "$5M-$50M ARR", "$2M raised", amounts of $1M or more
        if v >= 1e6 or NOT_PRICE_RE.search(tail):
            continue
        mo = MONTHLY_RE.search(tail)
        if mo and re.search(r"year|annual|/\s?yr", tail[:mo.end()], re.I):
            mo = None
        out.append((v, bool(mo)))
    return out


# ---------------------------------------------------------------- source types
SOURCE_TYPES = [
    ("agency_list", "Agency-written list"),
    ("independent_list", "List or directory not written by an agency"),
    ("agency_site", "Agency's own site (other pages)"),
    ("reddit", "Reddit"),
    ("youtube", "YouTube"),
    ("linkedin", "LinkedIn"),
    ("media", "News and media (other pages)"),
    ("other", "Other (software vendors' other pages, reference sites, unrelated)"),
]
LIST_URL_RE = re.compile(r"(best|top-?\d+|\d+-best|agencies|companies|consultants|firms|ranked|ranking|compared|vs\b|alternatives)", re.I)
LIST_TITLE_RE = re.compile(r"\b(best|top \d+|\d+ best|top (geo|aeo|ai|seo|b2b|saas|fintech|generative)|agencies|companies|consultants|firms|ranked|compared|vs\.?)\b", re.I)


def load_domains(path):
    kinds, kind = {}, None
    for line in open(path, encoding="utf-8"):
        line = line.strip()
        if not line or line.startswith("#"):
            continue
        m = re.match(r"^\[(\w+)\]$", line)
        if m:
            kind = m.group(1)
            continue
        kinds[line.lower()] = kind
    return kinds


def is_list_page(c):
    """A ranking or comparison page: never a homepage; otherwise Promptwatch's contentType says
    LISTICLE or COMPARISON, or the URL or title reads as a list ("best", "top 10", "agencies")."""
    path = re.sub(r"^https?://[^/]+", "", c["url"]).split("?")[0].split("#")[0]
    if path in ("", "/"):
        return False
    if c.get("contentType") in ("LISTICLE", "COMPARISON"):
        return True
    return bool(LIST_URL_RE.search(c["url"].split("?")[0])) or bool(LIST_TITLE_RE.search(c.get("title") or ""))


def source_type(c, domains, unknown):
    host = L.registrable_domain(c["url"])
    if host == "reddit.com" or host.endswith(".reddit.com"):
        return "reddit"
    if host in ("youtube.com", "youtu.be"):
        return "youtube"
    if host == "linkedin.com" or host.endswith(".linkedin.com"):
        return "linkedin"
    kind = domains.get(host)
    if kind is None:
        unknown[host] += 1
        kind = "other"
    lst = is_list_page(c)
    if kind == "agency":
        return "agency_list" if lst else "agency_site"
    if kind == "directory":
        return "independent_list"
    if kind in ("media", "tool", "other") and lst:
        return "independent_list"
    if kind == "media":
        return "media"
    return "other"


# ---------------------------------------------------------------- main
def pct(a, b):
    return round(100.0 * a / b, 1) if b else 0.0


def main():
    os.makedirs(OUT, exist_ok=True)
    ents = L.load_entities(os.path.join(HERE, "rules", "entities.txt"))
    agencies = [e for e in ents if e["kind"] == "agency"]
    ent_by_name = {e["name"]: e for e in agencies}
    domains = load_domains(os.path.join(HERE, "rules", "domains.txt"))

    all_resp = L.load_responses(RESP_DIR)
    resp = [r for r in all_resp if L.in_window(r, *WINDOW)]
    resp.sort(key=lambda r: (r["createdAt"], r["model"], r["prompt"]["id"]))
    eng = lambda r: L.ENGINE_CODE[r["model"]]  # noqa: E731
    q = lambda r: L.QUESTION_CODE[r["prompt"]["id"]]  # noqa: E731
    groups = {"all": resp}
    for c in L.ENGINE_ORDER:
        groups[c] = [r for r in resp if eng(r) == c]

    R = {"window": {"start": WINDOW[0], "end": WINDOW[1], "basis": "UTC date of each answer's createdAt"},
         "pulled": "2026-12-04T23:40Z (responses, 3 fanout questions); 2026-12-05T00:50Z (GEO fanouts)"}

    # ---- answers and run days
    days = collections.defaultdict(set)
    for r in resp:
        days[eng(r)].add(r["createdAt"][:10])
    R["answers"] = {
        "total": len(resp),
        "by_engine": {c: len(groups[c]) for c in L.ENGINE_ORDER},
        "by_engine_question": {c: {qq: sum(1 for r in groups[c] if q(r) == qq) for qq in L.QUESTION_ORDER} for c in L.ENGINE_ORDER},
        "by_question": {qq: sum(1 for r in resp if q(r) == qq) for qq in L.QUESTION_ORDER},
        "run_days": {c: sorted(days[c]) for c in L.ENGINE_ORDER},
        "run_days_all": sorted(set(r["createdAt"][:10] for r in resp)),
    }

    # ---- per-answer extraction
    per = []
    for r in resp:
        prose = L.clean_prose(r["content"])
        found = L.find_entities(prose, agencies)
        named, credit_only = [], []
        for n in sorted(found, key=lambda n: found[n]):
            rec, _ = mention_kinds(prose, ent_by_name[n])
            (named if rec else credit_only).append(n)
        cits = r.get("citations") or []
        am = amounts(prose)
        warn = warning_sentences(prose)
        per.append({
            "id": r["id"], "date": r["createdAt"][:10], "engine": eng(r), "question": q(r),
            "agencies": named, "credit_only": credit_only, "n_citations": len(cits),
            "urls": sorted(set(L.normalise_url(c["url"]) for c in cits)),
            "domains": sorted(set(L.registrable_domain(c["url"]) for c in cits)),
            "warning": warn, "amounts": am,
            "sc_named": bool(SC_NAME_RE.search(prose)),
            "sc_in_raw_text": bool(SC_NAME_RE.search(r["content"])),
            "sc_cited": any(L.registrable_domain(c["url"]) == SC_DOMAIN for c in cits),
            "pw_mentioned_our_brand": bool(r.get("mentionedOurBrand")),
        })
    by_id = {p["id"]: p for p in per}

    def sel(code):
        return [p for p in per if code == "all" or p["engine"] == code]

    # ---- agencies
    R["agencies"] = {}
    for code in ["all"] + L.ENGINE_ORDER:
        ps = sel(code)
        cnt = collections.Counter(a for p in ps for a in p["agencies"])
        R["agencies"][code] = {
            "answers": len(ps),
            "answers_naming_any_agency": sum(1 for p in ps if p["agencies"]),
            "distinct_agencies": len(cnt),
            "mean_agencies_per_answer": round(statistics.mean(len(p["agencies"]) for p in ps), 1) if ps else 0,
            "top": [{"name": n, "answers": k, "share": pct(k, len(ps)), "credit_only_answers": sum(1 for p in ps if n in p["credit_only"])}
                    for n, k in sorted(cnt.items(), key=lambda t: (-t[1], t[0]))[:15]],
            "credit_only_mentions": sum(len(p["credit_only"]) for p in ps),
        }
    # how often an answer naming an agency also cites that agency's own website
    own = {}
    for line in open(os.path.join(HERE, "rules", "agency_domains.txt"), encoding="utf-8"):
        line = line.strip()
        if line and not line.startswith("#"):
            n, ds = line.split(" = ")
            own[n] = set(d.strip() for d in ds.split("|"))
    R["agency_own_site_cited"] = {}
    for code in L.ENGINE_ORDER:
        ps = sel(code)
        R["agency_own_site_cited"][code] = []
        for t in R["agencies"][code]["top"][:6]:
            n = t["name"]
            if n not in own:
                continue
            naming = [p for p in ps if n in p["agencies"]]
            k = sum(1 for p in naming if own[n] & set(p["domains"]))
            R["agency_own_site_cited"][code].append({"name": n, "answers_naming": len(naming), "also_cite_own_site": k})
    # per question, overall
    R["agencies_by_question"] = {}
    for qq in L.QUESTION_ORDER:
        ps = [p for p in per if p["question"] == qq]
        cnt = collections.Counter(a for p in ps for a in p["agencies"])
        R["agencies_by_question"][qq] = {"answers": len(ps), "top": [{"name": n, "answers": k, "share": pct(k, len(ps))} for n, k in sorted(cnt.items(), key=lambda t: (-t[1], t[0]))[:5]]}

    # ---- citations
    unknown = collections.Counter()
    R["citations"] = {}
    cit_rows = []
    for r in resp:
        for c in r.get("citations") or []:
            cit_rows.append((r, c, source_type(c, domains, unknown)))
    for code in ["all"] + L.ENGINE_ORDER:
        rows = [(r, c, t) for r, c, t in cit_rows if code == "all" or eng(r) == code]
        ps = sel(code)
        page_ans = collections.defaultdict(set)
        dom_ans = collections.defaultdict(set)
        type_cits = collections.Counter()
        type_pages = collections.defaultdict(set)
        type_ans = collections.defaultdict(set)
        page_title = {}
        for r, c, t in rows:
            u = L.normalise_url(c["url"])
            page_ans[u].add(r["id"])
            page_title.setdefault(u, (c.get("title") or "").strip())
            dom_ans[L.registrable_domain(c["url"])].add(r["id"])
            type_cits[t] += 1
            type_pages[t].add(u)
            type_ans[t].add(r["id"])
        with_c = sum(1 for p in ps if p["n_citations"])
        R["citations"][code] = {
            "answers": len(ps),
            "answers_with_citations": with_c,
            "citations": len(rows),
            "mean_citations_per_citing_answer": round(len(rows) / with_c, 1) if with_c else 0,
            "distinct_pages": len(page_ans),
            "distinct_domains": len(dom_ans),
            "top_pages": [{"url": u, "title": page_title[u], "answers": len(a)} for u, a in sorted(page_ans.items(), key=lambda t: (-len(t[1]), t[0]))[:15]],
            "top_domains": [{"domain": d, "class": domains.get(d, "platform" if d in ("reddit.com", "youtube.com", "linkedin.com") else "unlabelled"), "answers": len(a)} for d, a in sorted(dom_ans.items(), key=lambda t: (-len(t[1]), t[0]))[:15]],
            "source_types": [{"type": t, "label": lab, "citations": type_cits[t], "share_of_citations": pct(type_cits[t], len(rows)),
                              "distinct_pages": len(type_pages[t]), "answers_citing": len(type_ans[t]),
                              "share_of_citing_answers": pct(len(type_ans[t]), with_c)} for t, lab in SOURCE_TYPES],
        }
    R["citations"]["unlabelled_domains"] = dict(unknown)
    page_type = {}
    for r, c, t in cit_rows:
        page_type.setdefault(L.normalise_url(c["url"]), t)
    R["citations"]["top15_pages_by_type"] = dict(collections.Counter(page_type[t["url"]] for t in R["citations"]["all"]["top_pages"][:15]))
    lists = [(r, c) for r, c, t in cit_rows if t in ("agency_list", "independent_list")]
    R["citations"]["list_citations_share_all"] = pct(len(lists), len(cit_rows))
    # StartupCookie's own pages ever cited?
    R["citations"]["startupcookie_pages_cited"] = sorted(set(L.normalise_url(c["url"]) for r, c, t in cit_rows if L.registrable_domain(c["url"]) == SC_DOMAIN))

    # ---- self-ranking warning
    R["warning"] = {}
    for code in ["all"] + L.ENGINE_ORDER:
        ps = sel(code)
        k = sum(1 for p in ps if p["warning"])
        R["warning"][code] = {"answers": len(ps), "warn": k, "share": pct(k, len(ps))}

    # ---- prices
    R["prices"] = {}
    for code in ["all"] + L.ENGINE_ORDER:
        ps = sel(code)
        withp = [p for p in ps if p["amounts"]]
        monthly = [v for p in ps for v, m in p["amounts"] if m]
        other = [v for p in ps for v, m in p["amounts"] if not m]
        R["prices"][code] = {
            "answers": len(ps), "answers_with_price": len(withp), "share": pct(len(withp), len(ps)),
            "amounts_total": len(monthly) + len(other),
            "answers_with_monthly_price": sum(1 for p in ps if any(m for _, m in p["amounts"])),
            "monthly_amounts": {"n": len(monthly), "min": min(monthly) if monthly else None, "p25": _q(monthly, .25),
                                "median": _q(monthly, .5), "p75": _q(monthly, .75), "max": max(monthly) if monthly else None},
            "other_amounts": {"n": len(other), "min": min(other) if other else None, "median": _q(other, .5), "max": max(other) if other else None},
        }

    # ---- background searches (fanouts)
    fan = []
    for path in sorted(glob.glob(FANOUT_GLOB)):
        d = json.load(open(path, encoding="utf-8"))
        for item in d["items"]:
            for f in item["fanouts"]:
                rid = f["response"]["id"]
                if rid in by_id:
                    fan.append({"text": f["text"], "response": rid, "engine": by_id[rid]["engine"], "question": by_id[rid]["question"],
                                "model": FANOUT_MODEL.get(f["response"]["model"], f["response"]["model"])})
    # de-duplicate fanout ids are unique per response; keep as is
    TERMS = [("2026", r"2026"), ("case studies", r"case stud"), ("reviews", r"\breviews?\b"), ("pricing", r"\bpricing\b"),
             ("answer engine optimization", r"answer engine optimi[sz]ation"), ("generative engine optimization", r"generative engine optimi[sz]ation")]
    R["fanouts"] = {}
    for code in ["all"] + L.ENGINE_ORDER:
        fs = [f for f in fan if code == "all" or f["engine"] == code]
        ans_with = len(set(f["response"] for f in fs))
        R["fanouts"][code] = {
            "searches": len(fs), "answers_with_searches": ans_with,
            "answers": len(sel(code)),
            "terms": {t: {"n": sum(1 for f in fs if re.search(rx, f["text"], re.I)), "share": pct(sum(1 for f in fs if re.search(rx, f["text"], re.I)), len(fs))} for t, rx in TERMS},
            "top_searches": collections.Counter(f["text"].lower() for f in fs).most_common(8),
        }

    # ---- StartupCookie
    R["startupcookie"] = {}
    for code in ["all"] + L.ENGINE_ORDER:
        ps = sel(code)
        R["startupcookie"][code] = {"answers": len(ps), "named": sum(p["sc_named"] for p in ps), "named_anywhere_in_text": sum(p["sc_in_raw_text"] for p in ps),
                                    "cited": sum(p["sc_cited"] for p in ps), "promptwatch_flag": sum(p["pw_mentioned_our_brand"] for p in ps)}

    # ---- write
    json.dump(R, open(os.path.join(OUT, "results.json"), "w"), indent=1, ensure_ascii=False)
    with open(os.path.join(OUT, "answers.csv"), "w", newline="", encoding="utf-8") as fh:
        w = csv.writer(fh)
        w.writerow(["response_id", "date_utc", "engine", "question", "agencies_named", "agencies_only_credited_as_source", "n_citations", "self_ranking_warning", "dollar_amounts", "startupcookie_named", "startupcookie_cited"])
        for p in per:
            w.writerow([p["id"], p["date"], p["engine"], p["question"], "; ".join(p["agencies"]), "; ".join(p["credit_only"]), p["n_citations"], " || ".join(p["warning"]),
                        "; ".join(f"{v:g}{'/mo' if m else ''}" for v, m in p["amounts"]), int(p["sc_named"]), int(p["sc_cited"])])
    with open(os.path.join(OUT, "citations.csv"), "w", newline="", encoding="utf-8") as fh:
        w = csv.writer(fh)
        w.writerow(["response_id", "date_utc", "engine", "question", "url", "url_normalised", "domain", "domain_class", "pw_sourceType", "pw_contentType", "study_source_type", "title"])
        for r, c, t in cit_rows:
            dmn = L.registrable_domain(c["url"])
            w.writerow([r["id"], r["createdAt"][:10], eng(r), q(r), c["url"], L.normalise_url(c["url"]), dmn, domains.get(dmn, ""), c.get("sourceType"), c.get("contentType"), t, c.get("title")])
    with open(os.path.join(OUT, "fanouts.csv"), "w", newline="", encoding="utf-8") as fh:
        w = csv.writer(fh)
        w.writerow(["response_id", "engine", "question", "search_text"])
        for f in fan:
            w.writerow([f["response"], f["engine"], f["question"], f["text"]])
    write_tables(R)
    print(json.dumps({k: R[k] for k in ("answers",)}, indent=1)[:1500])
    if unknown:
        print("UNLABELLED DOMAINS:", dict(unknown))


def _q(xs, f):
    if not xs:
        return None
    xs = sorted(xs)
    i = (len(xs) - 1) * f
    lo, hi = int(i), min(int(i) + 1, len(xs) - 1)
    return round(xs[lo] + (xs[hi] - xs[lo]) * (i - lo))


def write_tables(R):
    E = ["all"] + L.ENGINE_ORDER
    lab = dict(L.ENGINE_LABEL, all="All four engines")
    o = [f"# Results, {R['window']['start']} to {R['window']['end']} (UTC)\n"]
    o.append("## Answers\n\n| Engine | Answers | " + " | ".join(L.QUESTION_TEXT[qq] for qq in L.QUESTION_ORDER) + " |\n|---|---|" + "---|" * len(L.QUESTION_ORDER))
    for c in L.ENGINE_ORDER:
        o.append(f"| {lab[c]} | {R['answers']['by_engine'][c]} | " + " | ".join(str(R['answers']['by_engine_question'][c][qq]) for qq in L.QUESTION_ORDER) + " |")
    o.append(f"| Total | {R['answers']['total']} | " + " | ".join(str(R['answers']['by_question'][qq]) for qq in L.QUESTION_ORDER) + " |\n")
    for c in E:
        a = R["agencies"][c]
        o.append(f"## Agencies named: {lab[c]} ({a['answers']} answers; {a['distinct_agencies']} different agencies; {a['answers_naming_any_agency']} answers name at least one)\n\n| # | Agency | Answers | Share |\n|---|---|---|---|")
        for i, t in enumerate(a["top"], 1):
            o.append(f"| {i} | {t['name']} | {t['answers']} | {t['share']}% |")
        o.append("")
    o.append("## Citations\n\n| Engine | Answers with citations | Citations | Distinct pages | Distinct domains |\n|---|---|---|---|---|")
    for c in E:
        x = R["citations"][c]
        o.append(f"| {lab[c]} | {x['answers_with_citations']} of {x['answers']} | {x['citations']} | {x['distinct_pages']} | {x['distinct_domains']} |")
    o.append("")
    for c in E:
        x = R["citations"][c]
        o.append(f"### Source types: {lab[c]}\n\n| Type | Citations | Share of citations | Answers citing | Share of citing answers |\n|---|---|---|---|---|")
        for t in x["source_types"]:
            o.append(f"| {t['label']} | {t['citations']} | {t['share_of_citations']}% | {t['answers_citing']} | {t['share_of_citing_answers']}% |")
        o.append(f"\nTop pages ({lab[c]}):\n")
        for t in x["top_pages"][:10]:
            o.append(f"- {t['answers']} answers: {t['url']} ({t['title']})")
        o.append(f"\nTop domains ({lab[c]}):\n")
        for t in x["top_domains"][:10]:
            o.append(f"- {t['answers']} answers: {t['domain']} [{t['class']}]")
        o.append("")
    o.append("## Self-ranking warning\n\n| Engine | Answers with the warning | Share |\n|---|---|---|")
    for c in E:
        x = R["warning"][c]
        o.append(f"| {lab[c]} | {x['warn']} of {x['answers']} | {x['share']}% |")
    o.append("\n## Background searches\n\n| Engine | Searches | Answers with searches | 2026 | case studies | reviews | pricing | answer engine optimization | generative engine optimization |\n|---|---|---|---|---|---|---|---|---|")
    for c in E:
        x = R["fanouts"][c]
        if not x["searches"]:
            continue
        o.append(f"| {lab[c]} | {x['searches']} | {x['answers_with_searches']} of {x['answers']} | " + " | ".join(f"{v['n']} ({v['share']}%)" for v in x["terms"].values()) + " |")
    o.append("\n## Prices\n\n| Engine | Answers quoting a dollar amount | Answers quoting a monthly amount | Monthly amounts: min / p25 / median / p75 / max |\n|---|---|---|---|")
    for c in E:
        x = R["prices"][c]
        m = x["monthly_amounts"]
        o.append(f"| {lab[c]} | {x['answers_with_price']} of {x['answers']} ({x['share']}%) | {x['answers_with_monthly_price']} | {m['min']} / {m['p25']} / {m['median']} / {m['p75']} / {m['max']} (n={m['n']}) |")
    o.append("\n## StartupCookie\n\n| Engine | Answers | Name StartupCookie | Cite startupcookie.com |\n|---|---|---|---|")
    for c in E:
        x = R["startupcookie"][c]
        o.append(f"| {lab[c]} | {x['answers']} | {x['named']} | {x['cited']} |")
    open(os.path.join(OUT, "tables.md"), "w", encoding="utf-8").write("\n".join(o) + "\n")


if __name__ == "__main__":
    main()
