"""Chargement de l'instantané et règles communes de l'étude « State of AI Local Search » (v1, 21/11).

Tout part des fichiers figés de ops/etude/donnees/<date>/ (snapshot.py), jamais de la base vivante.

Définitions (écrites aussi dans methode.md) :
- Marché : une ville × un métier (« dentist » à Tulsa). Les marchés « online » et « worldwide » ne sont pas locaux : exclus.
- Mesure complète : le même jour, les 5 questions du marché posées aux 4 assistants de la méthode actuelle (ChatGPT gpt-5.4,
  Gemini 3.6 Flash, Perplexity Sonar, Claude Sonnet 5), soit 20 réponses. Une question reposée le même jour : la dernière compte.
- Commerce nommé : un nom extrait d'une réponse qui passe le filtre des noms (agents.insights._real, plus les intertitres et les
  noms faits seulement du métier, d'un service et de la ville). La précision du filtre est mesurée à la main (audit_noms.py).
- Rapprochement des noms : à l'intérieur d'un marché, « Dr. Ayed Hawatmeh », « Hawatmeh Dental Group » et la fiche Google
  « Hawatmeh Dental Group PLLC » forment un seul commerce (règles de resolve_market ; audit des fusions dans audit_fusions.csv).
- Marchés d'intervention : ceux où nous avons eu un client ou mesuré sa zone (interventions.csv) ; exclus des estimations.
"""
from __future__ import annotations

import gzip
import json
import re
from collections import defaultdict
from urllib.parse import urlparse
from pathlib import Path

import numpy as np
import pandas as pd

from agents.insights import _generic, _real
from core.text import business_key, normalize_name

HERE = Path(__file__).parent
SNAP = "2026-11-21"
DATA = HERE / "donnees" / SNAP
SEED = 20261121
MODELS = {"chatgpt": "gpt-5.4", "gemini": "gemini-3.6-flash", "perplexity": "sonar", "claude": "claude-sonnet-5"}
NOT_LOCAL = {"online", "worldwide"}
OWN_CATEGORIES = {"ai-visibility-tool", "ai-seo-agency"}

# v0.1 (19/11) : intertitres extraits par erreur (« severe toothache », « tips choosing right dentist »).
HEADING = re.compile(r"\b(tips?|how|what|why|choos\w*|anxiety|toothache|options?|cost|costs|prices?|pricing|benefits?|steps?|signs?|"
                     r"questions?|overview|summary|note|considerations?|factors?|insurance|reviews?|ratings?|near me|best|top|"
                     r"knocked|severe|pain|emergency room|urgent care|treatment|procedures?|services?)\b", re.I)

STATES = {
    "al": "alabama", "ak": "alaska", "az": "arizona", "ar": "arkansas", "ca": "california", "co": "colorado", "ct": "connecticut",
    "de": "delaware", "fl": "florida", "ga": "georgia", "hi": "hawaii", "id": "idaho", "il": "illinois", "in": "indiana",
    "ia": "iowa", "ks": "kansas", "ky": "kentucky", "la": "louisiana", "me": "maine", "md": "maryland", "ma": "massachusetts",
    "mi": "michigan", "mn": "minnesota", "ms": "mississippi", "mo": "missouri", "mt": "montana", "ne": "nebraska", "nv": "nevada",
    "nh": "new hampshire", "nj": "new jersey", "nm": "new mexico", "ny": "new york", "nc": "north carolina", "nd": "north dakota",
    "oh": "ohio", "ok": "oklahoma", "or": "oregon", "pa": "pennsylvania", "ri": "rhode island", "sc": "south carolina",
    "sd": "south dakota", "tn": "tennessee", "tx": "texas", "ut": "utah", "vt": "vermont", "va": "virginia", "wa": "washington",
    "wv": "west virginia", "wi": "wisconsin", "wy": "wyoming", "dc": "district of columbia"}
STOP = {"the", "of", "and", "at", "in", "on", "by", "a", "an", "dr", "drs", "dds", "dmd", "md", "do", "phd", "mph", "faad", "fagd",
        "magd", "pllc", "llc", "llp", "pa", "pc", "inc", "ltd", "co", "corp", "esq", "jr", "sr", "ii", "iii", "msd", "ms", "rn", "np"}
TRADE = {"dental", "dentistry", "dentist", "dentists", "family", "care", "clinic", "clinics", "center", "centers", "centre", "group",
         "associates", "office", "offices", "practice", "studio", "studios", "spa", "medspa", "medical", "med", "aesthetics",
         "aesthetic", "wellness", "law", "firm", "lawyers", "lawyer", "attorneys", "attorney", "injury", "personal", "plumbing",
         "plumber", "plumbers", "services", "service", "heating", "cooling", "air", "hvac", "roofing", "roofers", "roofer",
         "veterinary", "vet", "animal", "hospital", "pet", "chiropractic", "chiropractor", "smiles", "smile", "orthodontics",
         "cosmetic", "general", "comprehensive", "modern", "advanced", "complete", "total", "specialists", "partners", "company",
         "contractors", "contractor", "and", "sons", "realty", "real", "estate", "team", "homes", "dermatology", "skin"}
QTYPE = [("urgent", re.compile(r"\b(emergency|urgent|24[ /-]?hour|same[- ]day)\b", re.I)),
         ("top rated", re.compile(r"\btop[- ]rated\b|\bbest[- ]reviewed\b|\bhighest[- ]rated\b", re.I)),
         ("who is the best", re.compile(r"^\s*(who|which)\b", re.I)),
         ("best for a service", re.compile(r"\bbest\b.*\bfor\b", re.I)),
         ("most recommended", re.compile(r"\bmost recommended\b", re.I)),
         ("best", re.compile(r"\bbest\b", re.I))]


def qtype(query: str) -> str:
    for name, rx in QTYPE:
        if rx.search(query or ""):
            return name
    return "other"


def tokens(name: str) -> list[str]:
    return [t for t in normalize_name(name).split() if t]


def load():
    """Réponses des mesures complètes (méthode actuelle, marchés locaux), mentions filtrées, fiches, interventions."""
    a = pd.read_csv(DATA / "reponses.csv.gz", dtype={"scan_id": str})
    a = a[~a.city_slug.isin(NOT_LOCAL) & ~a.category.isin(OWN_CATEGORIES)]
    a = a[a.apply(lambda r: MODELS.get(r.engine) == r.model, axis=1)].copy()
    a["created_at"] = pd.to_datetime(a.created_at, utc=True, format="ISO8601")
    a = a.sort_values("created_at").drop_duplicates(["city_slug", "category", "scan_date", "engine", "query"], keep="last")
    g = a.groupby(["city_slug", "category", "scan_date"])
    full = g.filter(lambda d: d.engine.nunique() == 4 and d["query"].nunique() == 5 and len(d) == 20)
    full = full.copy()
    full["qtype"] = full["query"].map(qtype)
    full["market"] = full.city_slug + "|" + full.category
    inter = pd.read_csv(DATA / "interventions.csv")
    inter_set = set(inter.city_slug + "|" + inter.category)
    full["intervention"] = full.market.isin(inter_set)

    m = pd.read_csv(DATA / "mentions.csv.gz", dtype={"scan_id": str, "prospect_id": str})
    m = m[m.scan_id.isin(set(full.scan_id))].copy()
    info = full.set_index("scan_id")[["category", "city", "state", "market"]]
    m = m.join(info, on="scan_id")
    m["business_name"] = m.business_name.fillna("")
    keep = []
    for name, cat, city, st in zip(m.business_name, m.category, m.city, m.state):
        ok = _real(name, cat) and not HEADING.search(name) and not _generic(name, city or "", st if isinstance(st, str) else None)
        keep.append(ok)
    m["kept"] = keep

    f = pd.read_csv(DATA / "fiches.csv.gz", dtype={"prospect_id": str})
    f["market"] = f.city_slug + "|" + f.category
    f = f[f.market.isin(set(full.market))].copy()
    return full, m, f, inter


class UF:
    def __init__(self):
        self.p = {}

    def find(self, x):
        self.p.setdefault(x, x)
        while self.p[x] != x:
            self.p[x] = self.p[self.p[x]]
            x = self.p[x]
        return x

    def union(self, a, b):
        ra, rb = self.find(a), self.find(b)
        if ra != rb:
            self.p[max(ra, rb)] = min(ra, rb)


def seq(part: str) -> tuple[str, ...]:
    """Mots d'un nom dans l'ordre, sans titres, formes juridiques ni initiales (« Jeffrey H Stein DDS » -> jeffrey stein)."""
    return tuple(t for t in tokens(part) if t not in STOP and len(t) > 1)


def parts_of(name: str, listing: bool = False) -> list[tuple[str, ...]]:
    """Le nom entier ; chaque moitié d'un nom composé par l'assistant (« Sutra Dental Spa / Dr. Jimmy Wu ») ; et le début d'un
    nom suivi d'un lieu (« Manus Dental - Hyde Park » -> manus dental). Jamais la partie après un tiret ou une virgule :
    c'est presque toujours un quartier (« Queen Anne », « Buckhead ») ou une liste d'autres commerces (audit du 21/11)."""
    out = [seq(name)]
    if not listing:          # une fiche Google « MINT dentistry | Midtown Atlanta » : après le séparateur, c'est un lieu
        for part in re.split(r"[/|]", name or ""):
            out.append(seq(part))
    out.append(seq(re.split(r"\s[-–—]\s|[,(:/|]" if listing else r"\s[-–—]\s|[,(:]", name or "")[0]))
    uniq = []
    for x in out:
        if x and x not in uniq:
            uniq.append(x)
    return uniq


def same(a: tuple[str, ...], b: tuple[str, ...], place: set[str]) -> bool:
    """Règles prudentes, vérifiées à la main (audit_fusions_noms) :
    1. mêmes mots dans le même ordre (« Dr. Justin Phillips, DDS » = « Justin Phillips ») ;
    2. l'un est le début de l'autre, le plus court a au moins deux mots dont un qui n'est ni du métier ni du lieu, et les mots
       en plus ne sont que du métier, du lieu ou une forme juridique (« Sachar Dental » = « Sachar Dental NYC »,
       « Hub Plaza Dental Group » = « Hub Plaza Dental Group and Orthodontics »).
    Jamais de fusion sur un seul mot ni sur des mots du métier seulement (« Lancaster Dental Associates » reste distinct de
    « Lancaster Dental Care Associates »)."""
    informative = [w for w in a if w not in TRADE and w not in place]
    if a == b:
        return bool(informative) and (len(a) >= 2 or len(a[0]) >= 5)
    short, long_ = (a, b) if len(a) < len(b) else (b, a)
    if len(short) < 2 or long_[: len(short)] != short:
        return False
    if all(w in TRADE or w in place for w in short):
        return False
    extra = long_[len(short):]
    return all(w in TRADE or w in place or w in {"nyc", "la", "dc", "and"} for w in extra)


def resolve_market(names: list[str], listings: list[tuple[str, str]], city: str, state: str | None, freq: dict[str, int]):
    """Regroupe les noms d'un marché (et ses fiches) en commerces. Renvoie {nom: id}, {prospect_id: id}, fusions."""
    place = set(tokens(city))
    if state:
        place |= {state.lower()} | set(STATES.get(state.lower(), "").split())
    uf = UF()
    items = [("n", n, parts_of(n)) for n in names] + [("f", pid, parts_of(ln, listing=True)) for pid, ln in listings]
    index = defaultdict(list)                       # premier mot distinctif -> éléments (évite de tout comparer à tout)
    for kind, key, ps in items:
        uf.find((kind, key))
        for p in ps:
            index[p[0]].append((kind, key, p))
    merges = []
    for bucket in index.values():
        for i, (k1, key1, p1) in enumerate(bucket):
            for k2, key2, p2 in bucket[i + 1:]:
                if (k1, key1) == (k2, key2) or (k1 == "f" and k2 == "f"):
                    continue                        # deux fiches Google ne fusionnent jamais entre elles
                if same(p1, p2, place):
                    if uf.find((k1, key1)) != uf.find((k2, key2)):
                        uf.union((k1, key1), (k2, key2))
                        merges.append((" ".join(p1), " ".join(p2)))
    name_id = {n: uf.find(("n", n)) for n in names}
    pid_id = {pid: uf.find(("f", pid)) for pid, _ in listings}
    return name_id, pid_id, merges


def entities(full: pd.DataFrame, m: pd.DataFrame, f: pd.DataFrame, resolve: bool = True):
    """Ajoute à chaque mention gardée un identifiant de commerce (par marché) ; rattache les fiches au même identifiant.

    resolve=False : la clé brute de la v0 (prospect_id sinon business_key), pour l'analyse de sensibilité."""
    m = m[m.kept].copy()
    info = full.drop_duplicates("market").set_index("market")[["city", "state"]]
    ent = {}
    fiche_ent = {}
    merges_all = []
    for mk, grp in m.groupby("market"):
        if not resolve:
            for idx, row in grp.iterrows():
                ent[idx] = f"{mk}#p:{row.prospect_id}" if isinstance(row.prospect_id, str) else f"{mk}#{business_key(row.business_name)}"
            continue
        city, state = info.loc[mk, "city"], info.loc[mk, "state"]
        state = state if isinstance(state, str) else None
        lst = f[f.market == mk]
        listings = list(zip(lst.prospect_id, lst.name.fillna("")))
        names = sorted(set(grp.business_name))
        freq = grp.business_name.value_counts().to_dict()
        name_id, pid_id, merges = resolve_market(names, listings, city, state, freq)
        # un nom rattaché par le pipeline à une fiche (domaine, nom, alias) rejoint le commerce de cette fiche
        uf = UF()
        for n, i in name_id.items():
            uf.union(("e", i), ("e", i))
        for _, row in grp.iterrows():
            if isinstance(row.prospect_id, str) and row.prospect_id in pid_id:
                uf.union(("e", name_id[row.business_name]), ("e", pid_id[row.prospect_id]))
        for idx, row in grp.iterrows():
            ent[idx] = f"{mk}#{uf.find(('e', name_id[row.business_name]))}"
        for pid, i in pid_id.items():
            fiche_ent[pid] = f"{mk}#{uf.find(('e', i))}"
        merges_all += [(mk, a, b) for a, b in merges]
    m["entity"] = pd.Series(ent)
    if not resolve:
        # v0 : une fiche est nommée si une mention porte son prospect_id, ou si les noms normalisés sont identiques
        f = f.copy()
        named_pids = set(f.market + "#p:" + f.prospect_id) & set(m.entity)
        nn = {(mk, business_key(n)): e for mk, n, e in zip(m.market, m.business_name, m.entity)}
        f["entity"] = [p if p in named_pids else nn.get((mk, business_key(n if isinstance(n, str) else "")), p)
                       for p, mk, n in zip(f.market + "#p:" + f.prospect_id, f.market, f.name)]
    else:
        f = f.copy()
        f["entity"] = f.prospect_id.map(fiche_ent)
    return m, f, merges_all


def cluster_boot(units: pd.DataFrame, stat, cluster: str = "city_slug", b: int = 4000, seed: int = SEED):
    """IC à 95 % par bootstrap en grappes : on tire des villes avec remise (les marchés d'une même ville ne sont pas indépendants)."""
    rng = np.random.default_rng(seed)
    groups = {k: g for k, g in units.groupby(cluster)}
    keys = list(groups)
    est = stat(units)
    draws = []
    for _ in range(b):
        pick = rng.integers(0, len(keys), len(keys))
        sample = pd.concat([groups[keys[i]] for i in pick], ignore_index=True)
        try:
            draws.append(stat(sample))
        except Exception:  # noqa: BLE001  (un tirage dégénéré : on le saute et on le compte)
            continue
    lo, hi = np.nanpercentile(draws, [2.5, 97.5])
    return {"est": float(est), "lo": float(lo), "hi": float(hi), "n_units": int(len(units)), "n_clusters": len(keys), "draws": len(draws)}


def wilson(k: int, n: int, z: float = 1.96):
    if n == 0:
        return None
    p = k / n
    d = 1 + z * z / n
    c = (p + z * z / (2 * n)) / d
    h = z * np.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / d
    return {"est": p, "lo": c - h, "hi": c + h, "k": k, "n": n}


def dump(obj, path: Path):
    path.write_text(json.dumps(obj, ensure_ascii=False, indent=1, default=lambda o: o.item() if hasattr(o, "item") else str(o)))


def read_gz_text(path: Path) -> str:
    with gzip.open(path, "rt", encoding="utf-8") as fh:
        return fh.read()


# ——— Sources citées : familles de sites ———
GROUPS = [
    ("Google (Maps, Business Profile)", r"(^|\.)google\.|goo\.gl|business\.site$"), ("Yelp", r"(^|\.)yelp\."),
    ("Healthgrades", r"healthgrades\.com$"), ("Zocdoc", r"zocdoc\.com$"), ("WebMD", r"webmd\.com$"), ("BBB", r"(^|\.)bbb\.org$"),
    ("Reddit", r"(^|\.)reddit\.com$"), ("Birdeye", r"birdeye\.com$"),
    ("Social and video (Facebook, Nextdoor, YouTube, Instagram)", r"facebook\.com$|nextdoor\.com$|youtube\.com$|instagram\.com$|tiktok\.com$|linkedin\.com$"),
    ("Insurers' provider search", r"deltadental|cigna\.com$|aetna\.com$|metlife\.com$|guardianlife|humana\.com$|uhc\.com$|bcbs|anthem\.com$"),
    ("Directories and ranking sites", r"opencare\.com$|dentistsranked\.com$|toprateddentist\.com$|dental\.me$|tebra\.com$|bestinhood\.com$|"
        r"usnews\.com$|angi\.com$|threebestrated\.com$|realself\.com$|bestprosintown\.com$|rankmydentist\.com$|expertise\.com$|"
        r"thumbtack\.com$|authoritydental\.org$|homeadvisor\.com$|denscore\.com$|dentascore\.com$|smyleee\.com$|justia\.com$|"
        r"bestlawyers\.com$|superlawyers\.com$|avvo\.com$|findlaw\.com$|lawyers\.com$|martindale\.com$|trustanalytica\.org$|"
        r"medspascout\.com$|medicalspalocator\.com$|dentillo\.com$|dentdirectory\.com$|ratemds\.com$|homeguide\.com$|consumeraffairs\.com$|"
        r"yellowpages\.com$|mapquest\.com$|local\.yahoo\.com$|tripadvisor\.|opentable\.com$|vitals\.com$|castleconnolly\.com$|"
        r"1800dentist\.com$|ada\.org$|nationalorthodonticregistry\.com$|topratedlocal\.com$|nicelocal\.com$|chamberofcommerce\.com$|"
        r"manta\.com$|porch\.com$|bark\.com$|emergencydentist|247localdentist|emergencydental|findadentist|dentist\w*directory|"
        r"bestof|thebest|top10|bestinmycity|birdeye|carecredit\.com$|pawgrades|vetratingz|lawyer\w*finder|"
        r"priorityemergencydental\.care$"),
    ("News and magazines", r"forbes\.com$|phillymag\.com$|modernluxury\.com$|magazine|news|times\.com$|herald|tribune|post\.com$|"
                           r"journal|gazette|patch\.com$|axios\.com$|eater\.com$|timeout\.com$|infatuation\.com$"),
    ("Wikipedia", r"wikipedia\.org$")]
FAMILIES = [g for g, _ in GROUPS] + ["A business's own website", "Other sites"]


def core_label(host: str) -> str:
    """« smilegeneration.com » -> smilegeneration ; « www.drsmith-dental.co » -> drsmithdental."""
    labels = host.split(".")
    lab = labels[-3] if len(labels) >= 3 and labels[-2] in {"co", "com", "org", "net"} and len(labels[-1]) == 2 else labels[-2] if len(labels) >= 2 else host
    return re.sub(r"[^a-z0-9]", "", lab)


def compact_forms(name: str) -> set[str]:
    sq = seq(name)
    info = [w for w in sq if w not in TRADE]
    out = {"".join(sq)}
    if len(info) >= 1:
        out.add("".join(info))
    if len(sq) >= 2:
        out.add("".join(sq[:2]))
    return {x for x in out if len(x) >= 6}


def host_of(c):
    url, title = (c.get("url"), c.get("title")) if isinstance(c, dict) else (c, None)
    if not isinstance(url, str):
        return None
    h = urlparse(url).netloc.lower().removeprefix("www.")
    if h.startswith("vertexaisearch.cloud.google.com") and isinstance(title, str) and re.fullmatch(r"[\w.-]+\.[a-z]{2,}", title.strip().lower()):
        h = title.strip().lower().removeprefix("www.")
    return h or None




def load_all_markets():
    """Comme load(), marchés d'intervention compris (méthode client) : réponses complètes, mentions, fiches."""
    full, m, f, _ = load()
    return full, m, f
