"""Leakage-conscious chronological discovery replay, SHADOW ONLY.

Does not alter the app, its database, or strategy status. A historical score is
assumed known only on the following calendar date because kickoff/settlement
timestamps are unavailable. Same-day matches cannot train each other.
"""
from __future__ import annotations
import argparse, collections, datetime as dt, hashlib, json, math, sqlite3
from pathlib import Path
from qualification_shadow_v2 import date_of, outcome, odds_value, price, metrics, block_lower

STAKE = 100
SELECTIONS = ('Home Win', 'Draw', 'Away Win')

def replay(rows, min_training=50, min_forward=20, roi_target=5.0):
    if min_training < 50: raise ValueError('minimum training must be at least 50')
    if min_forward < 1: raise ValueError('forward validation must be nonempty')
    days=collections.defaultdict(list)
    invalid_dates=0
    for r in rows:
        d=date_of(r.get('date'))
        if d is None:
            invalid_dates+=1
            continue
        days[d].append(r)
    histories=collections.defaultdict(list)
    forward=collections.defaultdict(list)
    first_eligible={}
    invalid=collections.Counter()
    evaluated_days=0
    for day in sorted(days):
        # Predictions are registered before outcomes from the same day are revealed.
        for r in sorted(days[day],key=lambda x:str(x.get('id',''))):
            sheet=r.get('sheet')
            if sheet not in range(1,8): continue
            for market,col in (('Draw','drawOdds'),('Away','awayOdds')):
                v=odds_value(r.get(col))
                if v is None: continue
                trigger=f'{v:.2f}'
                for sel in SELECTIONS:
                    key=f'{sheet}|{market}|{trigger}|{sel}'
                    # A candidate is discovered only from earlier calendar days.
                    if len(histories[key]) < min_training: continue
                    actual=outcome(r.get('score'))
                    if actual is None: continue
                    bet_odds=price(r,sel)
                    if bet_odds is None:
                        invalid[key]+=1
                        continue
                    profit=round(STAKE*(bet_odds-1),2) if actual==sel else -STAKE
                    forward[key].append((day,str(r.get('id')),profit,bet_odds,actual==sel))
        # End-of-day results become available to later days only.
        for r in days[day]:
            sheet=r.get('sheet')
            if sheet not in range(1,8): continue
            actual=outcome(r.get('score'))
            if actual is None: continue
            for market,col in (('Draw','drawOdds'),('Away','awayOdds')):
                v=odds_value(r.get(col))
                if v is None: continue
                for sel in SELECTIONS:
                    key=f'{sheet}|{market}|{v:.2f}|{sel}'
                    bet_odds=price(r,sel)
                    if bet_odds is None:
                        invalid[key]+=1
                        continue
                    profit=round(STAKE*(bet_odds-1),2) if actual==sel else -STAKE
                    histories[key].append((day,str(r.get('id')),profit,bet_odds,actual==sel))
                    if len(histories[key]) == min_training:
                        first_eligible[key]=day
        evaluated_days+=1
    # Candidate family is defined by all tested combinations, not just winning ones.
    family_size=sum(len(v)>=min_training for v in histories.values())
    results=[]
    for key,train in sorted(histories.items()):
        if len(train)<min_training: continue
        fwd=forward[key]
        hist=metrics(train); val=metrics(fwd)
        # Exploratory inference, not independent evidence: train includes all history.
        seed=int(hashlib.sha256(key.encode()).hexdigest()[:12],16)
        lower=block_lower([x[2] for x in train],seed,alpha=.05/max(1,family_size),reps=1000)
        gates={
          'data': {'pass':len(train)>=50 and invalid[key]==0,'invalid':invalid[key]},
          'historical_roi': {'pass':hist['roi_pct'] is not None and hist['roi_pct']>=roi_target,'roi_pct':hist['roi_pct']},
          'statistical': {'pass':lower is not None and lower>0,'exploratory_lower_mean_profit':lower,'warning':'full historical data reused; not activation evidence'},
          'forward': {'pass':len(fwd)>=min_forward and val['roi_pct'] is not None and val['roi_pct']>0,'forward_matches':len(fwd),'forward_roi_pct':val['roi_pct']},
          'risk': {'pass':False,'reason':'risk limits not independently calibrated'},
          'stability': {'pass':False,'reason':'deterioration limits not independently calibrated'}
        }
        results.append({'key':key,'first_eligible_day':first_eligible[key],
          'status':'PROBATION' if len(fwd)>=min_forward else 'CANDIDATE',
          'historical':hist,'forward_after_eligibility':val,'gates':gates,
          'evidence_match_ids':sorted({x[1] for x in train}),
          'activation_authorized':False})
    return {'engine':'v2-chronological-discovery-replay','mode':'shadow-read-only',
      'activation_authorized':False,'assumption':'scores available no earlier than following calendar day',
      'limitation':'no historical odds-as-known timestamps; candidate discovery is replayed but not proof of tradable forward returns',
      'excluded_invalid_date_rows':invalid_dates,'processed_dates':evaluated_days,
      'candidate_family_size':family_size,'strategies':results}

def run(db_path, output_path):
    conn=sqlite3.connect(f'file:{Path(db_path).resolve()}?mode=ro&immutable=1',uri=True)
    conn.row_factory=sqlite3.Row
    try: rows=[dict(r) for r in conn.execute('SELECT id,sheet,date,homeOdds,drawOdds,awayOdds,score FROM matches')]
    finally: conn.close()
    result=replay(rows)
    Path(output_path).write_text(json.dumps(result,indent=2),encoding='utf-8')
    return result

if __name__=='__main__':
    parser=argparse.ArgumentParser()
    parser.add_argument('--database',type=Path,default=Path(__file__).with_name('football_analytics.db'))
    parser.add_argument('--output',type=Path,required=True)
    args=parser.parse_args()
    r=run(args.database,args.output)
    print(f"Shadow replay: {r['candidate_family_size']} candidate keys, activation disabled")
