"""
phi-cascade-check.py
====================

For each pair of dated public events, compute the gap in days, find the
closest power of the golden ratio phi^n (n = 5..10), and report whether
the gap falls within the Plan Q tolerance bracket.

Plan Q tolerance bracket: |delta| <= 8.1 % of the nearest phi^n.
The 8.1% figure is the empirical envelope observed across the Plan K and
Plan Q markers (see /spirale/cadence). Any post-hoc tolerance widening
must be flagged here.

Dependencies: pandas (Python 3.10+). No exotic packages.
"""

from __future__ import annotations

import math
from itertools import combinations
from pathlib import Path

import pandas as pd


CSV_PATH = Path(__file__).parent / "phi-cascade-dates.csv"
PHI = (1 + math.sqrt(5)) / 2  # 1.61803398875...
TOLERANCE = 0.081  # 8.1 %
N_RANGE = range(5, 11)  # phi^5 .. phi^10


def closest_phi_power(days: float, n_range=N_RANGE):
    """Return (n, phi^n, delta_pct) for the closest phi^n in range."""
    best = None
    for n in n_range:
        val = PHI ** n
        delta = abs(days - val) / val
        if best is None or delta < best[2]:
            best = (n, val, delta)
    return best


def main():
    df = pd.read_csv(CSV_PATH, parse_dates=["date"])
    print(f"Loaded {len(df)} events from {CSV_PATH.name}\n")
    for _, row in df.iterrows():
        print(f"  - {row['event']}  ({row['date'].date()})  [{row['source']}]")
    print()
    print(f"Golden ratio phi = {PHI:.6f}")
    print(f"Plan Q tolerance bracket: |delta| <= {TOLERANCE * 100:.1f} %")
    print(f"Range tested: phi^{N_RANGE.start} .. phi^{N_RANGE.stop - 1}")
    print()
    for n in N_RANGE:
        print(f"  phi^{n} = {PHI ** n:8.4f} days")
    print()

    pairs = list(combinations(df.itertuples(index=False), 2))
    pairs.sort(key=lambda ab: (ab[1].date - ab[0].date).days)

    in_bracket = 0
    for a, b in pairs:
        gap_days = (b.date - a.date).days
        if gap_days < 0:
            a, b = b, a
            gap_days = -gap_days
        n, val, delta = closest_phi_power(gap_days)
        in_b = delta <= TOLERANCE
        if in_b:
            in_bracket += 1
        verdict = "YES" if in_b else "NO (outside bracket)"
        print(
            f"{a.event} ({a.date.date()}) -> {b.event} ({b.date.date()}): {gap_days} days"
        )
        print(
            f"  closest phi^{n}: {val:.2f}  (delta {delta * 100:.1f} %)"
        )
        print(f"  in Plan Q bracket (<= {TOLERANCE * 100:.1f} %): {verdict}")
        print()

    total = len(pairs)
    print(f"Summary: {in_bracket}/{total} pairs land within the Plan Q phi bracket.")
    if in_bracket == total:
        print("All gaps register on the phi grid. Cadence is consistent with the bracket.")
    elif in_bracket == 0:
        print("No pair lands in the bracket. Cadence is not phi-anchored.")
    else:
        print(
            "Mixed result. Read the page /spirale/cadence for the discussion of which markers anchor."
        )


if __name__ == "__main__":
    main()
