"""Re-run the test behind Orthodynamo's ChatGPT standing figure. Plain Python, no libraries.

    python chatgpt_standing_test.py chatgpt-standing-2026-10-31.csv

The file lists one row per practice: its Semrush ChatGPT visibility averaged over October 4 to 31,
2026, the average of its strongest tracked competitor, how many competitors were tracked, and on how
many of the days it led (lines starting with # are the source and the definitions). A practice
"leads" when its average is above every tracked competitor's average. If a practice were no more
visible than its competitors, each of the competitors+1 domains would be equally likely to lead, so
its chance of leading is 1/(competitors+1). The expected number of leaders is the sum of those
chances. The p-value is the probability of at least the observed number of leaders when each
practice leads independently with its own chance (the upper tail of a Poisson-binomial
distribution, computed exactly by convolution).

If chatgpt-daily-2026-10-31.csv sits beside the standing file, the script also recomputes every
average from the daily values and reports whether they match.
"""
import csv
import os
import statistics
import sys


def poisson_binomial_upper(chances, k):
    dist = [1.0]
    for p in chances:
        new = [0.0] * (len(dist) + 1)
        for i, q in enumerate(dist):
            new[i] += q * (1 - p)
            new[i + 1] += q * p
        dist = new
    return sum(dist[k:])


def read_csv(path):
    with open(path, encoding="utf-8") as f:
        lines = [l for l in f if l.strip() and not l.startswith("#")]
    return list(csv.DictReader(lines))


def check_daily(rows, daily_path):
    """Recompute each practice's window average and its strongest competitor's from the daily file."""
    by = {}
    for r in read_csv(daily_path):
        by.setdefault(r["practice"], {}).setdefault(r["domain"], []).append((r["date"], float(r["visibility_pct"])))
    worst = 0.0
    for r in rows:
        days = int(r["days_averaged"])
        window = sorted(v for v in by[r["practice"]]["practice"] if "2026-10-04" <= v[0] <= "2026-10-31")[:days]
        own = sum(v for _, v in window) / len(window)
        comps = []
        for dom, vals in by[r["practice"]].items():
            if dom != "practice":
                w = sorted(v for v in vals if "2026-10-04" <= v[0] <= "2026-10-31")[:days]
                comps.append(sum(v for _, v in w) / len(w))
        worst = max(worst, abs(own - float(r["visibility_pct"])), abs(max(comps) - float(r["strongest_competitor_pct"])))
        assert len(comps) == int(r["competitors_tracked"]), r["practice"]
    print(f"Daily file: averages recomputed for {len(rows)} practices; largest difference to the standing file {worst:.3f} points"
          f" ({'match' if worst < 0.05 else 'DO NOT MATCH'}).")


def main(path):
    rows = read_csv(path)
    n = len(rows)
    vis = [float(r["visibility_pct"]) for r in rows]
    best = [float(r["strongest_competitor_pct"]) for r in rows]
    k = [int(r["competitors_tracked"]) for r in rows]
    leads = sum(v > b for v, b in zip(vis, best))
    chances = [1 / (c + 1) for c in k]
    p = poisson_binomial_upper(chances, leads)
    print(f"{leads} of {n} practices lead every competitor they track on the four-week average.")
    print(f"Expected by chance if no better than their competitors: {sum(chances):.2f}.")
    print(f"Probability of {leads} or more leaders by chance: {p:.2e} (about 1 in {1 / p:,.0f}).")
    print(f"Median practice average {statistics.median(vis):.1f}%, median strongest competitor {statistics.median(best):.1f}%.")
    behind = [(i + 1, v, b) for i, (v, b) in enumerate(zip(vis, best)) if v <= b]
    print(f"Behind: {len(behind)} practices, rows {', '.join(str(i) for i, _, _ in behind)}.")
    if "days_first" in rows[0]:
        maj = sum(int(r["days_first"]) > int(r["days_averaged"]) / 2 for r in rows)
        print(f"First on more than half of the days: {maj} of {n} (p = {poisson_binomial_upper(chances, maj):.1e}).")
    daily = os.path.join(os.path.dirname(os.path.abspath(path)), "chatgpt-daily-2026-10-31.csv")
    if os.path.exists(daily):
        check_daily(rows, daily)


if __name__ == "__main__":
    main(sys.argv[1] if len(sys.argv) > 1 else "chatgpt-standing-2026-10-31.csv")
