"""Lagna-degree transit scan: for every candidate lagna degree in Vrscika, count how many
dated life events fall while a slow graha (Saturn, Jupiter, Rahu, Ketu) stands within ±ORB of
the lagna degree or of the descendant degree.  Compare with chance coverage."""
from engine import *
import datetime as dt, json, math
import numpy as np

ORB = 1.0
EVENTS = [
 ('1849-07-30','Death of the father'),
 ('1850-01-25','Death of brother Joseph'),
 ('1858-10-05','Enters Schulpforta'),
 ('1865-11-01','Finds Schopenhauer in Leipzig'),
 ('1868-03-15','Riding accident'),
 ('1868-11-08','Meets Wagner'),
 ('1869-02-13','Basel chair'),
 ('1870-09-07','Dysentery and diphtheria at the front'),
 ('1872-01-02','The Birth of Tragedy published'),
 ('1876-04-11','Proposal to Mathilde Trampedach'),
 ('1876-08-13','Bayreuth; the break with Wagner'),
 ('1879-05-02','Asks Basel to release him'),
 ('1881-08-06','Eternal Recurrence at Surlei'),
 ('1882-05-13','Proposal to Lou Salomé at Lucerne'),
 ('1883-02-13','Zarathustra I finished; Wagner dies'),
 ('1888-09-30','Antichrist finished; Twilight preface'),
 ('1889-01-03','Collapse in Turin'),
 ('1897-04-20',"Mother's death"),
 ('1900-08-25','Death at Weimar'),
]
ev_dates = [dt.date.fromisoformat(d) for d,_ in EVENTS]

start = dt.date(1844,10,15); end = dt.date(1900,8,26)
ndays = (end-start).days+1
days = [start+dt.timedelta(days=i) for i in range(ndays)]
bodies = {'Sa':swe.SATURN,'Ju':swe.JUPITER,'Ra':swe.TRUE_NODE}
lon = {k: np.zeros(ndays) for k in list(bodies)+['Ke']}
for i,d in enumerate(days):
    j = swe.julday(d.year,d.month,d.day,12,swe.GREG_CAL)
    for k,b in bodies.items():
        lon[k][i] = pos(j,b)[0]
lon['Ke'] = (lon['Ra']+180)%360
np.save('transit_lons.npy', np.stack([lon[k] for k in ['Sa','Ju','Ra','Ke']]))

def angdiff(a,b):
    d = (a-b+180)%360-180
    return np.abs(d)

ev_idx = [(d-start).days for d in ev_dates]
results=[]
for tenth in range(0,300):
    L = 210 + tenth/10.0   # sidereal longitude of candidate lagna (Vrscika = 210..240)
    cover = np.zeros(ndays, dtype=bool)
    hits_by = {}
    for k in ['Sa','Ju','Ra','Ke']:
        for target,tag in [(L,'asc'),((L+180)%360,'dsc')]:
            m = angdiff(lon[k], target) <= ORB
            cover |= m
            for ei,(d,label) in zip(ev_idx,EVENTS):
                if m[ei]:
                    hits_by.setdefault(label,[]).append(f'{k}@{tag}')
    frac = cover.mean()
    nhit = len(hits_by)
    n = len(EVENTS)
    # binomial tail P(X>=nhit)
    p = sum(math.comb(n,x)*frac**x*(1-frac)**(n-x) for x in range(nhit,n+1))
    results.append(dict(deg=round(L-210,1), frac=frac, hits=nhit, p=p, which=hits_by))

json.dump(results, open('lagna_scan.json','w'), ensure_ascii=False)
best = sorted(results, key=lambda r:(-r['hits'], r['p']))[:12]
for r in results[::10]:
    print(f"{r['deg']:5.1f}°  cover {r['frac']*100:4.1f}%  hits {r['hits']}  p={r['p']:.3f}  {list(r['which'].keys())}")
print('--- best')
for r in best: print(r['deg'], r['hits'], round(r['frac'],3), round(r['p'],4), r['which'])
