"""Versioned, idempotent, auditable SHADOW evaluation store.

This is deliberately separate from the live match DB and cannot change the
active registry. The snapshot is an assessment, NOT a production activation.
"""
from __future__ import annotations
import argparse
import datetime as dt
import hashlib
import json
import sqlite3
from contextlib import closing
from pathlib import Path
from qualification_walkforward_v2 import run as evaluate

SCHEMA = '''
CREATE TABLE IF NOT EXISTS evaluation_runs (
  revision TEXT PRIMARY KEY, engine_version TEXT NOT NULL,
  created_utc TEXT NOT NULL, candidate_count INTEGER NOT NULL,
  assessment_json TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS strategy_evaluations (
  revision TEXT NOT NULL REFERENCES evaluation_runs(revision),
  strategy_key TEXT NOT NULL, status TEXT NOT NULL,
  historical_roi REAL, forward_roi REAL,
  gates_json TEXT NOT NULL,
  PRIMARY KEY(revision, strategy_key)
);
CREATE TABLE IF NOT EXISTS registry_events (
  event_id INTEGER PRIMARY KEY AUTOINCREMENT,
  revision TEXT NOT NULL, strategy_key TEXT NOT NULL,
  event_type TEXT NOT NULL CHECK(event_type='SHADOW_EVALUATED'),
  created_utc TEXT NOT NULL,
  UNIQUE(revision, strategy_key, event_type)
);
'''

def save_report(report, registry_path, revision):
    if report.get('activation_authorized') is not False or report.get('mode') != 'shadow-read-only':
        raise ValueError('Only explicitly nonactivating shadow reports may be persisted')
    registry_path=Path(registry_path)
    if registry_path.name == 'football_analytics.db':
        raise ValueError('Refusing to write to the live matches database')
    registry_path.parent.mkdir(parents=True, exist_ok=True)
    now=dt.datetime.now(dt.timezone.utc).isoformat()
    with closing(sqlite3.connect(registry_path)) as con, con:
        con.execute('PRAGMA foreign_keys=ON')
        con.executescript(SCHEMA)
        with con:
            cursor=con.execute('INSERT OR IGNORE INTO evaluation_runs VALUES (?,?,?,?,?)',
                (revision, report['engine'], now, report['candidate_family_size'], json.dumps(report,sort_keys=True)))
            if cursor.rowcount == 0:
                return {'revision':revision,'new_run':False,'strategies':0}
            for item in report['strategies']:
                key=item['key']
                con.execute('INSERT INTO strategy_evaluations VALUES (?,?,?,?,?,?)',
                    (revision,key,item['status'],item['historical']['roi_pct'],
                     item['forward_after_eligibility']['roi_pct'],json.dumps(item['gates'],sort_keys=True)))
                con.execute('INSERT INTO registry_events (revision,strategy_key,event_type,created_utc) VALUES (?,?,?,?)',
                    (revision,key,'SHADOW_EVALUATED',now))
    return {'revision':revision,'new_run':True,'strategies':len(report['strategies'])}

def snapshot_hash(db_path):
    h=hashlib.sha256()
    with open(db_path,'rb') as stream:
        for block in iter(lambda:stream.read(1024*1024),b''):
            h.update(block)
    return h.hexdigest()

def main():
    ap=argparse.ArgumentParser(description='Read-only evaluation + separate shadow registry')
    ap.add_argument('--database',type=Path,required=True)
    ap.add_argument('--registry',type=Path,required=True)
    ap.add_argument('--report',type=Path,required=True)
    a=ap.parse_args()
    if a.database.resolve()==a.registry.resolve():
        ap.error('registry must not be the source database')
    before=snapshot_hash(a.database)
    result=evaluate(a.database,a.report)
    after=snapshot_hash(a.database)
    if before!=after:
        raise RuntimeError('Source database changed during evaluation; refusing persistence')
    revision=hashlib.sha256(('v2-chronological-discovery-replay:'+before).encode()).hexdigest()
    print(json.dumps(save_report(result,a.registry,revision),indent=2))

if __name__=='__main__': main()
