"""Recount WordPress PHP-version shares and measure how fast each PHP branch
drains after it reaches end of life.

Data: api.wordpress.org/stats/php/1.0/ (live) plus every monthly-distinct
Internet Archive capture of the same URL (raw bytes via the id_ suffix).
EOL dates: php.net/eol.php and php.net/supported-versions.php (end of
security support), as read on 2026-11-29.

Usage: python -I wordpress-php-eol-decay.py [cache_dir] > wordpress-php-eol-decay-output.json
"""
import json
import math
import sys
import time
import gzip
import hashlib
import os
import urllib.request
from datetime import date, datetime

CACHE = sys.argv[1] if len(sys.argv) > 1 else None  # optional cache directory

API = "https://api.wordpress.org/stats/php/1.0/"
CDX = ("https://web.archive.org/cdx/search/cdx?url=api.wordpress.org/stats/php/1.0/"
       "&output=json&fl=timestamp,statuscode&collapse=timestamp:8&filter=statuscode:200")

# End of security support, per php.net (eol.php for ended branches,
# supported-versions.php for live ones).
EOL = {
    "5.2": date(2011, 1, 6), "5.3": date(2014, 8, 14), "5.4": date(2015, 9, 3),
    "5.5": date(2016, 7, 21), "5.6": date(2018, 12, 31), "7.0": date(2019, 1, 10),
    "7.1": date(2019, 12, 1), "7.2": date(2020, 11, 30), "7.3": date(2021, 12, 6),
    "7.4": date(2022, 11, 28), "8.0": date(2023, 11, 26), "8.1": date(2025, 12, 31),
    "8.2": date(2026, 12, 31), "8.3": date(2027, 12, 31), "8.4": date(2028, 12, 31),
    "8.5": date(2029, 12, 31), "8.6": date(2030, 12, 31),
}
RETIRE_THRESHOLD = 5.0  # WordPress core's stated 5% retirement baseline


def get(url, tries=6, cache=True):
    path = None
    if CACHE and cache:
        path = os.path.join(CACHE, hashlib.sha1(url.encode()).hexdigest())
        if os.path.exists(path):
            with open(path, "rb") as f:
                return f.read()
    for i in range(tries):
        try:
            req = urllib.request.Request(url, headers={"User-Agent": "recount-script/1.0"})
            with urllib.request.urlopen(req, timeout=60) as r:
                body = r.read()
            if body[:2] == bytes([0x1F, 0x8B]):
                body = gzip.decompress(body)
            if path:
                with open(path, "wb") as f:
                    f.write(body)
            time.sleep(2)
            return body
        except Exception:  # noqa: BLE001
            if i == tries - 1:
                raise
            time.sleep(10 * (i + 1))
    raise RuntimeError(url)


def vkey(v):
    a, b = v.split(".")
    return (int(a), int(b))


def eol_share(shares, on):
    """Share of sites on a branch whose security support ended before `on`."""
    return sum(p for v, p in shares.items() if v in EOL and EOL[v] < on)


def fit_exp(points):
    """Least-squares fit of ln(share) = a + k*t (t in years). Returns k, a."""
    xs = [t for t, _ in points]
    ys = [math.log(p) for _, p in points]
    n = len(xs)
    mx, my = sum(xs) / n, sum(ys) / n
    sxx = sum((x - mx) ** 2 for x in xs)
    k = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / sxx
    return k, my - k * mx


def main():
    rows = json.loads(get(CDX))[1:]
    # keep the first capture per calendar month
    seen, stamps = set(), []
    for ts, _ in rows:
        if ts[:6] not in seen:
            seen.add(ts[:6])
            stamps.append(ts)
    snaps = []
    for ts in stamps:
        raw = get(f"https://web.archive.org/web/{ts}id_/{API}")
        try:
            shares = json.loads(raw)
        except ValueError:
            print(f"skip {ts}: not JSON: {raw[:80]!r}", file=sys.stderr)
            continue
        snaps.append({"date": datetime.strptime(ts[:8], "%Y%m%d").date(), "shares": shares,
                      "source": f"wayback {ts}"})
    live = json.loads(get(API, cache=False))
    snaps.append({"date": date.today(), "shares": live, "source": "live API"})
    snaps.sort(key=lambda s: s["date"])

    out = {"fetched": date.today().isoformat(), "snapshots": []}
    for s in snaps:
        d, sh = s["date"], s["shares"]
        out["snapshots"].append({
            "date": d.isoformat(), "source": s["source"],
            "sum": round(sum(sh.values()), 3),
            "eol_now": round(eol_share(sh, d), 2),
            "eol_by_2027_01_01": round(eol_share(sh, date(2027, 1, 1)), 2),
            "shares": {v: sh[v] for v in sorted(sh, key=vkey)},
        })

    # Projection of the Jan 1 figure from different pace windows
    cur = snaps[-1]
    target = date(2027, 1, 1)
    le82 = lambda s: sum(p for v, p in s["shares"].items() if vkey(v) <= (8, 2))
    proj = []
    for s in snaps[:-1]:
        days = (cur["date"] - s["date"]).days
        if days < 20 or days > 800:
            continue
        rate = (le82(cur) - le82(s)) / days
        proj.append({"from": s["date"].isoformat(), "days": days,
                     "pts_per_30d": round(rate * 30, 2),
                     "projected_jan1": round(le82(cur) + rate * (target - cur["date"]).days, 1)})
    out["le82_now"] = round(le82(cur), 2)
    out["jan1_projection_by_window"] = proj

    # Post-EOL drain per branch
    decay = {}
    for v in ["5.6", "7.0", "7.1", "7.2", "7.3", "7.4", "8.0", "8.1"]:
        pts = [((s["date"] - EOL[v]).days / 365.25, s["shares"].get(v, 0))
               for s in snaps if s["date"] >= EOL[v] and s["shares"].get(v, 0) > 0]
        pre = [s for s in snaps if s["date"] <= EOL[v]]
        at_eol = pre[-1]["shares"].get(v) if pre else None
        if len(pts) < 3:
            decay[v] = {"eol": EOL[v].isoformat(), "share_at_last_pre_eol_snapshot": at_eol,
                        "points": len(pts), "note": "too few post-EOL snapshots"}
            continue
        k, a = fit_exp(pts)
        half = math.log(2) / -k if k < 0 else None
        latest = pts[-1]
        yrs_to_5 = (math.log(RETIRE_THRESHOLD / latest[1]) / k) if (k < 0 and latest[1] > RETIRE_THRESHOLD) else 0
        decay[v] = {
            "eol": EOL[v].isoformat(),
            "share_at_last_pre_eol_snapshot": at_eol,
            "share_now": latest[1],
            "years_since_eol": round(latest[0], 2),
            "post_eol_points": len(pts),
            "half_life_years": round(half, 2) if half else None,
            "years_from_now_to_5pct": round(yrs_to_5, 1),
            "series": [[round(t, 3), p] for t, p in pts],
        }
    out["post_eol_decay"] = decay

    # Rough projection of the next cliff (1 Jan 2028, when 8.3 ends).
    # Branches already past EOL drain at the median post-EOL half-life of
    # 7.1-8.0; 8.3 is assumed to shrink before its EOL by the same ratio 8.2
    # did between its peak and today. This is an illustration, not a forecast.
    hl = sorted(decay[v]["half_life_years"] for v in ["7.1", "7.2", "7.3", "8.0"])
    med = (hl[1] + hl[2]) / 2
    t = (date(2028, 1, 1) - cur["date"]).days / 365.25
    old = le82(cur) * 2 ** (-t / med)
    peak82 = max(s["shares"].get("8.2", 0) for s in snaps)
    ratio = cur["shares"]["8.2"] / peak82
    new83 = cur["shares"]["8.3"] * ratio
    out["cliff_2028_projection"] = {
        "median_half_life_years_7.1_to_8.0": round(med, 2),
        "le82_drained_by_2028": round(old, 1),
        "ratio_8.2_now_over_peak": round(ratio, 3),
        "8.3_estimated_at_eol": round(new83, 1),
        "eol_share_2028_01_01": round(old + new83, 1),
    }
    json.dump(out, sys.stdout, indent=1, default=str)


if __name__ == "__main__":
    main()
