"""Validate analysis readiness for this article's 2020-2023/2024 split before SPSS."""
if not __debug__:
    raise RuntimeError("Validation requires assertions; run Python without -O or PYTHONOPTIMIZE.")
from pathlib import Path
from datetime import datetime,timedelta
import csv,json,math,hashlib
ROOT=Path(__file__).resolve().parents[1]
(ROOT/'results').mkdir(parents=True,exist_ok=True)
receipt=ROOT/'results/analysis_readiness.json'
receipt.write_text(json.dumps({'status':'INCOMPLETE','reason':'Input validation started; no successful analysis-readiness check yet.'}))
path=ROOT/'data/sessions.csv'
expected='session_date,year,decision_time,label_end,pre_open,pre_high,pre_low,pre_close,prior20_mean,target_high,target_low,previous60_count,previous60_events,comparison_eligible'.split(',')
with path.open() as f:
    reader=csv.DictReader(f);assert reader.fieldnames==expected,'Unexpected sessions schema';rows=list(reader)
assert rows,'No study rows'
previous=None;train=[];holdout=[];features=[]
for row in rows:
    assert None not in row and all(v is not None for v in row.values()),'Malformed row'
    day=datetime.strptime(row['session_date'],'%Y.%m.%d')
    assert day.strftime('%Y.%m.%d')==row['session_date'] and day.weekday()<5
    assert previous is None or day>previous,'Duplicate/unordered date'
    previous=day;values={k:float(v) for k,v in row.items() if k not in ('session_date','decision_time','label_end')}
    assert all(math.isfinite(v) for v in values.values())
    assert values['year']==day.year and 2020<=day.year<=2024,'Unsupported study year'
    assert row['decision_time']==(day+timedelta(hours=8)).strftime('%Y.%m.%d %H:%M')
    assert row['label_end']==(day+timedelta(hours=16)).strftime('%Y.%m.%d %H:%M')
    o,h,l,c,a=[values[k] for k in ('pre_open','pre_high','pre_low','pre_close','prior20_mean')]
    assert 0<l<=min(o,c)<=max(o,c)<=h and h>l and a>0,'Invalid predictor prices/scale'
    th,tl=values['target_high'],values['target_low'];assert th>=tl>0
    count,events=values['previous60_count'],values['previous60_events']
    assert count==int(count) and events==int(events) and 0<=events<=count<=60
    assert values['comparison_eligible']==int(count==60),'Invalid comparison flag'
    outcome=int(th-tl>1.25*a)
    if day.year<=2023:
        train.append(outcome);features.append([1.,math.log1p((h-l)/a),abs(c-o)/(h-l)])
    elif count==60:holdout.append(outcome)
assert len(train)>3 and set(train)=={0,1},'Training needs both outcome classes and more rows than coefficients'
assert holdout,'No complete 2024 comparison sample'
# Rank check only, not model estimation.
a=[[sum(row[i]*row[j] for row in features) for j in range(3)] for i in range(3)]
for i in range(3):
    pivot=max(range(i,3),key=lambda j:abs(a[j][i]));a[i],a[pivot]=a[pivot],a[i]
    assert abs(a[i][i])>1e-12,'Rank-deficient training predictors'
    for j in range(i+1,3):
        scale=a[j][i]/a[i][i]
        for k in range(i,3):a[j][k]-=scale*a[i][k]
out={'status':'PASS','scope':'Input readiness only; SPSS convergence and included-case counts still require inspection.','input_sha256':hashlib.sha256(path.read_bytes()).hexdigest(),'rows':len(rows),'training_n':len(train),'training_events':sum(train),'holdout_n':len(holdout),'holdout_events':sum(holdout)}
receipt.write_text(json.dumps(out,indent=2));print(json.dumps(out,indent=2))
