"""Recompute the registered tests of "State of AI Local Search, Edition 2" from the public listing file.

    python reproduce.py            # run from the folder that holds data/, code/ and results/

Needs Python 3.10+, pandas, numpy, scipy and statsmodels. It loads the registered analysis code (code/analyse_phase_a.py) and
applies it to data/listings_anonymized.csv.gz, where the outcome ("named") is already computed. The matching of names to
listings cannot be rerun from this file, because it needs the business names that the registration keeps out of the release;
the names found in the answers are in data/mentions.csv.gz and the matching rules in code/commun.py and code/regles_v2.py.
It covers the eight registered hypotheses. The script prints each estimate next to the published one (results/registered_tests.json) and the largest difference.
"""
import json
import sys
import types
from pathlib import Path

import numpy as np
import pandas as pd

HERE = Path(__file__).parent
# The analysis module imports the matching rules, which depend on code that is not part of this release. Reading the public
# listing file does not need them, so two empty stand-ins are enough to load the registered statistical functions.
sys.modules.setdefault("commun", types.SimpleNamespace(resolve_market=None, TRADE=set()))
sys.path.insert(0, str(HERE / "code"))
import analyse_phase_a as A  # noqa: E402


def main() -> int:
    f = pd.read_csv(HERE / "data" / "listings_anonymized.csv.gz")
    f["lr"] = np.log2(1 + f.reviews_count.fillna(0))
    f["web"] = f.has_website
    pub = json.loads((HERE / "results" / "registered_tests.json").read_text())
    got: dict[str, float] = {}

    r1, d1 = A.fe_logit(f, "lr + web")
    got["H1 reviews, points per doubling"] = A.ame(r1, d1, "lr", False)[0]
    got["H3 website, points"] = A.ame(r1, d1, "web", True)[0]
    r2, d2 = A.fe_logit(f[f.rating.notna()], "lr + rating + web")
    got["H2 rating, points per star"] = A.ame(r2, d2, "rating", False)[0]
    site = f[f.page_read == 1].dropna(subset=["schema_org", "content_ok", "nap_consistent"]).copy()
    r3, d3 = A.fe_logit(site, "lr + schema_org + content_ok + nap_consistent")
    got["H4 schema markup, points"] = A.ame(r3, d3, "schema_org", True)[0]
    got["H5 home page content, points"] = A.ame(r3, d3, "content_ok", True)[0]
    got["H8 name, address, phone, points"] = A.ame(r3, d3, "nap_consistent", True)[0]
    got["H7 jump at 4.5, points"] = A.rd_honest(f)["est"]
    # H6: one row per listing and assistant, one intercept per market and assistant (odds ratio of the interaction, as registered)
    long = []
    for e in ("chatgpt", "gemini", "perplexity", "claude"):
        x = site[["market", "city_slug", "trade", "lr", "links_yelp", "links_healthgrades", f"named_{e}"]].copy()
        x["named"], x["engine"] = x.pop(f"named_{e}"), e
        long.append(x)
    L = pd.concat(long)
    L["mk_e"] = L.market + "#" + L.engine
    L["claude"], L["chatgpt"] = (L.engine == "claude").astype(int), (L.engine == "chatgpt").astype(int)
    r4, _ = A.fe_logit(L, "lr + links_yelp + links_yelp:claude", fe="mk_e")
    r5, _ = A.fe_logit(L[L.trade == "dentist"], "lr + links_healthgrades + links_healthgrades:chatgpt", fe="mk_e")
    ratios = {"H6 Yelp link x Claude, odds ratio": (float(np.exp(r4.params["links_yelp:claude"])), pub["H6_directories_proxy"]["yelp_x_claude"]["or"]),
              "H6 Healthgrades link x ChatGPT, odds ratio": (float(np.exp(r5.params["links_healthgrades:chatgpt"])),
                                                             pub["H6_directories_proxy"]["healthgrades_x_chatgpt"]["or"])}
    want = {"H1 reviews, points per doubling": pub["H1_reviews"]["ame_per_doubling"]["est"], "H3 website, points": pub["H3_website"]["ame"]["est"],
            "H2 rating, points per star": pub["H2_rating"]["ame_per_star"]["est"], "H4 schema markup, points": pub["H4_schema"]["ame"]["est"],
            "H5 home page content, points": pub["H5_content"]["ame"]["est"], "H8 name, address, phone, points": pub["H8_nap"]["ame"]["est"],
            "H7 jump at 4.5, points": pub["H7_rating_threshold"]["main"]["est"]}
    worst = 0.0
    print(f"{len(f):,} listings, {f.market.nunique()} markets, {int(f.named.sum()):,} named ({100 * f.named.mean():.1f}%)")
    for k, v in got.items():
        worst = max(worst, abs(v - want[k]))
        print(f"{k:44s} recomputed {100 * v:+8.3f}   published {100 * want[k]:+8.3f}")
    for k, (v, w) in ratios.items():
        worst = max(worst, abs(v - w) / 100)
        print(f"{k:44s} recomputed {v:8.3f}   published {w:8.3f}")
    print(f"largest difference: {100 * worst:.4f} points")
    return 0 if worst < 1e-6 else 1


if __name__ == "__main__":
    sys.exit(main())
