"""Authenticated HTTP read-model for V2 shadow lifecycle.

This module does not compute or alter live strategy status. It reads the
separate audit registry, never the matches DB, and surfaces provenance.
"""
from __future__ import annotations
import sqlite3
from contextlib import closing
import json
from pathlib import Path

ALLOWED = {'CANDIDATE','PROBATION','ACTIVE','DEMOTED'}

def snapshot(registry_path: Path):
    p = Path(registry_path)
    if p.name == 'football_analytics.db':
        raise ValueError('V2 registry must be separate from match database')
    if not p.is_file():
        return {'ok':True,'mode':'shadow-only','integrated':False,'ready':False,
                'reason':'No shadow evaluation registry generated yet',
                'strategies':[],'history':[],'counts':{s:0 for s in sorted(ALLOWED)}}
    with closing(sqlite3.connect(f'file:{p.resolve()}?mode=ro', uri=True)) as conn, conn:
        conn.row_factory=sqlite3.Row
        names={row['name'] for row in conn.execute("SELECT name FROM sqlite_master WHERE type='table'")}
        if not {'lifecycle_current','lifecycle_history'}.issubset(names):
            return {'ok':True,'mode':'shadow-only','integrated':False,'ready':False,
                    'reason':'Lifecycle tables not initialized',
                    'strategies':[],'history':[],'counts':{s:0 for s in sorted(ALLOWED)}}
        strategies=[dict(r) for r in conn.execute('''SELECT strategy_key,status,revision,
            last_transition_utc,prior_active FROM lifecycle_current ORDER BY strategy_key''')]
        # Attach evidence only from the same revision as the lifecycle record.
        # Older assessments must never masquerade as current qualification.
        if 'strategy_evaluations' in names:
            assessments = {(r['strategy_key'],r['revision']):dict(r) for r in conn.execute(
                'SELECT strategy_key,revision,historical_roi,forward_roi,gates_json FROM strategy_evaluations')}
            for strategy in strategies:
                assessment=assessments.get((strategy['strategy_key'],strategy['revision']))
                if assessment is None:
                    strategy['evidence_available']=False
                    strategy['gates']=None
                    strategy['historical_roi']=None
                    strategy['forward_roi']=None
                else:
                    strategy['evidence_available']=True
                    strategy['gates']=json.loads(assessment['gates_json'])
                    strategy['historical_roi']=assessment['historical_roi']
                    strategy['forward_roi']=assessment['forward_roi']
        else:
            for strategy in strategies:
                strategy.update(evidence_available=False,gates=None,historical_roi=None,forward_roi=None)
        history=[dict(r) for r in conn.execute('''SELECT strategy_key,revision,from_status,
            to_status,reason,created_utc FROM lifecycle_history ORDER BY id DESC LIMIT 200''')]
    counts={s:sum(r['status']==s for r in strategies) for s in sorted(ALLOWED)}
    return {'ok':True,'mode':'shadow-only','integrated':False,'ready':True,
            'activation_authorized':False,'strategies':strategies,
            'history':history,'counts':counts,
            'warning':'Shadow evaluations are NOT authoritative live strategy decisions'}
