#!/usr/bin/env python3
"""Recompute P (formula p-v1) for whenaikills.xyz from raw survey and compute inputs.

P = odds that AI causes human extinction or permanent disempowerment by 2100.
This is a human-supervised, independent re-implementation of p-v1 for checking. It does not
change the published number; the daily number comes from the day file and is anchored on X1 Blockchain.

Usage:
  python3 compute_p.py                      # uses https://whenaikills.xyz/api/method.json + today's day file (via /api/latest.json)
  python3 compute_p.py method.json day.json # local files (day.json = a day file from /days/)
Standard library only.
"""
import json, math, sys, datetime as dt, urllib.request

def load(src):
    if src.startswith("http"):
        with urllib.request.urlopen(urllib.request.Request(src, headers={"User-Agent": "compute_p.py"})) as r:
            return json.load(r)
    return json.load(open(src, encoding="utf-8"))

logit = lambda p: math.log(p / (1 - p))
sigmoid = lambda x: 1 / (1 + math.exp(-x))

def weighted_median(pairs):
    """pairs = [(value, weight)]; lower weighted median (first value where cumulative weight >= half)."""
    pairs = sorted((v, w) for v, w in pairs if w > 0)
    half, acc = sum(w for _, w in pairs) / 2, 0.0
    for v, w in pairs:
        acc += w
        if acc >= half:
            return v

def compute(method, day):
    d = dt.date.fromisoformat(day)
    hl = method["weights"]["half_life_years"]; yd = method["weights"]["days_per_year"]
    rows = []
    for s in method["sources"]:
        age = (d - dt.date.fromisoformat(s["wave_date"])).days / yd
        w = s["n_for_weight"] * 0.5 ** (age / hl) if s.get("p") is not None and s.get("in_p", True) else 0.0
        rows.append({"id": s["id"], "p": s.get("p"), "weight": w})
    centre = weighted_median([(logit(r["p"]), r["weight"]) for r in rows if r["p"] is not None])
    c = method["compute_adjustment"]
    years = (d - dt.date.fromisoformat(c["anchor_date"])).days / yd
    doublings = math.log2(c["flop_now"] / c["flop_anchor"])
    excess = doublings - c["trend_doublings_per_year"] * years
    shift = max(-c["cap_logodds"], min(c["cap_logodds"], c["coef_per_doubling"] * excess))
    p = sigmoid(centre + shift)
    return {"day": day, "sources": rows, "centre_logodds": centre, "flop_doublings_since_anchor": doublings,
            "expected_doublings": c["trend_doublings_per_year"] * years, "excess_doublings": excess,
            "shift_logodds": shift, "p": p, "p_rounded": round(p, method["stored_decimals"])}

if __name__ == "__main__":
    a = sys.argv[1:]
    method = load(a[0] if a else "https://whenaikills.xyz/api/method.json")
    dayf = load(a[1] if len(a) > 1 else load("https://whenaikills.xyz/api/latest.json")["day_file_url"])
    day = dayf.get("dzien") or dayf.get("day")
    stored = dayf["wskazniki"]["p"]["liczba"] if "wskazniki" in dayf else dayf.get("p")
    flop = next((o["wartosc"] for o in dayf.get("odczyty", []) if o.get("zrodlo") == "epoch-frontier"), None)
    if flop: method["compute_adjustment"]["flop_now"] = flop
    r = compute(method, day)
    for s in r["sources"]:
        print(f'{s["id"]:6} p={s["p"]} weight={s["weight"]:.4f}')
    print(f'centre {r["centre_logodds"]:.5f} log-odds, compute shift {r["shift_logodds"]:+.5f} '
          f'(doublings {r["flop_doublings_since_anchor"]:.4f} vs expected {r["expected_doublings"]:.4f})')
    print(f'day {day}: computed P = {r["p"]:.6f} -> {r["p_rounded"]} ; day file P = {stored} ; '
          + ("MATCH" if stored is not None and abs(r["p_rounded"] - stored) < 1e-12 else "MISMATCH"))
    sys.exit(0 if stored is not None and abs(r["p_rounded"] - stored) < 1e-12 else 1)
