"""Édition 2, phase A : analyses secondaires et de solidité prévues au dépôt (section 4), plus les chiffres descriptifs.

Tout ici est exploratoire ou de solidité : les tests de H1 à H8 sont dans `analyse_phase_a.py` et ne changent pas.
0 $, lecture des fichiers figés seulement.

    PYTHONPATH=. .venv/bin/python -u ops/etude/v2/analyse_phase_a_suite.py     # écrit resultats_phase_a_suite.json

Prévu au dépôt : par assistant, par métier (marchés d'au moins 10 fiches), fenêtres 4,2–4,8 et 4,35–4,65 pour H7, issue en
nombre de réponses (Poisson à effets fixes de marché), sans les chaînes, sans les 10 % de marchés les plus grands, sans
chaque ville tour à tour. Ajouté : sans les 4 marchés qui avaient des réponses de l'édition 1, sans les fiches d'une autre
catégorie Google, issue « cité » (le site du commerce parmi les sources d'une réponse).

Précisions fixées ici, avant de lancer :
- « chaîne » = le même nom (minuscules, lettres et chiffres seulement) dans au moins 3 villes ;
- « 10 % de marchés les plus grands » = les marchés des 2 villes les plus peuplées (Philadelphia, Minneapolis) : 90 marchés
  sur 200 atteignent le plafond de 100 fiches, le nombre de fiches ne permet pas de classer ;
- « autre catégorie Google » = la catégorie principale de la fiche ne contient aucun mot du métier (liste CAT ci-dessous).
"""
from __future__ import annotations

import json
import re
import sys
import time
from pathlib import Path
from urllib.parse import urlparse

import numpy as np
import pandas as pd
import statsmodels.formula.api as smf

sys.path.insert(0, str(Path(__file__).parents[1]))
sys.path.insert(0, str(Path(__file__).parent))
import analyse_phase_a as A  # noqa: E402

HERE = Path(__file__).parent
OVERLAP = {"philadelphia|dentist", "palmdale|dentist", "anaheim|dentist", "minneapolis|med-spa"}
BIG = {"philadelphia", "minneapolis"}
ENGINES = ("chatgpt", "gemini", "perplexity", "claude")
CAT = {"dentist": r"dentist|dental", "personal-injury-lawyer": r"injury|attorney|lawyer|law firm",
       "med-spa": r"spa|aesthetic|skin|laser|cosmetic|beauty", "plumber": r"plumb", "hvac-contractor": r"hvac|heating|air condition",
       "roofer": r"roof", "veterinarian": r"veterinar|animal hospital|pet", "chiropractor": r"chiropract",
       "real-estate-agent": r"real estate|realtor", "auto-repair-shop": r"auto|car repair|mechanic|tire|brake|transmission"}


def pts(est, se):
    return {"ame_pts": round(est * 100, 2), "lo": round((est - 1.96 * se) * 100, 2), "hi": round((est + 1.96 * se) * 100, 2)}


def site_frame(g: pd.DataFrame) -> pd.DataFrame:
    s = g[(g["reachable"] == True) & (g["empty"] == False)].copy()  # noqa: E712
    for c in ("schema_org", "content_ok", "nap_consistent"):
        s[c] = s[c].astype(float)
    return s.dropna(subset=["schema_org", "content_ok", "nap_consistent"])


def core(g: pd.DataFrame) -> dict:
    """Les trois modèles de l'analyse principale sur un sous-ensemble : effets marginaux moyens en points."""
    out = {"listings": int(len(g)), "named_share": round(float(g.named.mean()), 4)}
    try:
        r1, d1 = A.fe_logit(g, "lr + web")
        out["H1_reviews_per_doubling"] = {**pts(*A.ame(r1, d1, "lr", False)), "or": round(float(np.exp(r1.params["lr"])), 3)}
        out["H3_website"] = {**pts(*A.ame(r1, d1, "web", True)), "or": round(float(np.exp(r1.params["web"])), 3)}
        out["n_M1"], out["markets_M1"] = int(len(d1)), int(d1.market.nunique())
    except Exception as exc:  # noqa: BLE001
        out["M1_error"] = str(exc)[:160]
    try:
        r2, d2 = A.fe_logit(g[g.rating.notna()], "lr + rating + web")
        out["H2_rating_per_star"] = {**pts(*A.ame(r2, d2, "rating", False)), "or": round(float(np.exp(r2.params["rating"])), 3)}
    except Exception as exc:  # noqa: BLE001
        out["M2_error"] = str(exc)[:160]
    try:
        r3, d3 = A.fe_logit(site_frame(g), "lr + schema_org + content_ok + nap_consistent")
        for h, v in (("H4_schema", "schema_org"), ("H5_content", "content_ok"), ("H8_nap", "nap_consistent")):
            out[h] = {**pts(*A.ame(r3, d3, v, True)), "or": round(float(np.exp(r3.params[v])), 3)}
        out["n_M3"] = int(len(d3))
    except Exception as exc:  # noqa: BLE001
        out["M3_error"] = str(exc)[:160]
    return out


def poisson(g: pd.DataFrame, rhs: str) -> dict:
    d = g[g.groupby("market").answers.transform("sum") > 0].copy()
    res = smf.poisson(f"answers ~ {rhs} + C(market)", data=d).fit(disp=0, maxiter=300, method="bfgs", cov_type="cluster",
                                                                    cov_kwds={"groups": pd.factorize(d.city_slug)[0]})
    out = {"n": int(len(d))}
    for v in rhs.split(" + "):
        b, se = res.params[v], res.bse[v]
        out[v] = {"irr": round(float(np.exp(b)), 3), "lo": round(float(np.exp(b - 1.96 * se)), 3),
                  "hi": round(float(np.exp(b + 1.96 * se)), 3), "p": float(res.pvalues[v])}
    return out


def host(u: str) -> str:
    h = (urlparse(u if "//" in u else "//" + u).netloc or "").lower()
    return h.removeprefix("www.")


def cited_domains(a: pd.DataFrame) -> dict[str, set]:
    out: dict[str, set] = {}
    for mk, eng, cit in zip(a.market, a.engine, a.citations):
        try:
            items = json.loads(cit) if isinstance(cit, str) else []
        except Exception:  # noqa: BLE001
            items = []
        s = out.setdefault(mk, set())
        for it in items:
            u = (it.get("title") or "") if eng == "gemini" else (it.get("url") or "")
            h = host(u) if eng != "gemini" else u.lower().removeprefix("www.").strip()
            if h and "." in h and " " not in h:
                s.add(h)
    return out


def descriptives(a: pd.DataFrame, f: pd.DataFrame) -> dict:
    d: dict = {}

    def table(key):
        g = f.groupby(key)
        t = pd.DataFrame({"markets": g.market.nunique(), "listings": g.size(), "named": g.named.sum()})
        t["named_share"] = (t.named / t.listings).round(4)
        t["never_named_share"] = (1 - t.named / t.listings).round(4)
        return t.reset_index().to_dict("records")
    d["by_city"] = table("city_slug")
    d["by_trade"] = table("trade")
    d["by_assistant_named_share"] = {e: round(float(f[f"named_{e}"].mean()), 4) for e in ENGINES}
    k = f[[f"named_{e}" for e in ENGINES]].sum(axis=1)
    d["named_by_k_assistants"] = {int(i): int((k == i).sum()) for i in range(5)}
    d["answers_naming_among_named"] = {"median": float(f[f.named == 1].answers.median()),
                                       "share_named_once": round(float((f[f.named == 1].answers == 1).mean()), 4),
                                       "share_named_5plus": round(float((f[f.named == 1].answers >= 5).mean()), 4)}
    tot = f.groupby("market").answers.sum()
    top3 = f.sort_values("answers", ascending=False).groupby("market").head(3).groupby("market").answers.sum()
    d["top3_share_of_namings"] = round(float(top3.sum() / tot.sum()), 4)
    d["markets_with_no_listing_named"] = int((f.groupby("market").named.sum() == 0).sum())
    d["median_listings_named_per_market"] = float(f.groupby("market").named.sum().median())
    # nombre d'avis : quart du marché
    f = f.copy()
    f["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 np.nan)
    d["named_share_by_review_quartile_within_market"] = {int(q): round(float(v), 4) for q, v in
                                                         f.dropna(subset=["rq"]).groupby("rq").named.mean().items()}
    bands = pd.cut(f.rating, [0, 3.95, 4.45, 4.75, 5.0], labels=["<4.0", "4.0-4.4", "4.5-4.7", "4.8-5.0"])
    d["named_share_by_rating_band"] = {str(b): {"n": int(len(g)), "named_share": round(float(g.named.mean()), 4),
                                                 "median_reviews": float(g.reviews_count.median())}
                                       for b, g in f.groupby(bands, observed=True)}
    d["named_share_no_rating"] = {"n": int(f.rating.isna().sum()), "named_share": round(float(f[f.rating.isna()].named.mean()), 4)}
    d["named_share_by_website"] = {int(w): {"n": int(len(g)), "named_share": round(float(g.named.mean()), 4)} for w, g in f.groupby("web")}
    s = site_frame(f)
    for v in ("content_ok", "schema_org", "nap_consistent", "links_yelp"):
        d[f"named_share_by_{v}"] = {int(w): {"n": int(len(g)), "named_share": round(float(g.named.mean()), 4)}
                                    for w, g in s.groupby(s[v].astype(int))}
    d["site_status"] = {"with_website": int(f.web.sum()), "reachable_not_empty": int(len(s)),
                        "status_counts": f[f.web == 1].status.fillna("non lu").str.split(":").str[0].value_counts().to_dict()}
    # issue secondaire « cité »
    cd = cited_domains(a)
    dom = f.domain.fillna("").str.lower().str.removeprefix("www.")
    social = ("facebook.com", "instagram.com", "yelp.com", "linkedin.com", "google.com", "business.site", "linktr.ee")
    f["cited"] = [int(bool(x) and not x.endswith(social) and x in cd.get(mk, ())) for x, mk in zip(dom, f.market)]
    own = f[(f.web == 1) & ~dom.str.endswith(social)]
    d["cited"] = {"listings_with_own_site": int(len(own)), "cited_share": round(float(own.cited.mean()), 4),
                  "named_share_if_cited": round(float(own[own.cited == 1].named.mean()), 4),
                  "named_share_if_not_cited": round(float(own[own.cited == 0].named.mean()), 4),
                  "cited_share_among_named": round(float(own[own.named == 1].cited.mean()), 4)}
    return d, f


def main():
    t0 = time.time()
    a, m, f = A.load()
    f["cat_ok"] = [bool(re.search(CAT[t], str(c).lower())) for t, c in zip(f.trade, f.category_name)]
    key = f.name.fillna("").str.lower().str.replace(r"[^a-z0-9]+", "", regex=True)
    ncity = pd.Series(f.city_slug.values, index=key.values).groupby(level=0).nunique()
    f["chain"] = [int(bool(k) and ncity[k] >= 3) for k in key]
    out: dict = {"note": "exploratoire / solidité ; tests confirmatoires dans resultats_phase_a.json"}
    desc, f = descriptives(a, f)
    out["descriptives"] = desc
    print("descriptifs", round(time.time() - t0), "s", flush=True)

    def save():
        (HERE / "resultats_phase_a_suite.json").write_text(json.dumps(out, ensure_ascii=False, indent=1, default=float) + "\n")

    out["all"] = core(f)
    print("tout", json.dumps(out["all"]), flush=True)
    save()
    rob = {
        "without_4_overlap_markets": f[~f.market.isin(OVERLAP)],
        "without_chains": f[f.chain == 0],
        "without_2_largest_cities": f[~f.city_slug.isin(BIG)],
        "google_category_matches_trade_only": f[f.cat_ok],
        "markets_with_10plus_listings": f[f.groupby("market").market.transform("size") >= 10],
    }
    out["shares"] = {"chain_share": round(float(f.chain.mean()), 4), "cat_ok_share": round(float(f.cat_ok.mean()), 4),
                     "named_share_cat_not_ok": round(float(f[~f.cat_ok].named.mean()), 4)}
    out["robustness"] = {}
    for k, g in rob.items():
        out["robustness"][k] = core(g)
        print(k, round(time.time() - t0), "s", flush=True)
        save()
    out["by_assistant"] = {}
    for e in ENGINES:
        g = f.copy()
        g["named"] = g[f"named_{e}"]
        out["by_assistant"][e] = core(g)
        print(e, round(time.time() - t0), "s", flush=True)
        save()
    out["by_trade"] = {}
    big10 = f[f.groupby("market").market.transform("size") >= 10]
    for t, g in big10.groupby("trade"):
        out["by_trade"][t] = core(g)
        print(t, round(time.time() - t0), "s", flush=True)
        save()
    loo = {}
    for c in sorted(f.city_slug.unique()):
        loo[c] = core(f[f.city_slug != c])
        print("sans", c, round(time.time() - t0), "s", flush=True)
    out["leave_one_city_out"] = {}
    for h in ("H1_reviews_per_doubling", "H2_rating_per_star", "H3_website", "H4_schema", "H5_content", "H8_nap"):
        vals = {c: r[h]["ame_pts"] for c, r in loo.items() if h in r}
        out["leave_one_city_out"][h] = {"min": min(vals.values()), "max": max(vals.values()),
                                        "city_min": min(vals, key=vals.get), "city_max": max(vals, key=vals.get),
                                        "lowest_ci_lo": min(r[h]["lo"] for r in loo.values() if h in r),
                                        "highest_ci_hi": max(r[h]["hi"] for r in loo.values() if h in r)}
    save()
    out["poisson_answers"] = {}
    for label, g, rhs in (("M1", f, "lr + web"), ("M2", f[f.rating.notna()], "lr + rating + web"),
                          ("M3", site_frame(f), "lr + schema_org + content_ok + nap_consistent")):
        try:
            out["poisson_answers"][label] = poisson(g, rhs)
        except Exception as exc:  # noqa: BLE001
            out["poisson_answers"][label] = {"error": str(exc)[:160]}
    out["H7_windows"] = {"4.2-4.8": A.rd_honest(f, 4.5, 4.2, 4.8), "4.35-4.65": A.rd_honest(f, 4.5, 4.35, 4.65) or
                         "non estimable : une seule valeur de note à gauche du seuil (4,4)"}
    # H7 lu simplement : écart de moyennes (issue moins la moyenne du marché) entre 4,5 et 4,4, erreur groupée par ville
    r = f[f.rating.notna()].copy()
    r["yd"] = r.named - r.groupby("market").named.transform("mean")
    r["r1"] = r.rating.round(1)
    out["H7_means_by_rating"] = {str(k): {"n": int(len(g)), "named_share": round(float(g.named.mean()), 4),
                                          "within_market_dev_pts": round(float(g.yd.mean()) * 100, 2)}
                                 for k, g in r[(r.r1 >= 4.0) & (r.r1 <= 5.0)].groupby("r1")}
    save()
    print("FINI", round(time.time() - t0), "s", flush=True)


def h5_parts():
    """Exploratoire, ajouté le 22/11 après le contrôle des 50 pages : quelle partie de la variable de contenu porte l'écart ?
    (a) les trois parties séparées dans M3 ; (b) M3 chez les seules pages qui nomment le métier ; (c) les deux, chez les
    fiches dont la catégorie Google est celle du métier ; (d) M3 sans les marchés de St. Paul et sans l'immobilier (les deux
    défauts trouvés par le contrôle)."""
    a, m, f = A.load()
    f["cat_ok"] = [bool(re.search(CAT[t], str(c).lower())) for t, c in zip(f.trade, f.category_name)]
    s = pd.read_csv(HERE / "donnees" / "sites.csv.gz", dtype={"place_id": str})[["market", "place_id", "trade_ok", "city_ok", "service_ok"]]
    f = f.merge(s, on=["market", "place_id"], how="left")
    sf = site_frame(f).dropna(subset=["trade_ok", "city_ok", "service_ok"])
    out = {"shares": {v: round(float(sf[v].mean()), 4) for v in ("trade_ok", "city_ok", "service_ok", "content_ok")}}

    def parts(g):
        r, d = A.fe_logit(g, "lr + schema_org + trade_ok + city_ok + service_ok + nap_consistent")
        return {**{v: {**pts(*A.ame(r, d, v, True)), "or": round(float(np.exp(r.params[v])), 3)} for v in ("trade_ok", "city_ok", "service_ok")},
                "n": int(len(d))}

    def m3(g):
        r, d = A.fe_logit(g, "lr + schema_org + content_ok + nap_consistent")
        return {"content_ok": {**pts(*A.ame(r, d, "content_ok", True)), "or": round(float(np.exp(r.params["content_ok"])), 3)}, "n": int(len(d)),
                "named_share_with": round(float(d[d.content_ok == 1].named.mean()), 4),
                "named_share_without": round(float(d[d.content_ok == 0].named.mean()), 4)}
    out["a_three_parts"] = parts(sf)
    out["b_pages_naming_the_trade"] = m3(sf[sf.trade_ok == 1])
    out["c_google_category_matches"] = {"three_parts": parts(sf[sf.cat_ok]), "pages_naming_the_trade": m3(sf[sf.cat_ok & (sf.trade_ok == 1)])}
    out["d_without_st_paul_and_real_estate"] = m3(sf[(sf.city_slug != "st-paul") & (sf.trade != "real-estate-agent")])
    p = HERE / "resultats_phase_a_suite.json"
    o = json.loads(p.read_text())
    o["H5_parts_exploratory"] = out
    p.write_text(json.dumps(o, ensure_ascii=False, indent=1, default=float) + "\n")
    print(json.dumps(out, indent=1))


def faux_noms():
    """Sensibilité demandée par le fondateur le 22/11 : H1 à H5 sans les faux noms trouvés par la double lecture.

    Les 21 noms de l'échantillon de 200 que la majorité des trois lecteurs à l'aveugle (ajouts au dépôt) ne jugent pas être
    un commerce. (a) on retire ces 21 noms dans leur marché ; (b) on retire les mêmes chaînes dans tous les marchés ;
    (c) ajout : issue plus stricte, « nommé dans au moins 2 réponses », qu'un faux nom isolé ne peut pas créer.
    L'échantillon ne couvre que 200 des noms gardés : (a) et (b) ne retirent pas tous les faux noms de l'étude, ils montrent
    ce que pèsent ceux qu'on connaît ; (c) répond à la question pour l'ensemble.
    """
    import shutil
    import tempfile

    lec = pd.read_csv(HERE / "donnees" / "lectures_260.csv", dtype=str).fillna("")
    blind = ["reader3_claude_agent_blind", "reader4_gemini_blind", "reader5_openai_blind"]
    n = lec[lec.kind == "name"].copy()
    n["oui"] = sum((n[c] == "oui").astype(int) for c in blind)
    bad = n[n.oui <= 1]
    out = {"false_names_in_sample": int(len(bad)), "sample_names": int(len(n)), "names": sorted(set(bad.business_name))}
    a, m, f = A.load()
    base = core(f)
    # combien de ces faux noms se rattachent à une fiche (seuls ceux-là touchent l'issue)
    place = a.drop_duplicates("market").set_index("market")[["city", "state"]]
    attached = []
    for mk, names in bad.groupby("market").business_name:
        lst, grp = f[f.market == mk], 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())
        ents = set(pid_id.values())
        attached += [(mk, x) for x in names if name_id.get(x) in ents]
    out["false_names_attached_to_a_listing"] = [f"{mk} : {x}" for mk, x in attached]
    raw = pd.read_csv(A.DATA / "mentions.csv.gz", dtype={"scan_id": str})
    keys_a = set(zip(bad.market, bad.business_name))
    norm = lambda s: s.fillna("").str.lower().str.replace(r"[^a-z0-9]+", " ", regex=True).str.strip()  # noqa: E731
    strings_b = set(norm(bad.business_name))
    variants = {"a_21_names_in_their_market": pd.Series([k in keys_a for k in zip(raw.market, raw.business_name)], index=raw.index),
                "b_same_strings_in_all_markets": norm(raw.business_name).isin(strings_b)}
    real = A.DATA
    for label, drop in variants.items():
        tmp = Path(tempfile.mkdtemp(prefix="etude_sens_"))
        for fn in ("reponses.csv.gz", "fiches.csv.gz", "sites.csv.gz"):
            (tmp / fn).symlink_to((real / fn).resolve())
        r2 = raw.copy()
        r2.loc[drop & r2.kept, "kept"] = False
        r2.to_csv(tmp / "mentions.csv.gz", index=False, compression="gzip")
        A.DATA = tmp
        try:
            _, _, f2 = A.load()
        finally:
            A.DATA = real
            shutil.rmtree(tmp, ignore_errors=True)
        k = f.set_index(["market", "place_id"]).named
        k2 = f2.set_index(["market", "place_id"]).named.reindex(k.index)
        out[label] = {"kept_mentions_removed": int((drop & raw.kept).sum()), "listings_no_longer_named": int(((k == 1) & (k2 == 0)).sum()),
                      "named": int(f2.named.sum()), **core(f2)}
        print(label, json.dumps({h: out[label].get(h) for h in ("kept_mentions_removed", "listings_no_longer_named", "named")}), flush=True)
    g = f.copy()
    g["named"] = (g.answers >= 2).astype(int)
    out["c_named_in_2plus_answers"] = {"named": int(g.named.sum()), **core(g)}
    out["baseline"] = {"named": int(f.named.sum()), **base}
    p = HERE / "resultats_phase_a_suite.json"
    o = json.loads(p.read_text())
    o["sensitivity_false_names"] = out
    p.write_text(json.dumps(o, ensure_ascii=False, indent=1, default=float) + "\n")
    H = ["H1_reviews_per_doubling", "H2_rating_per_star", "H3_website", "H4_schema", "H5_content"]
    print("faux noms :", out["false_names_in_sample"], "| rattachés à une fiche :", out["false_names_attached_to_a_listing"])
    for lab in ("baseline", "a_21_names_in_their_market", "b_same_strings_in_all_markets", "c_named_in_2plus_answers"):
        r = out[lab]
        print(f"{lab:32s} nommées {r['named']:5d} | " + " | ".join(f"{h[:2]} {r[h]['ame_pts']:+.2f} [{r[h]['lo']:+.2f},{r[h]['hi']:+.2f}]" for h in H))


def rattachement_large():
    """Sensibilité ajoutée le 22/11 pendant la rédaction : et si les règles de rattachement manquaient des commerces ?

    Les règles déposées sont prudentes (57 rattachements justes sur 60) : elles peuvent laisser « non nommée » une fiche dont
    le commerce est pourtant dans une réponse sous une autre forme. Définition écrite AVANT de lancer. Une fiche est
    « nommée au sens large » si elle l'est avec les règles déposées, OU si un nom gardé du même marché remplit l'une des
    conditions suivantes (mots « distinctifs » = ni titre ou forme juridique, ni mot du métier, ni mot du lieu, 2 lettres
    au moins ; il en faut au moins un de 4 lettres ou plus) :
      (a) tous les mots distinctifs du nom de la réponse sont dans le nom de la fiche, dans n'importe quel ordre ;
      (b) tous les mots distinctifs du nom de la fiche sont dans le nom de la réponse, dans n'importe quel ordre ;
      (c) le domaine donné avec le nom dans la réponse est le domaine du site de la fiche.
    La règle est volontairement trop large (« Smith Dental » rejoint « Smith & Jones Orthodontics ») : elle donne une borne
    haute du nombre de fiches nommées, pas une meilleure mesure. Les tests déposés ne changent pas.
    """
    import commun

    a, m, f = A.load()
    place = a.drop_duplicates("market").set_index("market")[["city", "state"]]
    loose, trigger = {}, {}
    how = {"a": 0, "b": 0, "c": 0}
    for mk, lst in f.groupby("market"):
        grp = m[m.market == mk]
        city, st = place.loc[mk, "city"], place.loc[mk, "state"]
        pl = set(commun.tokens(city))
        if isinstance(st, str):
            pl |= {st.lower()} | set(commun.STATES.get(st.lower(), "").split())

        def info(part):
            return frozenset(w for w in part if w not in commun.TRADE and w not in pl)

        def ok(s):
            return bool(s) and max(len(w) for w in s) >= 4
        names = []
        for nm in sorted(set(grp.business_name.dropna())):
            names.append((set(commun.seq(nm)), [info(x) for x in commun.parts_of(nm)], nm))
        doms = {str(d).lower().removeprefix("www.") for d in grp.domain.dropna() if str(d).strip()}
        for pid, ln, dom in zip(lst.place_id, lst.name.fillna(""), lst.domain):
            full_f = set(commun.seq(ln))
            parts_f = [info(x) for x in commun.parts_of(ln, listing=True)]
            hit, via = None, ""
            for full_n, parts_n, nm in names:
                if any(ok(s) and s <= full_f for s in parts_n):
                    hit, via = "a", nm
                    break
                if any(ok(s) and s <= full_n for s in parts_f):
                    hit, via = "b", nm
                    break
            if hit is None and isinstance(dom, str) and dom.lower().removeprefix("www.") in doms:
                hit = "c"
                via = "; ".join(sorted(set(grp[grp.domain.astype(str).str.lower().str.removeprefix("www.") == dom.lower().removeprefix("www.")].business_name))[:3])
            loose[(mk, pid)] = hit
            trigger[(mk, pid)] = via
    g = f.copy()
    hits = [loose.get(k) for k in zip(g.market, g.place_id)]
    added = [(h is not None) and (nmd == 0) for h, nmd in zip(hits, g.named)]
    for h, ad in zip(hits, added):
        if ad:
            how[h] += 1
    g["named"] = [int(nmd == 1 or h is not None) for h, nmd in zip(hits, g.named)]
    out = {"definition": "registered rules OR all distinctive words of one name contained in the other (any order) OR same website domain",
           "named_registered": int(f.named.sum()), "named_loose": int(g.named.sum()), "listings": int(len(g)),
           "named_share_registered": round(float(f.named.mean()), 4), "named_share_loose": round(float(g.named.mean()), 4),
           "listings_added": int(sum(added)), "added_by_rule": how, **core(g)}
    # une ligne par fiche : nommée (règles déposées), nommée au sens large, et par quelle règle (pour l'export public et la presse)
    d = HERE / "audit" / "large"
    d.mkdir(parents=True, exist_ok=True)
    pd.DataFrame({"market": g.market, "place_id": g.place_id, "named_registered": f.named.values, "named_loose": g.named.values,
                  "loose_rule": [h if ad else "" for h, ad in zip(hits, added)]}).to_csv(d / "fiches_large.csv.gz", index=False, compression="gzip")
    # par ville et par métier : part nommée avec les règles déposées et avec la règle large (pour dire la fourchette)
    g["city_slug"], g["trade"] = g.market.str.split("|").str[0], g.market.str.split("|").str[1]
    for col in ("city_slug", "trade"):
        out[f"by_{col.split('_')[0]}"] = {k: {"listings": int(len(x)), "named_registered": int(f.loc[x.index, "named"].sum()), "named_loose": int(x.named.sum())}
                                          for k, x in g.groupby(col)}
    # tirage de 60 fiches ajoutées, pour une lecture une par une (graine fixe) : audit/large/tirage.csv
    ex = g[[bool(x) for x in added]].sample(min(60, int(sum(added))), random_state=20261122)
    ex = ex.assign(rule=[loose[k] for k in zip(ex.market, ex.place_id)], name_in_answers=[trigger[k] for k in zip(ex.market, ex.place_id)])
    ex = ex.reset_index(drop=True)
    ex.insert(0, "card", [f"g{i + 1:03d}" for i in range(len(ex))])
    ex[["card", "market", "place_id", "name", "address", "domain", "category_name", "rule", "name_in_answers"]].to_csv(d / "tirage.csv", index=False)
    out["audit_sample"] = int(len(ex))
    # la lecture des 60 fiches (audit/large/) : Claude d'abord (lecture.csv), puis Gemini et OpenAI à l'aveugle (ajout du 22/11
    # au soir). Règle fixée avant les deux lectures : « même commerce » si au moins deux lecteurs sur trois répondent oui.
    lec = d / "lecture.csv"
    if lec.exists():
        import math

        t = pd.read_csv(lec, dtype=str).fillna("")
        R = pd.DataFrame({"claude": t.set_index("card").reader_claude})
        for who in ("gemini", "openai"):
            pth = d / f"lecteur_{who}.csv"
            if pth.exists():
                R[who] = pd.read_csv(pth, dtype=str).set_index("card")[f"reader_{who}"]
        n, three = len(R), R.shape[1] == 3
        oui, non = (R == "oui").sum(axis=1), (R == "non").sum(axis=1)
        same = (oui >= 2) if three else (R.claude == "oui")
        notsame = (non >= 2) if three else (R.claude == "non")
        k, u = int(same.sum()), int((~same & ~notsame).sum())
        z, ph = 1.96, k / n
        den = 1 + z * z / n
        mid, half = (ph + z * z / (2 * n)) / den, z * math.sqrt(ph * (1 - ph) / n + z * z / (4 * n * n)) / den
        add, reg, tot = out["listings_added"], out["named_registered"], out["listings"]

        def kappa(x, y):
            po = float((x == y).mean())
            pe = sum(float((x == c).mean()) * float((y == c).mean()) for c in ("oui", "non", "nsp"))
            return round((po - pe) / (1 - pe), 3) if pe < 1 else 1.0
        rule = t.set_index("card").rule.reindex(R.index)
        out["audit"] = {"cards": n, "basis": "at least two of three readers (Claude, Gemini, OpenAI)" if three else "reader Claude only",
                        "same_business": k, "unsure": u, "not_same": n - k - u, "share_same": round(ph, 4),
                        "wilson_lo": round(mid - half, 4), "wilson_hi": round(mid + half, 4),
                        "by_rule": {r: {"cards": int((rule == r).sum()), "same_business": int((same & (rule == r)).sum())} for r in "abc"},
                        "per_reader": {w: {v: int((R[w] == v).sum()) for v in ("oui", "non", "nsp")} for w in R.columns},
                        "pairs": {f"{a}_vs_{b}": {"agree": int((R[a] == R[b]).sum()), "n": n, "kappa": kappa(R[a], R[b])}
                                  for a, b in (("claude", "gemini"), ("claude", "openai"), ("gemini", "openai")) if a in R and b in R},
                        "all_agree": int((R.nunique(axis=1) == 1).sum()),
                        "readers": "Claude (AI model, read first, not blind to the purpose); Google gemini-3.6-flash and OpenAI gpt-5.4, blind, same card and criteria",
                        "named_share_corrected": round((reg + add * ph) / tot, 4), "named_share_corrected_lo": round((reg + add * (mid - half)) / tot, 4),
                        "named_share_corrected_hi": round((reg + add * (mid + half)) / tot, 4),
                        "share_same_claude_only": round(float((R.claude == "oui").mean()), 4)}
    p = HERE / "resultats_phase_a_suite.json"
    o = json.loads(p.read_text())
    o["sensitivity_loose_matching"] = out
    p.write_text(json.dumps(o, ensure_ascii=False, indent=1, default=float) + "\n")
    print(json.dumps({k: out.get(k) for k in ("named_registered", "named_loose", "listings_added", "added_by_rule", "audit_sample", "audit")}, ensure_ascii=False))


if __name__ == "__main__":
    rattachement_large() if "--large" in sys.argv else faux_noms() if "--faux-noms" in sys.argv else h5_parts() if "--h5" in sys.argv else main()
