"""Independent, read-only v2 shadow evaluator. Does not authorize promotions.

Run: python qualification_shadow_v2.py --output path/to/report.json
Historical outcomes are used for retrospective diagnostics only; results are NOT
prospective out-of-sample proof because original candidate discovery used all data.
"""
from __future__ import annotations
import argparse, collections, datetime as dt, hashlib, json, math, random, sqlite3
from pathlib import Path

BASE=Path(__file__).resolve().parent
STAKE=100

def date_of(s):
    for fmt in ('%Y-%m-%d','%d/%m/%y','%d/%m/%Y','%d-%m-%Y','%d.%m.%Y'):
        try: return dt.datetime.strptime(str(s or '').strip(),fmt).date().isoformat()
        except ValueError: pass
    return None

def outcome(s):
    import re
    m=re.fullmatch(r'\s*(\d+)\s*[-:–]\s*(\d+)\s*',str(s or ''))
    if not m:return None
    a,b=map(int,m.groups())
    return 'Home Win' if a>b else 'Away Win' if a<b else 'Draw'

def odds_value(x):
    try:
        v=float(x)
        return v if math.isfinite(v) and v>1 else None
    except (ValueError,TypeError):return None

def price(row,selection):
    return odds_value(row[{'Home Win':'homeOdds','Draw':'drawOdds','Away Win':'awayOdds'}[selection]])

def bets(rows,selection):
    result=[];bad=[]
    for row in rows:
        o=outcome(row['score'])
        if o is None:continue
        v=price(row,selection)
        if v is None or date_of(row['date']) is None:
            bad.append(str(row['id']));continue
        p=round(STAKE*(v-1),2) if o==selection else -STAKE
        result.append((date_of(row['date']),str(row['id']),p,v,o==selection))
    result.sort(key=lambda x:(x[0],x[1]))
    return result,bad

def metrics(items):
    profits=[x[2] for x in items];n=len(profits);balance=peak=dd=0.;streak=worst=0
    for p in profits:
        balance+=p;peak=max(peak,balance);dd=max(dd,peak-balance)
        streak=streak+1 if p<0 else 0;worst=max(worst,streak)
    return {'settled':n,'wins':sum(x[4] for x in items),'net_profit':round(sum(profits),2),
        'roi_pct':round(sum(profits)/n,4) if n else None, # 100 stake => per-bet profit equals ROI percent
        'max_drawdown':round(dd,2),'max_losing_streak':worst,
        'recent_20_profit':round(sum(profits[-20:]),2) if n>=20 else None,
        'recent_50_profit':round(sum(profits[-50:]),2) if n>=50 else None}

def block_lower(profits,seed,alpha=.05,reps=1000,block=5):
    n=len(profits)
    if n<2:return None
    rng=random.Random(seed);block=min(block,n);means=[]
    for _ in range(reps):
        sampled=[]
        while len(sampled)<n:
            j=rng.randrange(n)
            sampled.extend(profits[(j+k)%n] for k in range(block))
        means.append(sum(sampled[:n])/n)
    means.sort();return means[max(0,min(reps-1,int(alpha*reps)))]

def evaluate(rows,key,candidate_count,config):
    sheet,market,trigger,selection=key
    items,bad=bets(rows,selection)
    m=metrics(items);n=len(items)
    # Gate 4 uses first 50 settled matches as training and next 20 as a
    # retrospective holdout. Since candidate set was discovered using the full
    # database, this is NOT leakage-free walk-forward discovery.
    train=items[:50];holdout=items[50:70]
    lower=block_lower([x[2] for x in train],int(hashlib.sha256(str(key).encode()).hexdigest()[:12],16),
                      alpha=.05/max(1,candidate_count)) if len(train)>=50 else None
    g1=n>=50 and not bad
    g2=m['roi_pct'] is not None and m['roi_pct']>=config['roi_target_pct']
    g3=lower is not None and lower>0
    g4=len(holdout)==20 and metrics(holdout)['roi_pct']>0
    # Risk limits intentionally require explicit calibration before activation.
    g5=False
    g6=False
    gates=[{'name':'data eligibility','pass':g1,'invalid_settlements':len(bad)},
           {'name':'historical profitability','pass':g2,'target_roi_pct':config['roi_target_pct']},
           {'name':'statistical profitability','pass':g3,'training_lower_mean_profit':lower,
            'method':'seeded circular block bootstrap; Bonferroni candidate-count correction; exploratory only'},
           {'name':'chronological validation','pass':False,'retrospective_holdout_pass':g4,
            'reason':'full-database discovery leaks future candidate existence'},
           {'name':'risk protection','pass':g5,'reason':'risk limits not calibrated'},
           {'name':'stability','pass':g6,'reason':'deterioration thresholds not calibrated'}]
    return {'key':f'{sheet}|{market}|{trigger:.2f}|{selection}', 'status':'CANDIDATE' if n<50 else 'PROBATION',
            'activation_authorized':False,'metrics':m,'training_matches':len(train),
            'retrospective_holdout_matches':len(holdout),'gates':gates}

def run(db,output):
    uri=f'file:{db.resolve()}?mode=ro&immutable=1'
    con=sqlite3.connect(uri,uri=True);con.row_factory=sqlite3.Row
    try: rows=[dict(r) for r in con.execute('SELECT id,sheet,date,homeOdds,drawOdds,awayOdds,score FROM matches')]
    finally:con.close()
    groups=collections.defaultdict(list)
    for r in rows:
        if r['sheet'] not in range(1,8):continue
        for market,column in (('Draw','drawOdds'),('Away','awayOdds')):
            v=odds_value(r[column])
            if v is not None:groups[(r['sheet'],market,round(v,2))].append(r)
    # Include only groups that have 50 settled observations, matching existing discovery prefilter.
    candidates=[(group,selection,rs) for group,rs in groups.items()
                if sum(outcome(r['score']) is not None for r in rs)>=50
                for selection in ('Home Win','Draw','Away Win')]
    result={'engine':'v2-shadow-diagnostics','mode':'read-only','activation_authorized':False,
            'disclaimer':'NOT leakage-free forward validation; no status changes or promotions',
            'database_match_count':len(rows),'discovered_candidate_count':len(candidates),
            'strategies':[evaluate(rs,(*group,selection),len(candidates),{'roi_target_pct':5.0})
                          for group,selection,rs in candidates]}
    output.parent.mkdir(parents=True,exist_ok=True)
    output.write_text(json.dumps(result,indent=2),encoding='utf-8')
    return result

if __name__=='__main__':
    ap=argparse.ArgumentParser();ap.add_argument('--database',type=Path,default=BASE/'football_analytics.db')
    ap.add_argument('--output',type=Path,required=True);a=ap.parse_args()
    result=run(a.database,a.output)
    print('Shadow report generated:',len(result['strategies']),'strategies; activation disabled')
