"""Article de l'édition 2 : chaque chiffre, tableau et figure est tiré des fichiers de résultats, rien n'est tapé à la main. 0 $.

    PYTHONPATH=. .venv/bin/python ops/etude/v2/publication/construire.py

Avant : analyse_phase_a.py, puis analyse_phase_a_suite.py sans option, puis avec --h5, --faux-noms et --large (dans cet ordre :
la première réécrit le fichier, les trois autres y ajoutent leur clé ; --large relit audit/large/lecture.csv).

Lit : resultats_phase_a.json (tests déposés), resultats_phase_a_suite.json (solidité, descriptifs), audit/accord.json (double
lecture), controle_pages/comparaison.json (50 pages), presse/chiffres.json, donnees/ (compléments descriptifs recalculés ici).
Écrit : valeurs.json (chaque valeur de l'article avec sa source), figures/fig1.svg à fig4.svg (et leurs versions étroites pour le téléphone dans figures_narrow/), article_edition2.md (le gabarit
article.gabarit.md dont les {{clés}} sont remplacées). Une clé inconnue arrête le script : aucun chiffre ne peut rester à la main
dans une {{clé}}. Le script liste aussi les nombres écrits en dur dans le gabarit (constantes de protocole) pour relecture.
"""
import collections
import csv
import json
import re
import sys
from decimal import ROUND_HALF_UP, Decimal
from pathlib import Path

HERE = Path(__file__).parent
V2 = HERE.parent
# Édition 1 : la version en ligne depuis le 21/11 (page et fichier téléchargeable), et la mise à jour jamais mise en ligne
E1_PUBLISHED = V2.parent.parent.parent / "apps" / "web" / "public" / "study" / "ai-local-search-2026-11" / "listings_anonymized.csv"
E1_PAGE = V2.parent.parent.parent / "apps" / "web" / "lib" / "ai-local-search-2026-11.json"
E1_UPDATE = V2.parent / "public" / "listings_anonymized.csv"
E1_UPDATE_RESULTS = V2.parent / "resultats_v1.json"
sys.path.insert(0, str(V2.parent))
sys.path.insert(0, str(V2))
sys.path.insert(0, str(HERE))
import analyse_phase_a as A  # noqa: E402
import numpy as np  # noqa: E402
import pandas as pd  # noqa: E402
from scipy import stats  # noqa: E402
from fichiers import PUBLIC, zenodo_doi  # noqa: E402

R = json.loads((V2 / "resultats_phase_a.json").read_text())
S = json.loads((V2 / "resultats_phase_a_suite.json").read_text())
ACC = json.loads((V2 / "audit" / "accord.json").read_text())
PAGES = json.loads((V2 / "controle_pages" / "comparaison.json").read_text())
PRESS = json.loads((HERE.parent / "presse" / "chiffres.json").read_text())
MAN = json.loads((V2 / "donnees" / "MANIFEST.json").read_text())

VAL: dict[str, dict] = {}
F_R, F_S = "resultats_phase_a.json", "resultats_phase_a_suite.json"
ENG = [("chatgpt", "ChatGPT"), ("gemini", "Gemini"), ("perplexity", "Perplexity"), ("claude", "Claude")]
TRADE = {"dentist": "Dentists", "personal-injury-lawyer": "Personal injury lawyers", "med-spa": "Med spas", "plumber": "Plumbers",
         "hvac-contractor": "HVAC contractors", "roofer": "Roofers", "veterinarian": "Veterinarians",
         "chiropractor": "Chiropractors", "real-estate-agent": "Real estate agents", "auto-repair-shop": "Auto repair shops"}


def put(key: str, value, source: str) -> str:
    VAL[key] = {"value": str(value), "source": source}
    return str(value)


def n0(x) -> str:
    return f"{int(round(x)):,}"


def f1(x, d: int = 1) -> str:
    """Arrondi décimal « au plus proche, demi vers le haut » (pas d'artefact binaire : 8.35 -> 8.4), signe moins typographique."""
    q = Decimal(str(float(x))).quantize(Decimal(1).scaleb(-d), rounding=ROUND_HALF_UP)
    if q == 0:
        q = abs(q)
    return str(q).replace("-", "−")


def sg(x, d: int = 1) -> str:
    """Un effet avec son signe (0.0 sans signe)."""
    a = f1(abs(x), d)
    return a if float(a) == 0 else ("+" if x >= 0 else "−") + a


def pc(x, d: int = 1) -> str:
    return f1(100 * x, d) + "%"


def rng(lo, hi, d: int = 1) -> str:
    return f"{f1(lo, d)} to {f1(hi, d)}"


def pval(p: float) -> str:
    return "< 0.001" if p < 0.001 else f"{p:.2f}" if p >= 0.0995 else f"{p:.3f}"


# ---------------------------------------------------------------- compléments descriptifs, recalculés sur les données figées
def extras() -> dict:
    a, m, f = A.load()
    x: dict = {}
    per = m.groupby("scan_id").size().reindex(a.scan_id, fill_value=0)
    a = a.assign(n=per.values)
    x["answers_by_engine"] = {e: int((a.engine == e).sum()) for e, _ in ENG}
    x["names_per_answer"] = {e: float(a[a.engine == e].n.mean()) for e, _ in ENG}
    x["names_per_answer_all"] = float(a.n.mean())
    x["answers_naming_none"] = {e: float((a[a.engine == e].n == 0).mean()) for e, _ in ENG}
    x["models"] = {e: sorted(set(a[a.engine == e].model))[0] for e, _ in ENG}
    x["answers_first"], x["answers_last"] = str(a.created_at.min())[:16], str(a.created_at.max())[:16]
    x["lists_first"], x["lists_last"] = str(f.collected_at.min())[:16], str(f.collected_at.max())[:16]
    # quarts du nombre d'avis dans le marché : même découpage que analyse_phase_a_suite.descriptives (marchés d'au moins 8 fiches),
    # pour donner l'effectif de chaque quart au tableau 3 ; les parts doivent retomber sur celles du fichier de résultats
    rq = f.groupby("market").reviews_count.transform(lambda s: pd.qcut(s.fillna(0).rank(method="first"), 4, labels=False)
                                                     if len(s) >= 8 else float("nan"))
    g = f.assign(rq=rq).dropna(subset=["rq"]).groupby("rq").named.agg(["size", "mean"])
    pub = S["descriptives"]["named_share_by_review_quartile_within_market"]
    assert all(round(float(g.loc[int(k), "mean"]), 4) == v for k, v in pub.items()), "quarts d'avis : parts différentes du fichier de résultats"
    x["review_quarters"] = {"n": [int(g.loc[i, "size"]) for i in range(4)], "left_out": int(rq.isna().sum()),
                            "small_markets": int((f.groupby("market").size() < 8).sum())}
    size = f.groupby("market").size()
    x["listings_per_market"] = {"min": int(size.min()), "median": float(size.median()), "max": int(size.max()),
                                "at_cap_100": int((size >= 100).sum()), "under_10": int((size < 10).sum())}
    x["rated"] = int(f.rating.notna().sum())
    hi, five = f[(f.rating >= 4.5) & (f.rating <= 4.9)], f[f.rating == 5.0]
    x["rating_5_vs_45_49"] = {"r45_49": {"n": int(len(hi)), "named_share": float(hi.named.mean()), "median_reviews": float(hi.reviews_count.median())},
                              "r50": {"n": int(len(five)), "named_share": float(five.named.mean()), "median_reviews": float(five.reviews_count.median())}}
    # Édition 1 (correction du 26/11, relevée par la session de la page) : le fichier PUBLIÉ est celui de la page en ligne depuis
    # le 21/11 (36 marchés dans le modèle des avis). ops/etude/public/listings_anonymized.csv est la mise à jour préparée le
    # 21/11 à 16 h 42 (branche etude-v1-2111, commit 0f49b8ec, 77 marchés) et jamais mise en ligne : elle n'est citée que comme telle.
    e1 = pd.read_csv(E1_PUBLISHED)
    e1 = e1[e1.rating.notna()]
    h1, f1_ = e1[(e1.rating >= 4.5) & (e1.rating <= 4.9)], e1[e1.rating == 5.0]
    x["edition1_rating_5_vs_45_49"] = {"r45_49": {"n": int(len(h1)), "named_share": float(h1.named.mean())},
                                       "r50": {"n": int(len(f1_)), "named_share": float(f1_.named.mean())}}
    x["states"] = int(a.state.nunique())
    # couverture : parmi les commerces nommés (après fusion des graphies), combien se rattachent à une fiche Google Maps
    place = a.drop_duplicates("market").set_index("market")[["city", "state"]]
    ents = matched = ment = ment_matched = 0
    for mk, lst in f.groupby("market"):
        grp = m[m.market == mk]
        st = place.loc[mk, "state"]
        name_id, pid_id, _ = A.resolve_market(sorted(set(grp.business_name)), list(zip(lst.place_id, lst.name.fillna(""))),
                                              place.loc[mk, "city"], st if isinstance(st, str) else None,
                                              grp.business_name.value_counts().to_dict())
        on_list = set(pid_id.values())
        named = {name_id[n] for n in grp.business_name}
        ents += len(named)
        matched += len(named & on_list)
        ment += len(grp)
        ment_matched += sum(name_id[n] in on_list for n in grp.business_name)
    x["coverage"] = {"named_businesses": ents, "on_our_lists": matched, "share": matched / ents, "mentions": ment,
                     "mentions_on_lists": ment_matched, "mentions_share": ment_matched / ment}
    qs: dict[str, set] = {}
    for q, c, stt, cat in zip(a["query"], a["city"], a["state"], a["category"]):
        q2 = q.replace(c, "[city]")
        if isinstance(stt, str):
            q2 = re.sub(r"\b" + re.escape(stt) + r"\b", "[state]", q2)
        qs.setdefault(cat, set()).add(q2)
    x["questions"] = {k: sorted(v) for k, v in qs.items()}
    # ---- ajouts de la relecture du 23/11 (deux relecteurs indépendants) : aucun ne change un résultat déposé
    # marchés sortis de chacun des trois modèles (un marché où aucune fiche, ou toute fiche, est nommée n'apporte rien)
    f3 = f[(f["reachable"] == True) & (f["empty"] == False)].copy()  # noqa: E712
    for c in ("schema_org", "content_ok", "nap_consistent", "links_yelp", "links_healthgrades"):
        f3[c] = f3[c].astype(float)
    f3 = f3.dropna(subset=["schema_org", "content_ok", "nap_consistent"])
    rated = f[f.rating.notna()]

    def dropped(d):
        sh = d.groupby("market").named.mean()
        keep = sh[(sh > 0) & (sh < 1)].index
        return {"markets_in": int(len(keep)), "markets_out": int(len(sh) - len(keep)), "none_named": int((sh == 0).sum()),
                "all_named": int((sh == 1).sum()), "listings_in": int(d.market.isin(keep).sum())}
    x["models_dropped"] = {"M1": dropped(f), "M2": dropped(rated), "M3": dropped(f3)}

    # position de la fiche dans les résultats Google Maps (champ `rank` du fournisseur) : absente de l'article jusqu'au 23/11.
    # Descriptif, puis les trois modèles déposés avec log2(position) en plus : exploratoire, hors dépôt.
    def fit_ames(d, rhs, tests):
        res, dd = A.fe_logit(d, rhs)
        out = {}
        for key, var, binary in tests:
            t = A.two_sided(*A.ame(res, dd, var, binary))
            out[key] = {"ame_pts": 100 * t["est"], "lo": 100 * t["lo"], "hi": 100 * t["hi"], "n": int(len(dd))}
        return out
    lrank = lambda d: d.assign(lrank=np.log2(d["rank"].astype(float)))  # noqa: E731
    top, rest, dup = f[f["rank"] <= 20], f[f["rank"] > 20], f.groupby(["market", "rank"]).size()
    x["position"] = {"listings": int(len(f)), "max": int(f["rank"].max()), "missing": int(f["rank"].isna().sum()),
                     "top20": {"n": int(len(top)), "named": int(top.named.sum()), "named_share": float(top.named.mean())},
                     "beyond20": {"n": int(len(rest)), "named_share": float(rest.named.mean())},
                     "shared_positions": int((dup > 1).sum()), "positions": int(len(dup)),
                     **fit_ames(lrank(f), "lr + web + lrank", [("H1_reviews_per_doubling", "lr", False), ("H3_website", "web", True),
                                                               ("position_per_doubling", "lrank", False)]),
                     **fit_ames(lrank(rated), "lr + rating + web + lrank", [("H2_rating_per_star", "rating", False)]),
                     **fit_ames(lrank(f3), "lr + schema_org + content_ok + nap_consistent + lrank",
                                [("H4_schema", "schema_org", True), ("H5_content", "content_ok", True), ("H8_nap", "nap_consistent", True)])}

    # fiches avec un site : ce qui a été lu, et ce qui ne l'a pas été
    w = f[f.web == 1]
    read = (w["reachable"] == True) & (w["empty"] == False)  # noqa: E712
    stt = w.status.fillna("non lu").str.split(":").str[0]
    x["site_reading"] = {"with_website": int(len(w)), "read": int(read.sum()), "not_read": int((~read).sum()),
                         "named_share_read": float(w[read].named.mean()), "named_share_not_read": float(w[~read].named.mean()),
                         "error": int((stt == "error").sum()), "robots": int((stt == "robots").sum()), "social": int((stt == "social").sum()),
                         "not_fetched": int((stt == "non lu").sum()), "fetched_unreadable_or_empty": int(((stt == "http") & ~read).sum())}
    x["h6_counts"] = {"pages": int(len(f3)), "yelp": int(f3.links_yelp.sum()), "dentist_pages": int((f3.trade == "dentist").sum()),
                      "healthgrades_dentists": int(f3[f3.trade == "dentist"].links_healthgrades.sum())}

    # part nommée par note affichée, sans double arrondi (figure 2)
    byr = f[f.rating.notna()].assign(r=lambda d: d.rating.round(1)).groupby("r").named.agg(["size", "sum"])
    x["named_by_rating_exact"] = {f"{r:.1f}": {"n": int(v["size"]), "named": int(v["sum"])} for r, v in byr.iterrows()}

    # édition 1 : le modèle de la note (H2) de l'édition 2 sur le fichier publié de l'édition 1. Ce fichier n'a pas la ville :
    # l'erreur type n'est pas comparable, seule l'estimation est citée.
    for key, path in (("edition1_model", E1_PUBLISHED), ("edition1_update_model", E1_UPDATE)):
        e1a = pd.read_csv(path)
        e1m = e1a[e1a.rating.notna()].assign(lr=lambda d: np.log2(1 + d.reviews_count.fillna(0)), web=lambda d: d.has_website.astype(int),
                                             market=lambda d: d.market_id.astype(str), city_slug=lambda d: d.market_id.astype(str))
        res1, d1 = A.fe_logit(e1m, "lr + rating + web")
        x[key] = {"rating_ame_pts": 100 * A.ame(res1, d1, "rating", False)[0], "n": int(len(d1)), "markets": int(d1.market.nunique()),
                  "dentist_share": float((e1a.trade == "dentist").mean()), "named_share": float(e1a.named.mean()),
                  "rated_share": float(e1a.rating.notna().mean())}
    page = json.loads(E1_PAGE.read_text())["reviews"]                    # ce que la page en ligne affiche
    x["edition1_page"] = {"or": page["or_doubling"]["rating"], "markets": page["markets"], "model_listings": page["model_listings"],
                          "cities": page["auc_rating"]["cities"]}
    x["edition1_update_cities"] = json.loads(E1_UPDATE_RESULTS.read_text())["correlates"]["conditional_logit_per_doubling_of_reviews"]["n_cities"]

    # premier tirage des 60 rattachements (annexe B, point 4)
    lab1 = [r["label"] for r in csv.DictReader((V2 / "audit" / "tirage1" / "lecteur1.csv").open(encoding="utf-8")) if r["kind"] == "match"]
    x["first_draw_matches"] = {"n": len(lab1), "right": lab1.count("oui"), "wrong": lab1.count("non"), "undecided": lab1.count("nsp")}
    x["listings_all_200_markets"] = MAN["files"]["fiches.csv.gz"]["rows"]
    x["answers_all_200_markets"] = MAN["files"]["reponses.csv.gz"]["rows"]
    return x


# ---------------------------------------------------------------- figures (SVG simples, sans dépendance)
INK, MUTE, BAR, GRID = "#111827", "#6b7280", "#1f4fd8", "#e5e7eb"
FONT = 'font-family="Inter, system-ui, -apple-system, Segoe UI, Helvetica, Arial, sans-serif"'


def svg_bars(path: Path, title: str, rows: list[tuple[str, float, str]], ymax: float, ylabel: str):
    """Barres verticales : (étiquette, valeur en %, note sous l'étiquette)."""
    # le bas ne garde que ce que les étiquettes demandent (revue design de la page, 23/11 : sans note sous les barres, une
    # ligne de textes vides laissait une bande blanche) ; la hauteur du tracé ne change pas
    notes = any(n for _, _, n in rows)
    w, left, top, ph = 720, 56, 54, 262
    bottom = 64 if notes else 48
    h = top + ph + bottom
    pw = w - left - 24
    step = pw / len(rows)
    bw = min(64, step * 0.62)
    o = [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {w} {h}" role="img" aria-label="{title}" {FONT}>',
         f'<rect width="{w}" height="{h}" fill="#ffffff"/>', f'<text x="20" y="28" font-size="16" font-weight="600" fill="{INK}">{title}</text>']
    ticks = [t for t in range(0, int(ymax) + 1, 10)]
    for t in ticks:
        y = top + ph * (1 - t / ymax)
        o.append(f'<line x1="{left}" y1="{y:.1f}" x2="{w - 24}" y2="{y:.1f}" stroke="{GRID}"/>')
        o.append(f'<text x="{left - 8}" y="{y + 4:.1f}" font-size="12" text-anchor="end" fill="{MUTE}">{t}%</text>')
    o.append(f'<text x="14" y="{top + ph / 2:.0f}" font-size="12" fill="{MUTE}" transform="rotate(-90 14 {top + ph / 2:.0f})" text-anchor="middle">{ylabel}</text>')
    for i, (lab, v, note) in enumerate(rows):
        cx = left + step * (i + 0.5)
        bh = ph * v / ymax
        o.append(f'<rect x="{cx - bw / 2:.1f}" y="{top + ph - bh:.1f}" width="{bw:.1f}" height="{bh:.1f}" rx="3" fill="{BAR}"/>')
        o.append(f'<text x="{cx:.1f}" y="{top + ph - bh - 6:.1f}" font-size="12" font-weight="600" text-anchor="middle" fill="{INK}">{v:.1f}%</text>')
        o.append(f'<text x="{cx:.1f}" y="{top + ph + 20}" font-size="12" text-anchor="middle" fill="{INK}">{lab}</text>')
        if note:
            o.append(f'<text x="{cx:.1f}" y="{top + ph + 38}" font-size="11" text-anchor="middle" fill="{MUTE}">{note}</text>')
    o.append("</svg>")
    path.write_text("\n".join(o) + "\n")


def svg_forest(path: Path, title: str, rows: list[tuple[str, float, float, float]], xmin: float, xmax: float, xlabel: str,
               band: float | None = None):
    """Estimations avec intervalle : (étiquette, estimation, borne basse, borne haute), en points."""
    w, left, top, rh = 720, 250, 58, 30
    h = top + rh * len(rows) + 62
    pw = w - left - 60

    def X(v):
        return left + pw * (v - xmin) / (xmax - xmin)
    o = [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {w} {h}" role="img" aria-label="{title}" {FONT}>',
         f'<rect width="{w}" height="{h}" fill="#ffffff"/>', f'<text x="20" y="28" font-size="16" font-weight="600" fill="{INK}">{title}</text>']
    base = top + rh * len(rows)
    if band:
        o.append(f'<rect x="{X(-band):.1f}" y="{top - 8}" width="{X(band) - X(-band):.1f}" height="{base - top + 8}" fill="#f3f4f6"/>')
    step = 5 if xmax - xmin <= 45 else 10
    t = int(xmin // step * step)
    while t <= xmax:
        if t >= xmin:
            o.append(f'<line x1="{X(t):.1f}" y1="{top - 8}" x2="{X(t):.1f}" y2="{base}" stroke="{GRID if t else MUTE}"/>')
            o.append(f'<text x="{X(t):.1f}" y="{base + 18}" font-size="12" text-anchor="middle" fill="{MUTE}">{"0" if t == 0 else f"{t:+d}".replace("-", "−")}</text>')
        t += step
    o.append(f'<text x="{left + pw / 2:.0f}" y="{base + 42}" font-size="12" text-anchor="middle" fill="{MUTE}">{xlabel}</text>')
    for i, (lab, est, lo, hi) in enumerate(rows):
        y = top + rh * i + rh / 2
        o.append(f'<text x="{left - 14}" y="{y + 4:.1f}" font-size="13" text-anchor="end" fill="{INK}">{lab}</text>')
        o.append(f'<line x1="{X(max(lo, xmin)):.1f}" y1="{y:.1f}" x2="{X(min(hi, xmax)):.1f}" y2="{y:.1f}" stroke="{BAR}" stroke-width="2.5"/>')
        o.append(f'<circle cx="{X(est):.1f}" cy="{y:.1f}" r="5" fill="{BAR}"/>')
        o.append(f'<text x="{w - 8}" y="{y + 4:.1f}" font-size="12" text-anchor="end" fill="{INK}">{sg(est)}</text>')
    o.append("</svg>")
    path.write_text("\n".join(o) + "\n")


# ---------------------------------------------------------------- figures étroites (téléphone)
# Les mêmes chiffres, redessinés pour un écran étroit : 328 unités de large, aucun texte sous 13 unités. Affichée sur 280 px ou
# plus (un téléphone de 320 px avec ses marges et un cadre), chaque étiquette fait donc au moins 11 px à l'écran. Les barres passent à
# l'horizontale (11 notes ne tiennent pas côte à côte) et chaque intervalle a son étiquette sur la ligne du dessus.
NW, NPAD, NFS, NTITLE = 328, 12, 13, 15
TNUM = 'style="font-variant-numeric:tabular-nums"'   # les colonnes de chiffres alignées à droite


def wrap2(text: str, limit: int) -> list[str]:
    """Une ou deux lignes : coupe après une virgule ou deux-points, ou avant une parenthèse, sinon au plus équilibré."""
    if len(text) <= limit:
        return [text]
    cuts = [m.end() for m in re.finditer(r"[,:] ", text)] + [m.start() + 1 for m in re.finditer(r" \(", text)]
    ok = [c for c in cuts if len(text[:c].strip()) <= limit and len(text[c:].strip()) <= limit]
    if not ok:
        ok = [m.end() for m in re.finditer(" ", text) if len(text[:m.end()].strip()) <= limit and len(text[m.end():]) <= limit]
    assert ok, f"« {text} » ne tient pas sur deux lignes de {limit} caractères"
    c = min(ok, key=lambda k: abs(len(text[:k].strip()) - len(text[k:].strip())))
    return [text[:c].strip(), text[c:].strip()]


def narrow_head(title: str, h: int) -> tuple[list[str], int]:
    lines = wrap2(title, 36)
    o = [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {NW} {h}" role="img" aria-label="{title}" {FONT}>',
         f'<rect width="{NW}" height="{h}" fill="#ffffff"/>']
    for i, ln in enumerate(lines):
        o.append(f'<text x="{NPAD}" y="{26 + 20 * i}" font-size="{NTITLE}" font-weight="600" fill="{INK}">{ln}</text>')
    return o, 26 + 20 * (len(lines) - 1)


def narrow_write(path: Path, o: list[str]):
    sizes = [float(x) for x in re.findall(r'font-size="([0-9.]+)"', "\n".join(o))]
    assert min(sizes) >= NFS, f"{path.name} : un texte sous {NFS} unités"
    path.write_text("\n".join(o + ["</svg>"]) + "\n")


def svg_bars_narrow(path: Path, title: str, rows: list[tuple[str, float, str]], xmax: float, xlabel: str, label_w: int):
    """Barres horizontales : (étiquette, valeur en %, note à droite). label_w : la largeur gardée pour l'étiquette."""
    notes = any(n for _, _, n in rows)
    rh, bh = (30, 16) if len(rows) > 6 else (36, 18)
    nlines = len(wrap2(title, 36))
    top = 26 + 20 * (nlines - 1) + 24
    base = top + rh * len(rows)
    h = base + 58
    left = NPAD + label_w + 8
    # la valeur au bout de la barre, puis la note alignée à droite : le tracé prend toute la place que la plus longue barre et
    # sa valeur laissent (revue design du 23/11 : les graduations étaient trop serrées)
    room = NW - left - NPAD - (66 if notes else 0)
    need = lambda v: 6 + 8.7 * len(f"{v:.1f}%")  # noqa: E731
    pw = int(min(room - (30 if notes else 15), min((room - need(v)) * xmax / v for _, v, _ in rows if v > 0)))
    o, _ = narrow_head(title, h)
    for t in range(0, int(xmax) + 1, 10):
        x = left + pw * t / xmax
        o.append(f'<line x1="{x:.1f}" y1="{top - 4}" x2="{x:.1f}" y2="{base}" stroke="{GRID if t else MUTE}"/>')
        o.append(f'<text x="{x:.1f}" y="{base + 18}" font-size="{NFS}" text-anchor="middle" fill="{MUTE}">{t}%</text>')
    o.append(f'<text x="{left + pw / 2:.0f}" y="{base + 42}" font-size="{NFS}" text-anchor="middle" fill="{MUTE}">{xlabel}</text>')
    for i, (lab, v, note) in enumerate(rows):
        y = top + rh * i + rh / 2
        bl = pw * v / xmax
        o.append(f'<text x="{NPAD}" y="{y + 4.5:.1f}" font-size="{NFS}" fill="{INK}">{lab}</text>')
        o.append(f'<rect x="{left}" y="{y - bh / 2:.1f}" width="{bl:.1f}" height="{bh}" rx="3" fill="{BAR}"/>')
        o.append(f'<text x="{left + bl + 6:.1f}" y="{y + 4.5:.1f}" font-size="{NFS}" font-weight="600" fill="{INK}">{v:.1f}%</text>')
        if note:
            o.append(f'<text x="{NW - NPAD}" y="{y + 4.5:.1f}" font-size="{NFS}" text-anchor="end" fill="{MUTE}" {TNUM}>{note}</text>')
    narrow_write(path, o)


def svg_forest_narrow(path: Path, title: str, rows: list[tuple[str, float, float, float]], xmin: float, xmax: float, xlabel: str,
                      band: float | None = None):
    """Estimations avec intervalle : l'étiquette et l'estimation sur une ligne, l'intervalle sur la ligne du dessous."""
    rh, left, right = 46, 21, 25
    pw = NW - left - right
    nlines = len(wrap2(title, 36))
    top = 26 + 20 * (nlines - 1) + 20
    base = top + rh * len(rows)
    xl = wrap2(xlabel, 45)
    h = base + 30 + 20 * len(xl) + 12

    def X(v):
        return left + pw * (v - xmin) / (xmax - xmin)
    step = 5 if xmax - xmin <= 45 else 10
    ticks = [t for t in range(int(xmin // step * step), int(xmax) + 1, step) if t >= xmin]
    o, _ = narrow_head(title, h)
    for i, (lab, est, lo, hi) in enumerate(rows):
        y0 = top + rh * i
        y = y0 + 29   # 7 unités sous son étiquette, 15,5 au-dessus de la suivante : l'intervalle tient à sa ligne
        o.append(f'<text x="{NPAD}" y="{y0 + 15}" font-size="{NFS}" fill="{INK}">{lab}</text>')
        o.append(f'<text x="{NW - NPAD}" y="{y0 + 15}" font-size="{NFS}" font-weight="600" text-anchor="end" fill="{INK}" {TNUM}>{sg(est)}</text>')
        if band:
            o.append(f'<rect x="{X(-band):.1f}" y="{y - 7}" width="{X(band) - X(-band):.1f}" height="14" fill="{GRID}"/>')
        for t in ticks:
            o.append(f'<line x1="{X(t):.1f}" y1="{y - 7}" x2="{X(t):.1f}" y2="{y + 7}" stroke="{GRID if t else MUTE}"/>')
        o.append(f'<line x1="{X(max(lo, xmin)):.1f}" y1="{y}" x2="{X(min(hi, xmax)):.1f}" y2="{y}" stroke="{BAR}" stroke-width="3"/>')
        o.append(f'<circle cx="{X(est):.1f}" cy="{y}" r="5.5" fill="{BAR}"/>')
    for t in ticks:
        o.append(f'<text x="{X(t):.1f}" y="{base + 18}" font-size="{NFS}" text-anchor="middle" fill="{MUTE}">{"0" if t == 0 else f"{t:+d}".replace("-", "−")}</text>')
    for i, ln in enumerate(xl):
        o.append(f'<text x="{left + pw / 2:.0f}" y="{base + 42 + 20 * i}" font-size="{NFS}" text-anchor="middle" fill="{MUTE}">{ln}</text>')
    narrow_write(path, o)


# ---------------------------------------------------------------- tableaux
def table(head: list[str], rows: list[list[str]]) -> str:
    out = ["| " + " | ".join(head) + " |", "|" + "|".join(["---"] * len(head)) + "|"]
    out += ["| " + " | ".join(str(c) for c in r) + " |" for r in rows]
    return "\n".join(out)


def eff(d: dict, key: str) -> str:
    e = d[key]
    return f"{sg(e['ame_pts'])} ({rng(e['lo'], e['hi'])})"


HKEYS = [("H1_reviews_per_doubling", "H1 reviews, per doubling"), ("H2_rating_per_star", "H2 rating, per star"),
         ("H3_website", "H3 website"), ("H4_schema", "H4 schema markup"), ("H5_content", "H5 home page content"),
         ("H8_nap", "H8 name, address, phone")]


def main():
    X = extras()
    D = S["descriptives"]
    fig = HERE / "figures"
    fig.mkdir(exist_ok=True)

    # ---- noms des fichiers cités dans l'article : les noms publics du dossier téléchargeable (publication/fichiers.py)
    for k, v in {"R": "resultats_phase_a.json", "S": "resultats_phase_a_suite.json", "ACC": "audit/accord.json", "READ": "donnees/lectures_260.csv",
                 "PAGES": "controle_pages/comparaison.json", "ANS": "donnees/reponses.csv.gz", "MEN": "donnees/mentions.csv.gz",
                 "LIST": "donnees/fiches.csv.gz", "VAL": "publication/valeurs.json", "CODE1": "analyse_phase_a.py",
                 "CODE2": "analyse_phase_a_suite.py", "BUILD": "publication/construire.py", "DEV": "ecarts_phase_a.md", "LOOSE": "audit/large/",
                 "PREREG": "preregistration.md", "DRAW": "tirage_villes.py", "DEFS": "definitions_sites.md", "MARKETS": "marches_phase_a.csv",
                 "AUDIT": "audit/protocole_ajouts.md", "PAGEDIR": "controle_pages/protocole.md", "PAGERES": "controle_pages/resultat.md",
                 "DRAW1": "audit/tirage1/lecteur1.csv", "H7V0": "resultats_phase_a_v0_bug_h7.json", "POWER": "puissance.py", "PRESS": "presse/chiffres.json",
                 "PRESSPY": "presse/chiffres.py", "MANIFEST": "donnees/MANIFEST.json", "REPRO": "publication/reproduce.py",
                 "LOOSEPROT": "audit/large/protocole.md", "E1U": "../public/listings_anonymized.csv"}.items():
        VAL[f"file:{k}"] = {"value": f"`{PUBLIC[v]}`", "source": v}

    # ---- DOI Zenodo : la phrase n'existe que si le DOI est réservé (publication/doi.txt)
    doi = zenodo_doi()
    VAL["text:zenodo"] = {"value": f" The same folder is archived on Zenodo (https://doi.org/{doi})." if doi else "", "source": "publication/doi.txt"}

    # ---- échantillon
    put("markets_drawn", MAN["markets"], "donnees/MANIFEST.json: markets")
    put("markets", R["sample"]["markets_complete"], f"{F_R}: sample.markets_complete")
    put("markets_excluded", MAN["markets"] - R["sample"]["markets_complete"], "donnees/MANIFEST.json: incomplete")
    put("cities", R["sample"]["cities"], f"{F_R}: sample.cities")
    put("states", X["states"], "donnees/reponses.csv.gz: state")
    put("answers", n0(R["sample"]["answers"]), f"{F_R}: sample.answers")
    put("answers_all", n0(X["answers_all_200_markets"]), "donnees/MANIFEST.json: files.reponses.csv.gz.rows")
    put("listings", n0(R["sample"]["listings"]), f"{F_R}: sample.listings")
    put("listings_all", n0(X["listings_all_200_markets"]), "donnees/MANIFEST.json: files.fiches.csv.gz.rows")
    put("named", n0(R["sample"]["named"]), f"{F_R}: sample.named")
    put("named_pct", pc(R["sample"]["named_share"]), f"{F_R}: sample.named_share")
    put("never_pct", pc(1 - R["sample"]["named_share"]), f"{F_R}: sample.named_share")
    put("never_pct0", pc(1 - R["sample"]["named_share"], 0), f"{F_R}: sample.named_share")
    put("answers_first", X["answers_first"][11:], "donnees/reponses.csv.gz: created_at")
    put("answers_last", X["answers_last"][11:], "donnees/reponses.csv.gz: created_at")
    put("lists_first", X["lists_first"][11:], "donnees/fiches.csv.gz: collected_at")
    put("lists_last", X["lists_last"][11:], "donnees/fiches.csv.gz: collected_at")
    lm = X["listings_per_market"]
    put("lm_min", lm["min"], "donnees/fiches.csv.gz")
    put("lm_median", f1(lm["median"], 0), "donnees/fiches.csv.gz")
    put("lm_cap", lm["at_cap_100"], "donnees/fiches.csv.gz")
    put("lm_under10", lm["under_10"], "donnees/fiches.csv.gz")
    put("rated", n0(X["rated"]), "donnees/fiches.csv.gz: rating")
    put("unrated", n0(D["named_share_no_rating"]["n"]), f"{F_S}: descriptives.named_share_no_rating")
    put("unrated_named", pc(D["named_share_no_rating"]["named_share"]), f"{F_S}: descriptives.named_share_no_rating")
    st = D["site_status"]
    put("with_site", n0(st["with_website"]), f"{F_S}: descriptives.site_status")
    put("no_site", n0(D["named_share_by_website"]["0"]["n"]), f"{F_S}: descriptives.named_share_by_website")
    put("pages_read", n0(st["reachable_not_empty"]), f"{F_S}: descriptives.site_status")
    put("site_error", n0(st["status_counts"]["error"]), f"{F_S}: descriptives.site_status.status_counts")
    put("site_robots", n0(st["status_counts"]["robots"]), f"{F_S}: descriptives.site_status.status_counts")
    put("site_social", n0(st["status_counts"]["social"]), f"{F_S}: descriptives.site_status.status_counts")
    cv = X["coverage"]
    put("cov_named", n0(cv["named_businesses"]), "construire.py: extras().coverage (donnees/mentions.csv.gz, fiches.csv.gz)")
    put("cov_on_lists", n0(cv["on_our_lists"]), "construire.py: extras().coverage")
    put("cov_share", pc(cv["share"], 0), "construire.py: extras().coverage")
    put("cov_mentions", n0(cv["mentions"]), "construire.py: extras().coverage")
    put("cov_mentions_share", pc(cv["mentions_share"], 0), "construire.py: extras().coverage")
    put("names_per_answer", f1(X["names_per_answer_all"]), "construire.py: extras().names_per_answer_all")

    # ---- concentration et accord entre assistants
    k = {int(i): v for i, v in D["named_by_k_assistants"].items()}
    tot_named = sum(v for i, v in k.items() if i > 0)
    put("top3_share", pc(D["top3_share_of_namings"], 0), f"{F_S}: descriptives.top3_share_of_namings")
    put("median_named_per_market", f1(D["median_listings_named_per_market"], 0), f"{F_S}: descriptives.median_listings_named_per_market")
    put("markets_none_named", D["markets_with_no_listing_named"], f"{F_S}: descriptives.markets_with_no_listing_named")
    put("named_once_pct", pc(D["answers_naming_among_named"]["share_named_once"], 0), f"{F_S}: descriptives.answers_naming_among_named")
    put("named_5plus_pct", pc(D["answers_naming_among_named"]["share_named_5plus"], 0), f"{F_S}: descriptives.answers_naming_among_named")
    put("by1", n0(k[1]), f"{F_S}: descriptives.named_by_k_assistants")
    put("by4", n0(k[4]), f"{F_S}: descriptives.named_by_k_assistants")
    put("by1_pct", pc(k[1] / tot_named, 0), f"{F_S}: descriptives.named_by_k_assistants")
    put("by4_pct", pc(k[4] / tot_named, 0), f"{F_S}: descriptives.named_by_k_assistants")
    eng_share = D["by_assistant_named_share"]
    put("eng_min", pc(min(eng_share.values())), f"{F_S}: descriptives.by_assistant_named_share")
    put("eng_max", pc(max(eng_share.values())), f"{F_S}: descriptives.by_assistant_named_share")

    # ---- tests déposés
    h1, h2, h3, h4, h5, h8 = (R[x] for x in ("H1_reviews", "H2_rating", "H3_website", "H4_schema", "H5_content", "H8_nap"))
    al = S["all"]
    for key, obj, sub in (("H1", h1, "ame_per_doubling"), ("H3", h3, "ame"), ("H5", h5, "ame")):
        e = obj[sub]
        put(f"{key}.ame", f1(100 * e["est"]), f"{F_R}: {key}")
        put(f"{key}.lo", f1(100 * e["lo"]), f"{F_R}: {key}")
        put(f"{key}.hi", f1(100 * e["hi"]), f"{F_R}: {key}")
        put(f"{key}.or", f1(obj["or"], 2), f"{F_R}: {key}")
        put(f"{key}.or_lo", f1(obj["lo"], 2), f"{F_R}: {key}")
        put(f"{key}.or_hi", f1(obj["hi"], 2), f"{F_R}: {key}")
    for key, obj, sub, sk in (("H2", h2, "ame_per_star", "H2_rating_per_star"), ("H4", h4, "ame", "H4_schema"), ("H8", h8, "ame", "H8_nap")):
        e = obj[sub]
        put(f"{key}.ame", f1(100 * e["est"]), f"{F_R}: {key}")
        put(f"{key}.lo90", f1(100 * e["lo90"]), f"{F_R}: {key}")
        put(f"{key}.hi90", f1(100 * e["hi90"]), f"{F_R}: {key}")
        put(f"{key}.lo", f1(al[sk]["lo"]), f"{F_S}: all.{sk}")
        put(f"{key}.hi", f1(al[sk]["hi"]), f"{F_S}: all.{sk}")
        put(f"{key}.or", f1(obj["or"], 2), f"{F_R}: {key}")
        put(f"{key}.p_diff", pval(e["p_difference"]), f"{F_R}: {key}.p_difference")
    put("H1.n", n0(h1["n"]), f"{F_R}: H1_reviews.n")
    put("H1.markets", h1["markets"], f"{F_R}: H1_reviews.markets")
    put("H1.dropped", R["sample"]["markets_complete"] - h1["markets"], f"{F_R}: H1_reviews.markets")
    put("H2.n", n0(h2["n"]), f"{F_R}: H2_rating.n")
    put("H4.n", n0(h4["n"]), f"{F_R}: H4_schema.n")
    MD = X["models_dropped"]
    assert MD["M1"]["listings_in"] == h1["n"] and MD["M2"]["listings_in"] == h2["n"] and MD["M3"]["listings_in"] == h4["n"], MD
    for mk in ("M1", "M2", "M3"):
        for k2 in ("markets_in", "markets_out", "none_named", "all_named"):
            put(f"{mk}.{k2}", MD[mk][k2], f"construire.py: extras().models_dropped.{mk} (donnees/fiches.csv.gz)")
    # chance qu'avait le test d'équivalence de conclure si le lien vrai était nul, avec l'erreur type obtenue
    z95 = stats.norm.ppf(0.95)
    for hk, e in (("H2", h2["ame_per_star"]), ("H4", h4["ame"]), ("H8", h8["ame"])):
        room = e["margin"] - z95 * e["se"]
        put(f"eq.{hk}_room", f1(100 * max(room, 0), 2), f"{F_R}: {hk} margin and se (margin minus 1.645 se)")
        put(f"eq.{hk}_chance", pc(0 if room <= 0 else 2 * stats.norm.cdf(room / e["se"]) - 1, 0), f"{F_R}: {hk} margin and se")
    # 20 villes : avec les quantiles de Student à 19 degrés de liberté au lieu des quantiles normaux, aucun verdict ne change
    t975, t95 = stats.t.ppf(0.975, 19), stats.t.ppf(0.95, 19)
    put("t19.wider", pc(t975 / 1.96 - 1, 0), "Student t, 19 degrees of freedom, against 1.96")
    for e in (h1["ame_per_doubling"], h3["ame"], h5["ame"]):
        assert e["est"] - t975 * e["se"] > 0
    assert h2["ame_per_star"]["est"] - t95 * h2["ame_per_star"]["se"] > h2["ame_per_star"]["margin"]
    for e in (h4["ame"], h8["ame"]):
        assert e["est"] + t95 * e["se"] > e["margin"]
    assert h4["ame"]["est"] - t975 * h4["ame"]["se"] < 0 < h8["ame"]["est"] - t975 * h8["ame"]["se"]
    put("t19.H8_lo", f1(100 * (h8["ame"]["est"] - t975 * h8["ame"]["se"])), f"{F_R}: H8_nap.ame with t(19)")
    put("t19.H8_hi", f1(100 * (h8["ame"]["est"] + t975 * h8["ame"]["se"])), f"{F_R}: H8_nap.ame with t(19)")
    put("H4.share", pc(h4["share_with"], 0), f"{F_R}: H4_schema.share_with")
    put("H5.share", pc(h5["share_with"], 0), f"{F_R}: H5_content.share_with")
    put("H8.share", pc(h8["share_with"], 0), f"{F_R}: H8_nap.share_with")
    h6 = R["H6_directories_proxy"]
    put("H6.yelp_share", pc(h6["share_links_yelp"]), f"{F_R}: H6_directories_proxy")
    put("H6.hg_share", pc(h6["share_links_healthgrades_dentists"]), f"{F_R}: H6_directories_proxy")
    for key, lab in (("yelp_x_claude", "yelp"), ("healthgrades_x_chatgpt", "hg")):
        put(f"H6.{lab}_or", f1(h6[key]["or"], 2), f"{F_R}: H6_directories_proxy.{key}")
        put(f"H6.{lab}_lo", f1(h6[key]["lo"], 2), f"{F_R}: H6_directories_proxy.{key}")
        put(f"H6.{lab}_hi", f1(h6[key]["hi"], 2), f"{F_R}: H6_directories_proxy.{key}")
        put(f"H6.{lab}_p", pval(h6[key]["p"]), f"{F_R}: H6_directories_proxy.{key}")
    put("H6.raw_p", pval(min(1.0, 2 * min(h6["yelp_x_claude"]["p"], h6["healthgrades_x_chatgpt"]["p"]))), f"{F_R}: H6_directories_proxy (twice the smaller p)")
    HC = X["h6_counts"]
    put("H6.yelp_n", n0(HC["yelp"]), "construire.py: extras().h6_counts (donnees/fiches.csv.gz)")
    put("H6.hg_n", HC["healthgrades_dentists"], "construire.py: extras().h6_counts (donnees/fiches.csv.gz)")
    put("H6.dentist_pages", n0(HC["dentist_pages"]), "construire.py: extras().h6_counts (donnees/fiches.csv.gz)")
    h7m, h7v0 = R["H7_rating_threshold"]["main"], json.loads((V2 / "resultats_phase_a_v0_bug_h7.json").read_text())["H7_rating_threshold"]["main"]
    put("H7.honest_lo", f1(100 * h7m["lo"]), f"{F_R}: H7_rating_threshold.main.lo")
    put("H7.honest_hi", f1(100 * h7m["hi"]), f"{F_R}: H7_rating_threshold.main.hi")
    put("H7.M", f1(h7m["M"]), f"{F_R}: H7_rating_threshold.main.M")
    put("H7.M_v0", f1(h7v0["M"], 0), "resultats_phase_a_v0_bug_h7.json: H7_rating_threshold.main.M")
    h7 = R["H7_rating_threshold"]["main"]
    put("H7.est", sg(100 * h7["est"]), f"{F_R}: H7_rating_threshold.main")
    put("H7.se", f1(100 * h7["se"]), f"{F_R}: H7_rating_threshold.main")
    put("H7.cl_lo", f1(100 * (h7["est"] - 1.96 * h7["se"])), f"{F_R}: H7_rating_threshold.main (est − 1.96 se)")
    put("H7.cl_hi", f1(100 * (h7["est"] + 1.96 * h7["se"])), f"{F_R}: H7_rating_threshold.main (est + 1.96 se)")
    put("H7.honest_half", f1(100 * (h7["hi"] - h7["lo"]) / 2, 0), f"{F_R}: H7_rating_threshold.main (lo, hi)")
    put("H7.n_left", n0(h7["n_left"]), f"{F_R}: H7_rating_threshold.main")
    put("H7.n_right", n0(h7["n_right"]), f"{F_R}: H7_rating_threshold.main")
    w = S["H7_windows"]["4.2-4.8"]
    put("H7.wide_est", sg(100 * w["est"]), f"{F_S}: H7_windows.4.2-4.8")
    put("H7.wide_se", f1(100 * w["se"]), f"{F_S}: H7_windows.4.2-4.8")
    for pl in ("4.2", "4.7"):
        p = R["H7_rating_threshold"][f"placebo_{pl}"]
        put(f"H7.placebo{pl}", sg(100 * p["est"]), f"{F_R}: H7_rating_threshold.placebo_{pl}")
    bh = R["bh_adjusted"]
    for hk, v in bh.items():
        put(f"bh.{hk}", pval(v), f"{F_R}: bh_adjusted.{hk}")

    # ---- descriptifs
    q = D["named_share_by_review_quartile_within_market"]
    for i in range(4):
        put(f"q{i + 1}", pc(q[str(i)], 0), f"{F_S}: descriptives.named_share_by_review_quartile_within_market")
    rb = D["named_share_by_rating_band"]
    for lab, key in (("r_lt4", "<4.0"), ("r_40", "4.0-4.4"), ("r_45", "4.5-4.7"), ("r_48", "4.8-5.0")):
        put(lab, pc(rb[key]["named_share"], 0), f"{F_S}: descriptives.named_share_by_rating_band")
    mr = S["H7_means_by_rating"]
    # parts exactes (nommées / fiches) : le fichier de résultats les arrondit à 4 décimales, d'où un double arrondi (32,35 -> 32,4)
    ex = X["named_by_rating_exact"]
    for r in mr:
        assert ex[r]["n"] == mr[r]["n"] and round(ex[r]["named"] / ex[r]["n"], 4) == mr[r]["named_share"], r
    exs = {r: ex[r]["named"] / ex[r]["n"] for r in mr}
    put("r_49", pc(exs["4.9"], 0), f"{F_S}: H7_means_by_rating")
    put("r_44x", pc(exs["4.4"]), f"{F_S}: H7_means_by_rating")
    put("r_45x", pc(exs["4.5"]), f"{F_S}: H7_means_by_rating")
    put("r_47x", pc(exs["4.7"]), f"{F_S}: H7_means_by_rating")
    put("r_50", pc(mr["5.0"]["named_share"], 0), f"{F_S}: H7_means_by_rating")
    put("r_50_n", n0(mr["5.0"]["n"]), f"{F_S}: H7_means_by_rating")
    rr = X["rating_5_vs_45_49"]
    SRC5 = "construire.py: extras().rating_5_vs_45_49 (donnees/fiches.csv.gz)"
    put("r_45_49", pc(rr["r45_49"]["named_share"], 0), SRC5)
    put("r_45_49_n", n0(rr["r45_49"]["n"]), SRC5)
    put("r_45_49_median", f1(rr["r45_49"]["median_reviews"], 0), SRC5)
    put("r_50_median", f1(rr["r50"]["median_reviews"], 0), SRC5)
    e1r = X["edition1_rating_5_vs_45_49"]
    SRC_E1 = "construire.py: extras().edition1_rating_5_vs_45_49 (published Edition 1 file, study/ai-local-search-2026-11/listings_anonymized.csv)"
    put("e1.r_45_49", pc(e1r["r45_49"]["named_share"], 0), SRC_E1)
    put("e1.r_50", pc(e1r["r50"]["named_share"], 0), SRC_E1)
    put("r_48_median_reviews", f1(rb["4.8-5.0"]["median_reviews"], 0), f"{F_S}: descriptives.named_share_by_rating_band")
    put("r_45_median_reviews", f1(rb["4.5-4.7"]["median_reviews"], 0), f"{F_S}: descriptives.named_share_by_rating_band")
    for lab, key in (("web", "named_share_by_website"), ("content", "named_share_by_content_ok"), ("schema", "named_share_by_schema_org"),
                     ("nap", "named_share_by_nap_consistent"), ("yelp", "named_share_by_links_yelp")):
        put(f"{lab}0", pc(D[key]["0"]["named_share"], 0), f"{F_S}: descriptives.{key}")
        put(f"{lab}1", pc(D[key]["1"]["named_share"], 0), f"{F_S}: descriptives.{key}")
    c = D["cited"]
    put("cited_share", pc(c["cited_share"], 0), f"{F_S}: descriptives.cited")
    put("cited_named", pc(c["named_share_if_cited"], 0), f"{F_S}: descriptives.cited")
    put("notcited_named", pc(c["named_share_if_not_cited"], 0), f"{F_S}: descriptives.cited")
    put("cited_n", n0(c["listings_with_own_site"]), f"{F_S}: descriptives.cited")
    put("chain_share", pc(S["shares"]["chain_share"]), f"{F_S}: shares.chain_share")
    put("cat_ok_share", pc(S["shares"]["cat_ok_share"], 0), f"{F_S}: shares.cat_ok_share")
    put("cat_not_ok_share", pc(1 - S["shares"]["cat_ok_share"], 0), f"{F_S}: shares.cat_ok_share")
    put("cat_not_ok_named", pc(S["shares"]["named_share_cat_not_ok"], 0), f"{F_S}: shares.named_share_cat_not_ok")

    # ---- solidité
    lo = S["leave_one_city_out"]
    for hk, lab in (("H1_reviews_per_doubling", "H1"), ("H2_rating_per_star", "H2"), ("H3_website", "H3"), ("H4_schema", "H4"),
                    ("H5_content", "H5"), ("H8_nap", "H8")):
        put(f"loo.{lab}", f"{f1(lo[hk]['min'])} to {f1(lo[hk]['max'])}", f"{F_S}: leave_one_city_out.{hk}")
    po = S["poisson_answers"]
    put("irr.reviews", f1(po["M1"]["lr"]["irr"], 2), f"{F_S}: poisson_answers.M1.lr")
    put("irr.rating", f1(po["M2"]["rating"]["irr"], 2), f"{F_S}: poisson_answers.M2.rating")
    put("irr.web", f1(po["M1"]["web"]["irr"], 2), f"{F_S}: poisson_answers.M1.web")
    put("irr.content", f1(po["M3"]["content_ok"]["irr"], 2), f"{F_S}: poisson_answers.M3.content_ok")
    put("irr.schema", f1(po["M3"]["schema_org"]["irr"], 2), f"{F_S}: poisson_answers.M3.schema_org")
    put("irr.schema_lo", f1(po["M3"]["schema_org"]["lo"], 2), f"{F_S}: poisson_answers.M3.schema_org")
    put("irr.schema_hi", f1(po["M3"]["schema_org"]["hi"], 2), f"{F_S}: poisson_answers.M3.schema_org")
    sf = S["sensitivity_false_names"]
    put("fn.n", sf["false_names_in_sample"], f"{F_S}: sensitivity_false_names")
    put("fn.attached", len(sf["false_names_attached_to_a_listing"]), f"{F_S}: sensitivity_false_names.false_names_attached_to_a_listing")
    put("fn.removed_a", sf["a_21_names_in_their_market"]["kept_mentions_removed"], f"{F_S}: sensitivity_false_names.a_21_names_in_their_market")
    put("fn.removed_b", sf["b_same_strings_in_all_markets"]["kept_mentions_removed"], f"{F_S}: sensitivity_false_names.b_same_strings_in_all_markets")
    put("fn.changed", sf["b_same_strings_in_all_markets"]["listings_no_longer_named"], f"{F_S}: sensitivity_false_names.b_same_strings_in_all_markets")
    st2 = sf["c_named_in_2plus_answers"]
    put("strict.named", n0(st2["named"]), f"{F_S}: sensitivity_false_names.c_named_in_2plus_answers")
    put("strict.share", pc(st2["named_share"]), f"{F_S}: sensitivity_false_names.c_named_in_2plus_answers")
    for hk, lab in HKEYS:
        put(f"strict.{hk[:2]}", f1(st2[hk]["ame_pts"]), f"{F_S}: sensitivity_false_names.c_named_in_2plus_answers.{hk}")
    lg = S["sensitivity_loose_matching"]
    au = lg["audit"]
    FL = f"{F_S}: sensitivity_loose_matching"
    put("loose.named", n0(lg["named_loose"]), FL)
    put("loose.added", n0(lg["listings_added"]), FL)
    put("loose.share", pc(lg["named_share_loose"], 0), FL)
    put("loose.never", pc(1 - lg["named_share_loose"], 0), FL)
    put("loose.audit_n", au["cards"], FL + ".audit")
    put("loose.audit_same", au["same_business"], FL + ".audit")
    put("loose.audit_unsure", au["unsure"], FL + ".audit")
    put("loose.audit_not", au["not_same"], FL + ".audit")
    put("loose.audit_share", pc(au["share_same"], 0), FL + ".audit")
    put("loose.audit_lo", pc(au["wilson_lo"], 0), FL + ".audit")
    put("loose.audit_hi", pc(au["wilson_hi"], 0), FL + ".audit")
    put("loose.corr_named", pc(au["named_share_corrected"], 0), FL + ".audit")
    put("loose.corr_never", pc(1 - au["named_share_corrected"], 0), FL + ".audit")
    put("loose.corr_never_lo", pc(1 - au["named_share_corrected_hi"], 0), FL + ".audit")
    put("loose.corr_never_hi", pc(1 - au["named_share_corrected_lo"], 0), FL + ".audit")
    for w in ("claude", "gemini", "openai"):
        put(f"loose.r_{w}", au["per_reader"][w]["oui"], FL + ".audit.per_reader")
    put("loose.all_agree", au["all_agree"], FL + ".audit.all_agree")
    put("loose.pair_min", min(v["agree"] for v in au["pairs"].values()), FL + ".audit.pairs")
    put("loose.pair_max", max(v["agree"] for v in au["pairs"].values()), FL + ".audit.pairs")
    put("loose.kappa_min", f1(min(v["kappa"] for v in au["pairs"].values()), 2), FL + ".audit.pairs")
    put("loose.kappa_max", f1(max(v["kappa"] for v in au["pairs"].values()), 2), FL + ".audit.pairs")
    put("loose.domain_same", f"{au['by_rule']['c']['same_business']} of {au['by_rule']['c']['cards']}", FL + ".audit.by_rule.c")
    for hk, lab in HKEYS:
        put(f"loose.{hk[:2]}", f1(lg[hk]["ame_pts"]), FL + f".{hk}")
    hp = S["H5_parts_exploratory"]
    put("h5.cat", f1(S["robustness"]["google_category_matches_trade_only"]["H5_content"]["ame_pts"]), f"{F_S}: robustness.google_category_matches_trade_only")
    cm = hp["c_google_category_matches"]["pages_naming_the_trade"]
    put("h5.strict", f1(cm["content_ok"]["ame_pts"]), f"{F_S}: H5_parts_exploratory.c_google_category_matches.pages_naming_the_trade")
    put("h5.strict_lo", f1(cm["content_ok"]["lo"]), f"{F_S}: H5_parts_exploratory.c_google_category_matches.pages_naming_the_trade")
    put("h5.strict_hi", f1(cm["content_ok"]["hi"]), f"{F_S}: H5_parts_exploratory.c_google_category_matches.pages_naming_the_trade")
    put("h5.strict_with", pc(cm["named_share_with"], 0), f"{F_S}: H5_parts_exploratory.c_google_category_matches.pages_naming_the_trade")
    put("h5.strict_without", pc(cm["named_share_without"], 0), f"{F_S}: H5_parts_exploratory.c_google_category_matches.pages_naming_the_trade")
    put("h5.strict_n", n0(cm["n"]), f"{F_S}: H5_parts_exploratory.c_google_category_matches.pages_naming_the_trade")
    for part in ("trade_ok", "city_ok", "service_ok"):
        put(f"h5.{part}", f1(hp["a_three_parts"][part]["ame_pts"]), f"{F_S}: H5_parts_exploratory.a_three_parts.{part}")
        put(f"h5.{part}_share", pc(hp["shares"][part], 0), f"{F_S}: H5_parts_exploratory.shares.{part}")
    put("h5.no_stpaul_re", f1(hp["d_without_st_paul_and_real_estate"]["content_ok"]["ame_pts"]), f"{F_S}: H5_parts_exploratory.d_without_st_paul_and_real_estate")
    bt = S["by_trade"]
    h5t = sorted(((t, v["H5_content"]["ame_pts"]) for t, v in bt.items()), key=lambda z: z[1])
    put("h5.trade_min", f1(h5t[0][1]), f"{F_S}: by_trade.{h5t[0][0]}.H5_content")
    put("h5.trade_max", f1(h5t[-1][1]), f"{F_S}: by_trade.{h5t[-1][0]}.H5_content")
    put("h2.trades_clear", sum(1 for v in bt.values() if v["H2_rating_per_star"]["lo"] > 0), f"{F_S}: by_trade.*.H2_rating_per_star.lo > 0")
    put("h1.trades_clear", sum(1 for v in bt.values() if v["H1_reviews_per_doubling"]["lo"] > 0), f"{F_S}: by_trade.*.H1_reviews_per_doubling.lo > 0")
    put("h3.trades_clear", sum(1 for v in bt.values() if v["H3_website"]["lo"] > 0), f"{F_S}: by_trade.*.H3_website.lo > 0")
    ba = S["by_assistant"]
    put("h5.eng_min", f1(min(v["H5_content"]["ame_pts"] for v in ba.values())), f"{F_S}: by_assistant.*.H5_content")
    put("h5.eng_max", f1(max(v["H5_content"]["ame_pts"] for v in ba.values())), f"{F_S}: by_assistant.*.H5_content")

    # ---- base du tirage : la liste, les villes retirées avant le tirage, ce qui reste (relecture du 23/11 : l'article disait
    #      « the 344 municipalities with 100,000 residents or more » ; il y en a 348 dans la liste, 344 après le retrait)
    import ast
    listed = list(csv.DictReader((V2 / "us_cities_100k.csv").open()))
    excl = ast.literal_eval(re.search(r"EXCLUDE = (\{.*?\})\n", (V2 / "tirage_villes.py").read_text(), re.S).group(1))
    removed = sorted((c["city"], c["state"]) for c in listed if (c["city"], c["state"]) in excl)
    # la phrase de la section 3.2 et le point 22 de l'annexe B nomment ces quatre villes : on s'arrête si la liste change
    assert removed == [("Antioch", "CA"), ("Concord", "CA"), ("Los Angeles", "CA"), ("Tulsa", "OK")], removed
    put("draw.listed", len(listed), "us_cities_100k.csv: rows")
    put("draw.removed", len(removed), "tirage_villes.py: EXCLUDE, cities present in us_cities_100k.csv")
    put("draw.frame", len(listed) - len(removed), "us_cities_100k.csv: rows minus tirage_villes.py: EXCLUDE")

    # ---- ce que dit le kappa faible entre les lecteurs 1 et 2 : les noms que le lecteur 1 juge « non », vus par le lecteur 2
    cards = list(csv.DictReader((V2 / "donnees" / "lectures_260.csv").open(encoding="utf-8")))
    r1_no = [c for c in cards if c["kind"] == "name" and c["reader1_claude_with_evidence"] == "non"]
    put("r12.names_r1_no", len(r1_no), "donnees/lectures_260.csv: kind = name, reader 1 = non")
    for lab, ans in (("no", "non"), ("dk", "nsp"), ("yes", "oui")):
        put(f"r12.names_r1_no_r2_{lab}", sum(1 for c in r1_no if c["reader2_founder_blind"] == ans),
            f"donnees/lectures_260.csv: kind = name, reader 1 = non, reader 2 = {ans}")
    assert sum(int(VAL[f"r12.names_r1_no_r2_{lab}"]["value"]) for lab in ("no", "dk", "yes")) == len(r1_no)

    # ---- double lecture et contrôle des pages
    p12 = ACC["pairs"]["l1_vs_l2"]
    for lab, key in (("all", "all_260"), ("names", "names_n"), ("matches", "matches_r")):
        t = p12[key]["three_answers"]
        put(f"r12.{lab}_agree", t["agree"], f"audit/accord.json: pairs.l1_vs_l2.{key}.three_answers")
        put(f"r12.{lab}_raw", pc(t["agree"] / t["n"]), f"audit/accord.json: pairs.l1_vs_l2.{key}.three_answers")
        put(f"r12.{lab}_kappa", f1(t["kappa"], 2), f"audit/accord.json: pairs.l1_vs_l2.{key}.three_answers")
        put(f"r12.{lab}_ac1", f1(t["ac1"], 2), f"audit/accord.json: pairs.l1_vs_l2.{key}.three_answers")
    bm = ACC["blind_model_readers"]
    put("maj.names", bm["majority_oui"]["names_n"], "audit/accord.json: blind_model_readers.majority_oui")
    put("maj.names_pct", pc(bm["majority_oui"]["names_n"] / 200), "audit/accord.json: blind_model_readers.majority_oui")
    put("maj.matches", bm["majority_oui"]["matches_r"], "audit/accord.json: blind_model_readers.majority_oui")
    put("maj.matches_wrong", 60 - bm["majority_oui"]["matches_r"], "audit/accord.json: blind_model_readers.majority_oui")
    put("blind_all_agree", bm["all_agree"]["all_260"], "audit/accord.json: blind_model_readers.all_agree")
    for pair in ("l1_vs_l3", "l1_vs_l4", "l1_vs_l5", "l4_vs_l5"):
        t = ACC["pairs"][pair]["all_260"]["three_answers"]
        put(f"{pair}.raw", pc(t["agree"] / t["n"]), f"audit/accord.json: pairs.{pair}.all_260.three_answers")
        put(f"{pair}.kappa", f1(t["kappa"], 2), f"audit/accord.json: pairs.{pair}.all_260.three_answers")
    for key in ("schema_org", "address_ok", "phone_ok", "links_yelp", "city_ok", "trade_ok", "name_ok", "service_ok", "content_ok", "nap_consistent"):
        put(f"pg.{key}", f"{PAGES[key]['agree']} of {PAGES[key]['n']}", f"controle_pages/comparaison.json: {key}")
        put(f"pg.{key}_kappa", f1(PAGES[key]["kappa"], 2), f"controle_pages/comparaison.json: {key}")

    # ---- ajouts de la relecture du 23/11
    cv2 = X["coverage"]
    put("cov_unmatched", n0(cv2["named_businesses"] - cv2["on_our_lists"]), "construire.py: extras().coverage (donnees/mentions.csv.gz, fiches.csv.gz)")
    put("fn.upper", pc(1 - 0.025 ** (1 / int(sf["false_names_in_sample"])), 0), f"{F_S}: sensitivity_false_names (exact 95% upper bound for 0 of n)")
    put("h5.range_lo", f1(float(VAL["h5.strict"]["value"]), 0), VAL["h5.strict"]["source"])
    put("h5.range_hi", f1(float(VAL["H5.ame"]["value"]), 0), VAL["H5.ame"]["source"])
    put("irr.nap", f1(po["M3"]["nap_consistent"]["irr"], 2), f"{F_S}: poisson_answers.M3.nap_consistent")
    put("irr.nap_lo", f1(po["M3"]["nap_consistent"]["lo"], 2), f"{F_S}: poisson_answers.M3.nap_consistent")
    put("irr.nap_hi", f1(po["M3"]["nap_consistent"]["hi"], 2), f"{F_S}: poisson_answers.M3.nap_consistent")
    P = X["position"]
    src_p = "construire.py: extras().position (donnees/fiches.csv.gz)"
    assert P["missing"] == 0 and P["listings"] == R["sample"]["listings"]
    put("pos.max", P["max"], src_p)
    put("pos.top20_n", n0(P["top20"]["n"]), src_p)
    put("pos.top20_named", n0(P["top20"]["named"]), src_p)
    put("pos.top20_share", pc(P["top20"]["named_share"], 0), src_p)
    put("pos.beyond_share", pc(P["beyond20"]["named_share"], 0), src_p)
    put("pos.shared", n0(P["shared_positions"]), src_p)
    put("pos.positions", n0(P["positions"]), src_p)
    for hk, lab in (("H1_reviews_per_doubling", "H1"), ("H2_rating_per_star", "H2"), ("H3_website", "H3"), ("H4_schema", "H4"), ("H5_content", "H5"),
                    ("H8_nap", "H8"), ("position_per_doubling", "pos")):
        put(f"pos.{lab}", f1(P[hk]["ame_pts"]), src_p)
        put(f"pos.{lab}_lo", f1(P[hk]["lo"]), src_p)
        put(f"pos.{lab}_hi", f1(P[hk]["hi"]), src_p)
    SR = X["site_reading"]
    src_s = "construire.py: extras().site_reading (donnees/fiches.csv.gz)"
    assert SR["with_website"] == st["with_website"] and SR["read"] == st["reachable_not_empty"]
    assert SR["not_read"] == SR["error"] + SR["robots"] + SR["social"] + SR["not_fetched"] + SR["fetched_unreadable_or_empty"]
    for k2 in ("not_read", "error", "robots", "social", "not_fetched", "fetched_unreadable_or_empty"):
        put(f"site.{k2}", n0(SR[k2]), src_s)
    put("site.named_read", pc(SR["named_share_read"], 0), src_s)
    put("site.named_not_read", pc(SR["named_share_not_read"], 0), src_s)
    E1, EU, EP = X["edition1_model"], X["edition1_update_model"], X["edition1_page"]
    src_e = "construire.py: extras().edition1_model (published Edition 1 file, study/ai-local-search-2026-11/listings_anonymized.csv)"
    put("e1.h2_ame", f1(E1["rating_ame_pts"]), src_e)
    put("e1.dentist_share", pc(E1["dentist_share"], 0), src_e)
    src_p = "construire.py: extras().edition1_page (published Edition 1 page data, apps/web/lib/ai-local-search-2026-11.json: reviews)"
    put("e1.page_or", f"{EP['or']['odds_ratio']:.2f}", src_p)
    put("e1.page_or_lo", f"{EP['or']['lo']:.2f}", src_p)
    put("e1.page_or_hi", f"{EP['or']['hi']:.2f}", src_p)
    put("e1.markets", EP["markets"], src_p)
    put("e1.cities", EP["cities"], src_p)
    put("e1.model_n", n0(EP["model_listings"]), src_p)
    assert EP["markets"] == E1["markets"] and EP["model_listings"] == E1["n"], "le fichier publié et la page de l'édition 1 divergent"
    src_u = "construire.py: extras().edition1_update_model (Edition 1 update never put online, data/edition1_update_listings_not_published.csv)"
    put("e1u.h2_ame", f1(EU["rating_ame_pts"]), src_u)
    put("e1u.markets", EU["markets"], src_u)
    put("e1u.cities", X["edition1_update_cities"], "ops/etude/resultats_v1.json: correlates (working results of the Edition 1 update, not published)")
    FD = X["first_draw_matches"]
    for k2 in ("n", "right", "wrong", "undecided"):
        put(f"draw1.{k2}", FD[k2], "audit/tirage1/lecteur1.csv: kind = match")
    r1m = collections.Counter(c["reader1_claude_with_evidence"] for c in cards if c["kind"] == "match")
    put("r1.matches_wrong", r1m["non"], "donnees/lectures_260.csv: kind = match, reader 1 = non")
    put("r1.matches_undecided", r1m["nsp"], "donnees/lectures_260.csv: kind = match, reader 1 = nsp")
    h8t = sorted(((v["H8_nap"]["ame_pts"], t) for t, v in bt.items()))
    put("h8.trade_min", sg(h8t[0][0]), f"{F_S}: by_trade.{h8t[0][1]}.H8_nap")
    put("h8.trade_min_name", TRADE[h8t[0][1]].lower(), f"{F_S}: by_trade")
    put("h8.trade_max", sg(h8t[-1][0]), f"{F_S}: by_trade.{h8t[-1][1]}.H8_nap")
    put("h8.trade_max_name", TRADE[h8t[-1][1]].lower(), f"{F_S}: by_trade")
    put("h8.trades_clear", sum(1 for v in bt.values() if v["H8_nap"]["lo"] > 0 or v["H8_nap"]["hi"] < 0), f"{F_S}: by_trade.*.H8_nap interval excludes zero")
    put("h4.trades_clear", sum(1 for v in bt.values() if v["H4_schema"]["lo"] > 0 or v["H4_schema"]["hi"] < 0), f"{F_S}: by_trade.*.H4_schema interval excludes zero")

    # ---- tableaux
    T: dict[str, str] = {}
    T["T1"] = table(["Step", "Count"], [
        ["Cities drawn at random", VAL["cities"]["value"]],
        ["Markets (city × trade) drawn", VAL["markets_drawn"]["value"]],
        ["Markets with all 20 answers (analyzed)", VAL["markets"]["value"]],
        ["Answers in the analyzed markets", VAL["answers"]["value"]],
        ["Google Maps listings collected, all 200 markets", VAL["listings_all"]["value"]],
        ["Listings in the analyzed markets", VAL["listings"]["value"]],
        ["Listings with a rating", VAL["rated"]["value"]],
        ["Listings with a website on the listing", VAL["with_site"]["value"]],
        ["Home pages read and not empty", VAL["pages_read"]["value"]],
        ["Listings named in at least one answer", f"{VAL['named']['value']} ({VAL['named_pct']['value']})"],
    ])
    api = {"chatgpt": "OpenAI Responses API, web search on", "gemini": "Google Search grounding on",
           "perplexity": "Perplexity API (search built in)", "claude": "Anthropic API, web search on, city as approximate location"}
    T["T2"] = table(["Assistant", "Model", "Settings", "Answers", "Names kept per answer", "Answers naming none", "Listings named"], [
        [lab, X["models"][e], api[e], n0(X["answers_by_engine"][e]), f1(X["names_per_answer"][e]), pc(X["answers_naming_none"][e]),
         pc(eng_share[e])] for e, lab in ENG])
    T["T4"] = table(["Hypothesis", "Registered prediction", "Estimate", "Interval", "Adjusted p", "Verdict"], [
        ["H1 Google reviews", "More reviews, more often named", f"{sg(100 * h1['ame_per_doubling']['est'])} points per doubling; odds ratio {f1(h1['or'], 2)}",
         f"95%: {VAL['H1.lo']['value']} to {VAL['H1.hi']['value']}", VAL["bh.H1"]["value"], "Supported"],
        ["H2 Star rating", "No link beyond ±1.8 points per star", f"{sg(100 * h2['ame_per_star']['est'])} points per star",
         f"90%: {VAL['H2.lo90']['value']} to {VAL['H2.hi90']['value']}", VAL["bh.H2"]["value"], "Prediction rejected: a link larger than the margin"],
        ["H3 Website on the listing", "Listings with a website named more often", f"{sg(100 * h3['ame']['est'])} points; odds ratio {f1(h3['or'], 2)}",
         f"95%: {VAL['H3.lo']['value']} to {VAL['H3.hi']['value']}", VAL["bh.H3"]["value"], "Supported"],
        ["H4 Schema markup", "No link beyond ±1.8 points", f"{sg(100 * h4['ame']['est'])} points",
         f"90%: {VAL['H4.lo90']['value']} to {VAL['H4.hi90']['value']}", VAL["bh.H4"]["value"], "Inconclusive"],
        ["H5 Home page content", "Pages stating trade, city and a service named more often", f"{sg(100 * h5['ame']['est'])} points; odds ratio {f1(h5['or'], 2)}",
         f"95%: {VAL['H5.lo']['value']} to {VAL['H5.hi']['value']}", VAL["bh.H5"]["value"], "Supported, with the caveat in Section 4.5"],
        ["H6 Directories, by assistant", "Larger link for the assistant that cites the directory most", f"Yelp link × Claude: odds ratio {VAL['H6.yelp_or']['value']} (p = {VAL['H6.yelp_p']['value']}). Healthgrades link × ChatGPT, dentists: odds ratio {VAL['H6.hg_or']['value']} (p = {VAL['H6.hg_p']['value']})",
         f"95%: {VAL['H6.yelp_lo']['value']} to {VAL['H6.yelp_hi']['value']} (Yelp); {VAL['H6.hg_lo']['value']} to {VAL['H6.hg_hi']['value']} (Healthgrades)", VAL["bh.H6"]["value"], "No evidence (weaker measure than registered)"],
        ["H7 Threshold at 4.5", "No jump at a displayed rating of 4.5 (±7.5 points)", f"{VAL['H7.est']['value']} points",
         f"95%, registered (allows for a discrete rating): {VAL['H7.honest_lo']['value']} to {VAL['H7.honest_hi']['value']}. Conventional: {VAL['H7.cl_lo']['value']} to {VAL['H7.cl_hi']['value']}", VAL["bh.H7"]["value"], "Inconclusive: equivalence not shown"],
        ["H8 Name, address, phone", "No link beyond ±1.8 points", f"{sg(100 * h8['ame']['est'])} points",
         f"90%: {VAL['H8.lo90']['value']} to {VAL['H8.hi90']['value']}", VAL["bh.H8"]["value"], "Inconclusive"],
    ])
    RQ = X["review_quarters"]
    put("rq_left_out", n0(RQ["left_out"]), "construire.py: extras().review_quarters (donnees/fiches.csv.gz)")
    put("rq_small_markets", n0(RQ["small_markets"]), "construire.py: extras().review_quarters (donnees/fiches.csv.gz)")
    T["T3"] = table(["Group of listings", "Listings", "Named"], [
        ["Reviews: bottom quarter of the market", n0(RQ["n"][0]), VAL["q1"]["value"]], ["Reviews: second quarter", n0(RQ["n"][1]), VAL["q2"]["value"]],
        ["Reviews: third quarter", n0(RQ["n"][2]), VAL["q3"]["value"]], ["Reviews: top quarter", n0(RQ["n"][3]), VAL["q4"]["value"]],
        ["Rating below 4.0", n0(rb["<4.0"]["n"]), VAL["r_lt4"]["value"]], ["Rating 4.0 to 4.4", n0(rb["4.0-4.4"]["n"]), VAL["r_40"]["value"]],
        ["Rating 4.5 to 4.7", n0(rb["4.5-4.7"]["n"]), VAL["r_45"]["value"]], ["Rating 4.8 to 5.0", n0(rb["4.8-5.0"]["n"]), VAL["r_48"]["value"]],
        ["Rating 4.5 to 4.9 (second split of 4.5 and up)", VAL["r_45_49_n"]["value"], VAL["r_45_49"]["value"]],
        ["Rating 5.0 (second split of 4.5 and up)", VAL["r_50_n"]["value"], VAL["r_50"]["value"]],
        ["No rating", VAL["unrated"]["value"], VAL["unrated_named"]["value"]],
        ["No website on the listing", n0(D["named_share_by_website"]["0"]["n"]), VAL["web0"]["value"]],
        ["Website on the listing", n0(D["named_share_by_website"]["1"]["n"]), VAL["web1"]["value"]],
        ["Home page without trade, city and service", n0(D["named_share_by_content_ok"]["0"]["n"]), VAL["content0"]["value"]],
        ["Home page with trade, city and service", n0(D["named_share_by_content_ok"]["1"]["n"]), VAL["content1"]["value"]],
        ["Home page without schema markup", n0(D["named_share_by_schema_org"]["0"]["n"]), VAL["schema0"]["value"]],
        ["Home page with schema markup", n0(D["named_share_by_schema_org"]["1"]["n"]), VAL["schema1"]["value"]],
        ["Home page without the listing's name, address and phone", n0(D["named_share_by_nap_consistent"]["0"]["n"]), pc(D["named_share_by_nap_consistent"]["0"]["named_share"], 0)],
        ["Home page with the listing's name, address and phone", n0(D["named_share_by_nap_consistent"]["1"]["n"]), pc(D["named_share_by_nap_consistent"]["1"]["named_share"], 0)],
        ["Home page without a link to its Yelp page", n0(D["named_share_by_links_yelp"]["0"]["n"]), pc(D["named_share_by_links_yelp"]["0"]["named_share"], 0)],
        ["Home page with a link to its Yelp page", n0(D["named_share_by_links_yelp"]["1"]["n"]), pc(D["named_share_by_links_yelp"]["1"]["named_share"], 0)],
    ])
    rob = S["robustness"]
    rows5 = [("All listings (registered models)", S["all"]), ("Without the 4 markets that had Edition 1 answers", rob["without_4_overlap_markets"]),
             ("Without chains (same name in 3 or more cities)", rob["without_chains"]),
             ("Without the 2 largest cities", rob["without_2_largest_cities"]), ("Markets with 10 or more listings", rob["markets_with_10plus_listings"]),
             ("Listings whose Google category matches the trade", rob["google_category_matches_trade_only"]),
             ("With the Google Maps position as a covariate (exploratory, added November 23)", X["position"])]
    T["T5"] = table(["Check", "Listings"] + [lab.split(" ")[0] for _, lab in HKEYS],
                    [[lab, n0(d["listings"])] + [sg(d[hk]["ame_pts"]) for hk, _ in HKEYS] for lab, d in rows5]
                    + [["Leaving out each city in turn (range)", ""] + [VAL[f"loo.{lab.split(' ')[0]}"]["value"] for _, lab in HKEYS]])
    T["T6"] = table(["Version of the data", "Listings named"] + [lab for _, lab in HKEYS], [
        [lab, n0(d["named"])] + [eff(d, hk) for hk, _ in HKEYS] for lab, d in (
            ("Registered outcome", sf["baseline"]),
            (f"Without the {sf['false_names_in_sample']} false names, in their market", sf["a_21_names_in_their_market"]),
            ("Without the same strings in every market", sf["b_same_strings_in_all_markets"]),
            ("Stricter outcome: named in 2 or more answers", st2),
            ("Looser matching of names to listings (over-matches by design)", {**lg, "named": lg["named_loose"]}))])
    T["T7"] = table(["Comparison", "Listings", "Difference in points (95% interval)"], [
        ["All listings with a home page read (registered H5)", n0(al["n_M3"]), eff(al, "H5_content")],
        ["Listings whose Google category matches the trade", n0(rob["google_category_matches_trade_only"]["n_M3"]), eff(rob["google_category_matches_trade_only"], "H5_content")],
        ["Pages that name the trade", n0(hp["b_pages_naming_the_trade"]["n"]), eff(hp["b_pages_naming_the_trade"], "content_ok")],
        ["Category matches and page names the trade", n0(cm["n"]), eff(cm, "content_ok")],
        ["Part 1 alone: page names the trade", n0(hp["a_three_parts"]["n"]), eff(hp["a_three_parts"], "trade_ok")],
        ["Part 2 alone: page names the city", n0(hp["a_three_parts"]["n"]), eff(hp["a_three_parts"], "city_ok")],
        ["Part 3 alone: page names a service of the trade", n0(hp["a_three_parts"]["n"]), eff(hp["a_three_parts"], "service_ok")],
        ["Without St. Paul and real estate (two known rule defects)", n0(hp["d_without_st_paul_and_real_estate"]["n"]), eff(hp["d_without_st_paul_and_real_estate"], "content_ok")],
    ])
    T["T8"] = table(["Assistant", "Listings named"] + [lab for _, lab in HKEYS],
                    [[lab, pc(ba[e]["named_share"])] + [eff(ba[e], hk) for hk, _ in HKEYS] for e, lab in ENG])
    T["T9"] = table(["Trade", "Listings", "Named"] + [lab for _, lab in HKEYS],
                    [[TRADE[t], n0(v["listings"]), pc(v["named_share"])] + [eff(v, hk) for hk, _ in HKEYS] for t, v in sorted(bt.items(), key=lambda z: TRADE[z[0]])])

    def agree(pair: str, key: str) -> list[str]:
        t = ACC["pairs"][pair][key]["three_answers"]
        return [f"{t['agree']} of {t['n']} ({pc(t['agree'] / t['n'])})", f1(t["kappa"], 2), f1(t["ac1"], 2)]
    T["T10"] = table(["Cards", "Raw agreement", "Cohen's kappa", "Gwet's AC1"], [
        ["All 260"] + agree("l1_vs_l2", "all_260"), ["200 names"] + agree("l1_vs_l2", "names_n"), ["60 matches"] + agree("l1_vs_l2", "matches_r"),
        ["243 cards where both readers decided", f"{p12['all_260']['both_decided']['agree']} of {p12['all_260']['both_decided']['n']} ({pc(p12['all_260']['both_decided']['agree'] / p12['all_260']['both_decided']['n'])})",
         f1(p12["all_260"]["both_decided"]["kappa"], 2), f1(p12["all_260"]["both_decided"]["ac1"], 2)]])
    names = {"l1": "Reader 1 (Claude, with evidence)", "l2": "Reader 2 (founder, blind)", "l3": "Reader 3 (separate Claude agent, blind)",
             "l4": "Reader 4 (Gemini, blind)", "l5": "Reader 5 (OpenAI, blind)"}
    T["T11"] = table(["Pair of readers", "Raw agreement (260 cards)", "Cohen's kappa", "Gwet's AC1"], [
        [f"{names[p[:2]].split(' (')[0]} and {names[p[-2:]].split(' (')[0]}"] + agree(p, "all_260")
        for p in ("l1_vs_l3", "l1_vs_l4", "l1_vs_l5", "l4_vs_l5", "l3_vs_l4", "l3_vs_l5", "l2_vs_l3", "l2_vs_l4", "l2_vs_l5")])
    pr = bm["per_reader_oui"]
    rk = ["reader1_claude_with_evidence", "reader2_founder_blind", "reader3_claude_agent_blind", "reader4_gemini_blind", "reader5_openai_blind"]
    T["T12"] = table(["", "Reader 1", "Reader 2", "Reader 3", "Reader 4", "Reader 5", "Majority of readers 3, 4, 5"], [
        ["Names judged a specific business, of 200"] + [pr[r]["names_n"] for r in rk] + [f"{bm['majority_oui']['names_n']} ({pc(bm['majority_oui']['names_n'] / 200)})"],
        ["Matches judged right, of 60"] + [pr[r]["matches_r"] for r in rk] + [f"{bm['majority_oui']['matches_r']} ({pc(bm['majority_oui']['matches_r'] / 60, 0)})"]])
    pl = [("schema_org", "Schema markup (H4)"), ("address_ok", "Address"), ("phone_ok", "Phone"), ("links_yelp", "Link to Yelp (H6)"),
          ("city_ok", "City"), ("trade_ok", "Trade"), ("name_ok", "Name"), ("service_ok", "Service"),
          ("content_ok", "Content (H5): trade, city and service"), ("nap_consistent", "Name, address, phone consistent (H8)")]
    T["T13"] = table(["Variable", "Agreement", "Rule yes, reader no", "Rule no, reader yes", "Cohen's kappa"], [
        [lab, f"{PAGES[key]['agree']} of {PAGES[key]['n']}", PAGES[key]["auto1_reader0"], PAGES[key]["auto0_reader1"], f1(PAGES[key]["kappa"], 2)] for key, lab in pl])
    city_meta = {}
    for r in csv.DictReader((V2 / "marches_phase_a.csv").open()):
        slug = r["city"].lower().replace(". ", "-").replace(" ", "-").replace("st.-paul", "st-paul")
        city_meta[slug] = r
    T["A1"] = table(["City", "State", "Census region", "Residents (2025 estimate)", "Markets analyzed", "Listings", "Named", "Not named in any answer"], [
        [city_meta[c["city_slug"]]["city"], city_meta[c["city_slug"]]["state"], city_meta[c["city_slug"]]["region"],
         n0(int(city_meta[c["city_slug"]]["pop2025"])), c["markets"], n0(c["listings"]), n0(c["named"]), pc(c["never_named_share"], 0)]
        for c in D["by_city"]])
    T["A2"] = table(["Trade", "Markets", "Listings returned by Google Maps", "Named (all)", "Not named (all)", "Listings in the trade's Google category", "Named (in category)", "Not named (in category)"], [
        [TRADE[t["trade"]], t["markets"], n0(t["listings"]), n0(t["named"]), pc(t["never_named_share"], 0), n0(PRESS["trades"][t["trade"]]["listings"]),
         n0(PRESS["trades"][t["trade"]]["named"]), PRESS["trades"][t["trade"]]["never_named_pct"]] for t in sorted(D["by_trade"], key=lambda z: TRADE[z["trade"]])])
    T["A3"] = table(["Trade", "The five questions"], [[TRADE[t], "; ".join(f"“{q}”" for q in X["questions"][t])] for t in sorted(X["questions"], key=lambda z: TRADE[z])])
    for kk, v in T.items():
        VAL[f"table:{kk}"] = {"value": v, "source": "construire.py"}

    # ---- figures
    nar = HERE / "figures_narrow"
    nar.mkdir(exist_ok=True)
    t1, t2 = "Share of listings named, by review count within the market", "Share of listings named, by displayed Google rating"
    r1 = [(lab, 100 * q[str(i)], "") for i, lab in enumerate(["Bottom quarter", "Second quarter", "Third quarter", "Top quarter"])]
    r2 = [(r, 100 * exs[r], f"n = {mr[r]['n']:,}") for r in sorted(mr)]
    svg_bars(fig / "fig1.svg", t1, r1, 40, "Named in at least one answer")
    svg_bars(fig / "fig2.svg", t2, r2, 40, "Named in at least one answer")
    svg_bars_narrow(nar / "fig1.svg", t1, r1, 40, "Named in at least one answer", label_w=100)
    svg_bars_narrow(nar / "fig2.svg", t2, r2, 40, "Named in at least one answer", label_w=24)
    t3, x3 = "Registered hypotheses: difference in the chance of being named", "Percentage points, with 95% intervals"
    r3 = [
        ("H1 reviews, per doubling", 100 * h1["ame_per_doubling"]["est"], 100 * h1["ame_per_doubling"]["lo"], 100 * h1["ame_per_doubling"]["hi"]),
        ("H2 rating, per star", al["H2_rating_per_star"]["ame_pts"], al["H2_rating_per_star"]["lo"], al["H2_rating_per_star"]["hi"]),
        ("H3 website on the listing", 100 * h3["ame"]["est"], 100 * h3["ame"]["lo"], 100 * h3["ame"]["hi"]),
        ("H4 schema markup", al["H4_schema"]["ame_pts"], al["H4_schema"]["lo"], al["H4_schema"]["hi"]),
        ("H5 home page content", 100 * h5["ame"]["est"], 100 * h5["ame"]["lo"], 100 * h5["ame"]["hi"]),
        ("H8 name, address, phone", al["H8_nap"]["ame_pts"], al["H8_nap"]["lo"], al["H8_nap"]["hi"]),
    ]
    svg_forest(fig / "fig3.svg", t3, r3, -5, 30, x3, band=1.8)
    svg_forest_narrow(nar / "fig3.svg", t3, r3, -5, 30, x3, band=1.8)
    t4, x4 = "Home page content (H5), by trade", "Percentage points, with 95% intervals (each trade analyzed alone)"
    r4 = [(TRADE[t], v["H5_content"]["ame_pts"], v["H5_content"]["lo"], v["H5_content"]["hi"]) for t, v in sorted(bt.items(), key=lambda z: -z[1]["H5_content"]["ame_pts"])]
    svg_forest(fig / "fig4.svg", t4, r4, -5, 45, x4)
    svg_forest_narrow(nar / "fig4.svg", t4, r4, -5, 45, x4)

    def public_source(src: str) -> str:
        for k in sorted(PUBLIC, key=len, reverse=True):
            if k.endswith("/") or k.startswith(".."):
                continue
            src = src.replace(k, PUBLIC[k])
        return src.replace("construire.py", "code/construire.py") if "code/construire.py" not in src else src
    (HERE / "valeurs.json").write_text(json.dumps({
        "note": "Every value printed in the article, with the public file and key it comes from. 'extras' are descriptive values computed by code/construire.py from the data files.",
        "extras": X, "values": {k: {"value": v["value"], "source": public_source(v["source"])} for k, v in VAL.items() if not k.startswith(("table:", "file:", "text:"))}},
        ensure_ascii=False, indent=1, default=float) + "\n")
    tpl_path = HERE / "article.gabarit.md"
    if not tpl_path.exists():
        print(f"{len(VAL)} valeurs écrites ; pas de gabarit, article non construit")
        return
    tpl = tpl_path.read_text()
    missing = sorted({k for k in re.findall(r"\{\{([^}]+)\}\}", tpl) if k not in VAL})
    if missing:
        sys.exit(f"clés inconnues dans le gabarit : {missing}")
    used = set(re.findall(r"\{\{([^}]+)\}\}", tpl))
    out = re.sub(r"\{\{([^}]+)\}\}", lambda mm: VAL[mm.group(1)]["value"], tpl)
    (HERE / "article_edition2.md").write_text(out)
    bare = re.sub(r"\{\{[^}]+\}\}", "", tpl)
    hard = sorted(set(re.findall(r"(?<![\w.])\d+(?:[.,]\d+)*%?", bare)), key=lambda z: (len(z), z))
    print(f"{len(VAL)} valeurs, {len(used)} utilisées dans le gabarit ; article écrit ({len(out.split()):,} mots)")
    print("nombres écrits en dur dans le gabarit (constantes de protocole, dates, numéros) :", " ".join(hard))


if __name__ == "__main__":
    main()
