
"""Phase B shadow qualification preview. PURE READ MODEL, never writes data.

Parity target: strategy-lifecycle.js five-gate evaluate() released 2026-11-15.
This is deliberately NOT an authoritative promotion or lifecycle writer.
"""
from __future__ import annotations
import datetime as _dt
import hashlib
import math
import re

_OUTCOMES = ('Home Win', 'Draw', 'Away Win')
_MARKETS = ('Draw', 'Away')
_REF = {'roi': 47.69, 'recent20': 2265.0, 'settled': 85.0, 'net': 3100.0}
_SCORE = re.compile(r'^(\d+)\s*[-:–]\s*(\d+)$')
_YMD = re.compile(r'^(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})(?:[T\s].*)?$')
_DMY = re.compile(r'^(\d{1,2})[\/.-](\d{1,2})[\/.-](\d{2,4})(?:[T\s].*)?$')

def _round_js(number):
    return math.floor((number + 2**-52)*100 + 0.5)/100

def _outcome(row):
    score = _SCORE.fullmatch(str(row.get('score') or '').strip())
    if score:
        home, away = int(score[1]), int(score[2])
        return (
            'Home Win' if home > away
            else 'Away Win' if home < away
            else 'Draw'
        )
    result = row.get('result')
    return result if result in _OUTCOMES else 'Upcoming'

def _odd(row, market):
    keys = {
        'Home': ('home', 'homeOdds', 'homeWin', '1'),
        'Draw': ('draw', 'drawOdds', 'x'),
        'Away': ('away', 'awayOdds', 'awayWin', '2')
    }[market]
    d = row.get('odds') or row
    for k in keys:
        val = d.get(k)
        if val is None or val == '':
            continue
        try:
            value = float(val)
        except (ValueError, TypeError):
            continue
        if math.isfinite(value) and value > 1:
            return value
    return math.nan

def _day(row):
    s = str(row.get('date') or row.get('matchDate') or '').strip()
    ymd = _YMD.fullmatch(s)
    dmy = _DMY.fullmatch(s)
    try:
        if ymd:
            year, month, day = map(int, ymd.groups())
        elif dmy:
            day, month, year = map(int, dmy.groups())
            if year < 100:
                year += 1900 if year >= 70 else 2000
        else:
            return 0
        return (
            _dt.date(year, month, day) -
            _dt.date(1970, 1, 1)
        ).days
    except ValueError:
        return 0

def _metrics(rule, hits):
    settled = [
        m for m in hits if _outcome(m) in _OUTCOMES
    ]
    pick_market = (
        'Home' if rule['selection'] == 'Home Win'
        else 'Draw' if rule['selection'] == 'Draw'
        else 'Away'
    )

    wins = 0
    net = 0
    complete = True
    ledger = []

    for index, match in enumerate(settled):
        won = _outcome(match) == rule['selection']
        wins += bool(won)

        if won:
            price = _odd(match, pick_market)
            profit = (
                _round_js((price-1)*100)
                if math.isfinite(price) else None
            )
        else:
            profit = -100

        if profit is None:
            complete = False
        else:
            net += profit

        ledger.append((_day(match), index, profit))

    ledger.sort(key=lambda t: (t[0], t[1]))

    recent = [p for _, _, p in ledger[-20:]]
    recent20 = (
        None if None in recent
        else _round_js(sum(recent))
    )

    net = _round_js(net) if complete else None
    count = len(settled)
    roi = (
        net/(count*100)*100
        if complete and count else None
    )

    perf = None
    if (
        complete
        and roi is not None
        and net is not None
        and recent20 is not None
    ):
        def clamp(x):
            return max(0.0, min(100.0, x))

        perf = _round_js(
            .40*clamp(roi/_REF['roi']*100)
            + .35*clamp(recent20/_REF['recent20']*100)
            + .15*clamp(math.sqrt(count/_REF['settled'])*100)
            + .10*clamp(net/_REF['net']*100)
        )

    qualifies = (
        complete
        and count >= 50
        and net is not None and net > 1000
        and roi is not None and roi > 0
        and recent20 is not None and recent20 > 0
        and perf is not None and perf >= 50
    )

    return {
        'matches':len(hits),
        'settled':count,
        'wins':wins,
        'losses':count-wins,
        'complete':complete,
        'net':net,
        'roi':roi,
        'recent20':recent20,
        'performanceScore':perf,
        'qualified':qualifies
    }

def _fingerprint(rows):
    payload = '\n'.join(
        str(m['id'])+'|'+str(
            m.get('revision')
            if m.get('revision') is not None else ''
        )
        for m in rows
    )
    return hashlib.sha256(
        payload.encode('utf-8')
    ).hexdigest()

def preview(rows):
    if not isinstance(rows, list):
        raise TypeError('Expected a canonical match list')

    groups = {}

    for row in rows:
        try:
            sheet = int(
                row.get('sourceSheet')
                if row.get('sourceSheet') is not None
                else row.get('sheet')
            )
        except (ValueError, TypeError):
            continue

        if sheet < 1 or sheet > 7:
            continue

        for market in _MARKETS:
            odds = _odd(row, market)
            if not math.isfinite(odds):
                continue

            group = (sheet, market, f'{odds:.2f}')
            groups.setdefault(group, []).append(row)

    active = []
    candidates = 0

    for (sheet, market, odds), matches in groups.items():
        for selection in _OUTCOMES:
            rule = {
                'id':f"EM-{sheet}-{market}-{odds}-{selection.replace(' ', '-')}",
                'sheet':sheet,
                'market':market,
                'odds':float(odds),
                'selection':selection
            }

            metrics = _metrics(rule, matches)

            if metrics['settled']>=50 and metrics['complete']:
                candidates += 1

            if metrics['qualified']:
                active.append({
                    'key':f'{sheet}|{market}|{odds}|{selection}',
                    **rule,
                    'metrics':metrics
                })

    active.sort(
        key=lambda r: (
            r['sheet'],r['market'],r['odds'],r['selection']
        )
    )

    return {
        'phase':'B1-SHADOW-ONLY',
        'source':'live-sqlite-read-only',
        'rules':'five-gate-v1',
        'matchCount':len(rows),
        'datasetHash':_fingerprint(rows),
        'sampleEligible':candidates,
        'qualifiedCount':len(active),
        'qualified':active,
        'note':'Qualification preview only. Does NOT replace active browser registrations or perform promotion/demotion.'
    }

