
"""Corrected Plan 2 decision replay.

Research verification only.
Never records decisions or changes strategy status.
"""

from __future__ import annotations
from datetime import date
import math
import re

OUTCOMES = ('Home Win', 'Draw', 'Away Win')

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}|\d{4})(?:[T\s].*)?$'
)

SCORE = re.compile(r'^(\d+)\s*[-:?]\s*(\d+)$')


def day(value):
    s = str(value or '').strip()
    a = YMD.fullmatch(s)
    b = DMY.fullmatch(s)

    try:
        if a:
            year, month, d = map(int, a.groups())
        elif b:
            d, month, year = map(int, b.groups())
            if year < 100:
                year += 1900 if year >= 70 else 2000
        else:
            return None

        return date(year, month, d).toordinal()
    except ValueError:
        return None


def result(row):
    m = SCORE.fullmatch(
        str(row.get('score') or '').strip()
    )

    if m:
        h, a = int(m[1]), int(m[2])
        return (
            'Home Win' if h > a
            else 'Away Win' if h < a
            else 'Draw'
        )

    value = row.get('result')
    return value if value in OUTCOMES else None


def market_odd(row, market):
    choices = {
        'Home': ('home', 'homeOdds', 'homeWin', '1'),
        'Draw': ('draw', 'drawOdds', 'x'),
        'Away': ('away', 'awayOdds', 'awayWin', '2')
    }[market]

    values = row.get('odds') or row

    for field in choices:
        val = values.get(field)

        if val is None or val == '':
            continue

        try:
            number = float(val)
        except (ValueError, TypeError):
            continue

        if math.isfinite(number) and number > 1:
            return number

    return None


def odd(row, prediction):
    market = {
        'Home Win': 'Home',
        'Draw': 'Draw',
        'Away Win': 'Away'
    }[prediction]

    return market_odd(row, market)


def key(rule):
    return (
        f"{int(rule['sheet'])}|"
        f"{rule['market']}|"
        f"{float(rule['odds']):.2f}|"
        f"{rule['selection']}"
    )


def firing_rules(match, active_rules):
    """One exact-odds matcher for replay and forward decisions."""
    try:
        sheet = int(match.get(
            'sheet', match.get('sourceSheet')
        ))
    except (TypeError, ValueError):
        return []

    hits = []

    for rule in active_rules:
        if sheet != int(rule['sheet']):
            continue

        price = market_odd(match, rule['market'])

        if (
            price is not None
            and f'{price:.2f}' == f"{float(rule['odds']):.2f}"
        ):
            hits.append(rule)

    return hits


def combos(rows, qualified):
    seen = set()
    output = []

    for match in rows:
        match_id = str(match.get('id') or '')

        if not match_id or match_id in seen:
            raise ValueError('Missing or duplicate Match ID')

        seen.add(match_id)
        fired = firing_rules(match, qualified)

        if len(fired) >= 2:
            output.append({
                'match': match,
                'hits': fired,
                'combo': tuple(sorted(
                    key(rule) for rule in fired
                ))
            })

    return output

def grade(history, prediction, round_js):
    wins = 0
    net = 0.0
    complete = True

    for row in history:
        match = row['match'] if 'match' in row else row

        if result(match) == prediction:
            wins += 1
            price = odd(match, prediction)

            if price is None:
                complete = False
            else:
                net += round_js((price-1)*100)
        else:
            net -= 100

    return {
        'wins': wins,
        'net': round_js(net) if complete else None,
        'roi': (
            round_js(net/len(history))
            if complete and history else None
        )
    }


def finite(value):
    return (
        float(value)
        if isinstance(value, (float, int))
        and math.isfinite(value)
        else -math.inf
    )


def rankitem(item):
    return (
        -finite(item.get('wins')),
        -finite(item.get('net')),
        -finite(item.get('roi')),
        -finite(item.get('score')),
        item['key']
    )


def choose(target, allrows, matches, shadow, *, forward=False):
    """Select the most frequent ACTUAL result of the exact fired strategy set.

    Unlike the old implementation, the choice may be Home, Draw or Away
    regardless of which outcomes the triggered strategies themselves signal.
    Historical rows use the full combination, including the target;
    forward capture sees settled evidence saved as of decision time.
    """
    # Historical rows use the entire exact settled combination.
    signals = sorted({
        r['selection'] for r in target['hits']
        if r['selection'] in OUTCOMES
    })
    zero = {outcome: 0 for outcome in OUTCOMES}
    target_id = str(target['match']['id'])

    # Only an IDENTICAL set of triggered Active rules contributes evidence.
    # Matching merely the signalled Home/Draw outcomes is insufficient.
    history_by_id = {
        str(other['match']['id']): other
        for other in allrows
        if (not forward or str(other['match']['id']) != target_id)
        and other['combo'] == target['combo']
        and result(other['match']) in OUTCOMES
    }
    history = list(history_by_id.values())
    counts = {
        outcome: sum(result(item['match']) == outcome for item in history)
        for outcome in OUTCOMES
    }

    common = {
        'history': len(history), 'eligible': signals,
        'outcomeCounts': counts
    }
    if not history:
        # DO NOT silently fall back to performance of individual strategies:
        # that isn't evidence for this particular multi-trigger combination.
        return {
            **common, 'prediction': None,
            'profitByOutcome': {}, 'reason': 'NO_SETTLED_COMBINATION_MATCHES'
        }

    maximum = max(counts.values())
    leaders = [x for x in OUTCOMES if counts[x] == maximum]
    if len(leaders) == 1:
        return {
            **common, 'prediction': leaders[0],
            'profitByOutcome': {}, 'reason': 'MAX_ACTUAL_RESULT_WINS'
        }

    # Tie: simulate the same GH₵100 stake on EACH tied outcome over every
    # settled historical match, using that match's own outcome odds.
    profits = {
        outcome: grade(history, outcome, shadow._round_js)['net']
        for outcome in leaders
    }
    if any(profit is None for profit in profits.values()):
        return {
            **common, 'prediction': None, 'profitByOutcome': profits,
            'reason': 'TIED_WINS_MISSING_ODDS'
        }

    best_profit = max(profits.values())
    winners = [x for x in leaders if profits[x] == best_profit]
    if len(winners) != 1:
        return {
            **common, 'prediction': None, 'profitByOutcome': profits,
            'reason': 'TIED_WINS_AND_EQUAL_PROFIT'
        }

    return {
        **common, 'prediction': winners[0],
        'profitByOutcome': profits,
        'reason': 'MAX_WINS_PROFIT_TIEBREAK'
    }


def preview(rows, shadow, db=None):
    qualification = shadow.preview(rows)

    grouped = combos(
        rows, qualification['qualified']
    )

    choices = []

    for entry in grouped:
        choice = choose(
            entry, grouped, rows, shadow
        )

        choices.append({
            'matchId': entry['match']['id'],
            'matchDate': entry['match'].get('date'),
            'prediction': choice['prediction'],
            'history': choice['history'],
            'reason': choice['reason'],
            'eligible': sorted({r['selection'] for r in entry['hits']}),
            'outcomeCounts': choice['outcomeCounts'],
            'profitByOutcome': choice['profitByOutcome'],
            'comboKeys': list(entry['combo'])
        })

    output = {
        'phase': 'C3-RESEARCH-REPLAY-ONLY',
        'decisionCaptureEnabled': False,
        'historicalRecordsAuthoritative': False,
        'matchCount': len(rows),
        'datasetHash': qualification['datasetHash'],
        'qualifiedStrategies':
            qualification['qualifiedCount'],
        'multiTriggerRows': len(grouped),
        'noHistoryFallbacks': sum(
            x['history'] == 0 for x in choices
        ),
        'unavailable': sum(
            x['prediction'] is None for x in choices
        ),
        'choices': choices
    }

    if db is not None:
        metadata = db.execute(
            'SELECT schema_version,capture_state '
            'FROM prediction_ledger_metadata '
            'WHERE singleton=1'
        ).fetchone()

        if (
            not metadata
            or metadata['schema_version'] != 'C2-V1'
            or metadata['capture_state'] not in ('NOT_ENABLED','LIVE')
        ):
            raise ValueError(
                'C2 ledger state invalid'
            )

        output['decisionCaptureEnabled'] = metadata['capture_state'] == 'LIVE'

        output['storedDecisions'] = db.execute(
            'SELECT COUNT(*) '
            'FROM prediction_decision_ledger'
        ).fetchone()[0]

        output['storedSettlements'] = db.execute(
            'SELECT COUNT(*) '
            'FROM prediction_settlement_events'
        ).fetchone()[0]

    return output



def preview_forward_decision(rows, active_rules, match_id, *, shadow):
    """Read-only Plan 1/Plan 2 preview. No timezone or database writes."""

    if not isinstance(rows, list) or not isinstance(active_rules, list):
        raise ValueError("Matches and Active rules required")

    found = [
        m for m in rows
        if str(m.get("id") or "") == str(match_id)
    ]

    if len(found) != 1:
        raise ValueError("Match ID missing or duplicated")

    target = found[0]

    base = {
        "mode": "RESEARCH_PREVIEW_ONLY",
        "matchId": str(match_id),
        "date": target.get("date"),
        "kickoff": target.get("kickoffTime")
    }

    if result(target) is not None:
        return {
            **base,
            "plan": None,
            "prediction": None,
            "reason": "SETTLED_MATCH_RESEARCH_ONLY"
        }

    ids = [key(r) for r in active_rules]

    if len(set(ids)) != len(ids) or any(
        r.get("key", key(r)) != key(r)
        for r in active_rules
    ):
        raise ValueError("Duplicate or invalid Active strategies")

    fired = firing_rules(target, active_rules)
    eligible = sorted({r["selection"] for r in fired})

    if any(v not in OUTCOMES for v in eligible):
        raise ValueError("Invalid strategy selection")

    base.update(
        eligible=eligible,
        fired=sorted(key(r) for r in fired)
    )

    if not fired:
        return {
            **base,
            "plan": None,
            "prediction": None,
            "reason": "NO_ACTIVE_STRATEGY"
        }

    if len(fired) == 1:
        selection = fired[0]["selection"]

        return {
            **base,
            "plan": "PLAN1",
            "prediction": selection,
            "selectedOdds": odd(target, selection),
            "reason": "SINGLE_ACTIVE_STRATEGY"
        }

    # Reuse existing historical-wins calculation.
    # Do not assume unverified same-day results were known.
    grouped = combos(rows, active_rules)

    combo = next(
        (
            x for x in grouped
            if str(x["match"].get("id")) == str(match_id)
        ),
        None
    )

    if combo is None:
        raise ValueError("Strategy combination missing")

    choice = choose(combo, grouped, rows, shadow, forward=True)
    selection = choice.get("prediction")

    # Plan 2 is allowed to select ANY actual outcome, including a market
    # that none of the triggered strategies originally predicted.
    if selection is not None and selection not in OUTCOMES:
        raise ValueError("Invalid selected match outcome")

    # The selected third outcome may have no quoted odds on the target.
    # It is a valid research finding but cannot become a priced official bet.
    chosen_odds = odd(target, selection) if selection else None
    if selection is not None and chosen_odds is None:
        return {
            **base, "plan": None, "routingPlan": "PLAN2",
            "prediction": None, "selectedOdds": None,
            "history": choice["history"],
            "outcomeCounts": choice['outcomeCounts'],
            "reason": "SELECTED_OUTCOME_ODDS_UNAVAILABLE"
        }

    # A zero-history or unresolved tie is not a defensible official pick.
    return {
        **base,
        "plan": "PLAN2" if selection else None,
        "routingPlan": "PLAN2",
        "prediction": selection,
        "selectedOdds": chosen_odds,
        "history": choice["history"],
        "outcomeCounts": choice['outcomeCounts'],
        "reason": choice["reason"]
    }
