#!/usr/bin/env python3
"""Evaluate a local MatchPrior paper-tracking record without network access.

Python 3.9+, standard library only. No API key is needed.
  python evaluate_research.py --predictions private-football.jsonl \
    --outcomes outcomes.csv --report research-report.json --rows research-rows.csv
  Add --quotes private-odds.jsonl for compare_odds.py history, or
  --quotes matchprior-comparisons.json for an account-workspace JSON export.

Outcome CSV columns: fixtureId,status,actual,outcomeBasis,observedAt,source,verified
Optional columns: sourcePublishedAt,sourcePublicationTimeVerified
Use completed / H,D,A for a verified completed result. Other statuses stay
excluded. outcomeBasis is regulation_time_1x2 (reviewed domestic football) or
completed_match_winner (ATP/WTA). Times must be UTC ISO timestamps ending in Z.
Verification fields are your declarations; this offline tool cannot verify a
provider, acquisition clock, publication time or licence. Preserve the originals.
Output paths must be new files in a private local folder.
"""
import argparse
import csv
from datetime import datetime, timezone, timedelta
import hashlib
import io
import json
import math
import os
from pathlib import Path
import re
import stat
import sys

MAX_BYTES = 32 * 1024 * 1024
MAX_LINE = 1024 * 1024
MAX_ROWS = 50_000
MAX_PACKET_QUOTES = 50
OUTCOMES = ('H', 'D', 'A')
FOOTBALL = {'E0', 'SP1', 'I1', 'D1', 'F1', 'BRA', 'NOR', 'SWE', 'FIN', 'IRL',
            'E1', 'N1', 'P1', 'B1', 'E2', 'E3', 'SC0', 'T1', 'G1'}
STATUSES = {'completed', 'pending', 'postponed', 'cancelled', 'void', 'retired', 'walkover', 'unknown', 'aborted'}
REQUIRED_RESULTS = {'fixtureId', 'status', 'actual', 'outcomeBasis', 'observedAt', 'source', 'verified'}
OPTIONAL_RESULTS = {'sourcePublishedAt', 'sourcePublicationTimeVerified'}


class ResearchError(Exception):
    """A safe error message containing no supplied input values."""


def canonical(value):
    return json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=False, allow_nan=False)


def digest(value):
    return hashlib.sha256(canonical(value).encode('utf-8')).hexdigest()


def finite_float(value):
    result = float(value)
    if not math.isfinite(result):
        raise ValueError('Non-finite number')
    return result


def json_object(raw):
    def unique(pairs):
        result = {}
        for key, value in pairs:
            if key in result:
                raise ValueError('Duplicate JSON key')
            result[key] = value
        return result
    try:
        value = json.loads(raw, parse_float=finite_float,
                           parse_constant=lambda value: (_ for _ in ()).throw(ValueError()),
                           object_pairs_hook=unique)
        if not isinstance(value, dict):
            raise ValueError()
        return value
    except (ValueError, UnicodeError, RecursionError, OverflowError):
        raise ResearchError('Each JSONL record must be an object with unique fields and finite numbers.') from None


def read_input(path):
    target = Path(path).expanduser()
    if target.is_symlink() or not target.is_file():
        raise ResearchError('Input paths must be regular local files, not symbolic links.')
    with target.open('rb') as handle:
        raw = handle.read(MAX_BYTES + 1)
    if len(raw) > MAX_BYTES:
        raise ResearchError('Each input file must be no larger than 32 MiB.')
    if re.search(rb'mp_live_[A-Za-z0-9_-]{6,}', raw):
        raise ResearchError('Remove API credentials from input files before evaluation.')
    return raw


def records(raw):
    lines = [line for line in raw.splitlines() if line.strip()]
    if len(lines) > MAX_ROWS or any(len(line) > MAX_LINE for line in lines):
        raise ResearchError('JSONL input exceeds the row or per-record limit.')
    output = [json_object(line) for line in lines]
    for row in output:
        reject_secrets(row)
    return output


def reject_secrets(value, depth=0):
    if depth > 20:
        raise ResearchError('Input nesting exceeds the safety limit.')
    if isinstance(value, dict):
        for key, item in value.items():
            if re.search(r'(^|[_-])(password|secret|authorization|api[_-]?key|access[_-]?token|refresh[_-]?token)($|[_-])', key, re.I):
                raise ResearchError('Remove credentials and authentication fields from input files.')
            reject_secrets(item, depth + 1)
    elif isinstance(value, list):
        for item in value:
            reject_secrets(item, depth + 1)


def text(value, limit=512):
    if not isinstance(value, str) or not value.strip() or len(value) > limit or any(ord(c) < 32 or ord(c) == 127 for c in value):
        raise ResearchError('A required text field is missing, too long or contains control characters.')
    return value


def utc(value):
    if not isinstance(value, str) or not re.fullmatch(r'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?Z', value):
        raise ResearchError('Times must be valid UTC ISO timestamps ending in Z.')
    try:
        return datetime.fromisoformat(value[:-1] + '+00:00')
    except ValueError:
        raise ResearchError('A UTC timestamp has an invalid calendar date.') from None


def flag(value, blank=False):
    if value == 'true' or value is True:
        return True
    if value == 'false' or value is False or (blank and value in ('', None)):
        return False
    raise ResearchError('Verification fields must be true or false.')


def probabilities(value):
    if not isinstance(value, dict) or any(type(value.get(key)) not in (int, float)
          or not math.isfinite(value[key]) or not 0 <= value[key] <= 1 for key in OUTCOMES):
        raise ResearchError('Prediction probabilities must be finite H/D/A values between zero and one.')
    if abs(sum(value[key] for key in OUTCOMES) - 1) > 1e-6:
        raise ResearchError('Prediction probabilities must sum to one.')
    return {key: value[key] for key in OUTCOMES}


def expected_basis(fixture):
    if fixture['sport'] == 'football' and fixture['league'] in FOOTBALL:
        return 'regulation_time_1x2'
    if fixture['sport'] == 'tennis' and fixture['league'] in ('ATP', 'WTA'):
        return 'completed_match_winner'
    return None


def prediction(row, now):
    if type(row.get('schemaVersion')) is not int or row.get('schemaVersion') != 1 or not isinstance(row.get('fixture'), dict) or not isinstance(row.get('model'), dict):
        raise ResearchError('Predictions must use the paper_tracker.py schemaVersion 1 format.')
    fixture, model = row['fixture'], row['model']
    identity = text(row.get('fixtureId'))
    if identity != fixture.get('id') or row.get('sport') != fixture.get('sport'):
        raise ResearchError('Prediction fixture identities or sports disagree.')
    for key in ('sport', 'league', 'date', 'home', 'away'):
        text(fixture.get(key))
    try:
        if not re.fullmatch(r'\d{4}-\d{2}-\d{2}', fixture['date']) or datetime.strptime(fixture['date'], '%Y-%m-%d').date().isoformat() != fixture['date']:
            raise ValueError()
    except ValueError:
        raise ResearchError('The original fixture date must be a valid YYYY-MM-DD date.') from None
    if identity != '|'.join(fixture[key] for key in ('league', 'date', 'home', 'away')):
        raise ResearchError('An exact fixture identity does not match its original fixture fields.')
    start = fixture.get('startMs')
    if type(start) not in (int, float) or not math.isfinite(start) or abs(start) > 8_640_000_000_000_000:
        raise ResearchError('Each forecast needs its original finite scheduled start.')
    try:
        start_at = datetime.fromtimestamp(start / 1000, timezone.utc)
    except (ValueError, OSError, OverflowError):
        raise ResearchError('A scheduled start is outside the supported date range.') from None
    probs = probabilities(model.get('probs'))
    pick = model.get('pick')
    if pick not in OUTCOMES or type(model.get('confidence')) not in (int, float) or not math.isfinite(model['confidence']) or abs(model['confidence'] - probs[pick]) > 1e-8:
        raise ResearchError('The recorded pick and confidence must match its probabilities.')
    observed = utc(row.get('observedAt'))
    server = utc(row.get('serverObservedAt'))
    snapshot = utc(row.get('snapshotAt'))
    if observed > now or server > now or snapshot > now or snapshot > server:
        raise ResearchError('A forecast has future or inconsistent observation timestamps.')
    basis = row.get('observationBasis')
    if basis == 'historical_replay':
        cohort = 'historical_replay'
    elif basis == 'current_snapshot_observation':
        cohort = 'prospective_observation' if max(observed, server, snapshot) < start_at else 'retrospective_observation'
    else:
        raise ResearchError('Observation basis must be current_snapshot_observation or historical_replay.')
    provenance = model.get('provenance') if isinstance(model.get('provenance'), dict) else {}
    return {'fixtureId': identity, 'fixture': fixture, 'probs': probs, 'pick': pick,
            'confidence': model['confidence'], 'snapshotAt': row['snapshotAt'],
            'observedAt': row['observedAt'], 'serverObservedAt': row['serverObservedAt'],
            'observedTime': max(observed, server), 'startTime': start_at, 'cohort': cohort,
            'originalRowSha256': digest(row), 'snapshotContentSha256': digest({'fixture': fixture, 'model': model}),
            'modelVersion': text(provenance['modelVersion'], 200) if isinstance(provenance.get('modelVersion'), str) else None,
            'sourcePublicationTimesVerifiedDeclared': provenance.get('sourcePublicationTimesVerified') is True,
            'syntheticExampleDeclared': row.get('syntheticExample') is True,
            'recordedSettlement': model.get('settlement') if isinstance(model.get('settlement'), dict) else None}


def parse_results(raw, now):
    try:
        reader = csv.DictReader(io.StringIO(raw.decode('utf-8-sig'), newline=''))
        columns = reader.fieldnames or []
        if len(columns) != len(set(columns)) or not REQUIRED_RESULTS.issubset(columns) or set(columns) - REQUIRED_RESULTS - OPTIONAL_RESULTS:
            raise ResearchError('Outcome CSV has missing, duplicate or unsupported columns.')
        output = {}
        for count, row in enumerate(reader, 1):
            if count > MAX_ROWS or None in row or any(value is None for value in row.values()):
                raise ResearchError('Outcome CSV exceeds the row limit or has inconsistent columns.')
            reject_secrets(row)
            identity = text(row['fixtureId'])
            if row['status'] not in STATUSES or row['actual'] not in ('', *OUTCOMES):
                raise ResearchError('Outcome status or H/D/A result is invalid.')
            observed = utc(row['observedAt'])
            if observed > now:
                raise ResearchError('Outcome observation time is in the future.')
            text(row['source'], 200); text(row['outcomeBasis'], 100)
            verified = flag(row['verified'])
            publication_verified = flag(row.get('sourcePublicationTimeVerified'), blank=True)
            published = utc(row['sourcePublishedAt']) if row.get('sourcePublishedAt') else None
            if publication_verified and published is None or published and published > observed:
                raise ResearchError('Outcome publication timestamps or verification declarations are inconsistent.')
            evidence = {'status': row['status'], 'actual': row['actual'], 'outcomeBasis': row['outcomeBasis'],
                        'source': row['source'], 'observedAt': row['observedAt'], 'observedTime': observed,
                        'verifiedDeclared': verified, 'sourcePublishedAt': row.get('sourcePublishedAt') or None,
                        'sourcePublicationTimeVerifiedDeclared': publication_verified, 'sha256': digest(row)}
            output.setdefault(identity, []).append(evidence)
        return output
    except (UnicodeError, csv.Error):
        raise ResearchError('Outcome CSV must be valid UTF-8 with bounded fields.') from None


def score(probs, actual):
    return sum((probs[outcome] - (1 if actual == outcome else 0)) ** 2 for outcome in OUTCOMES)


def finite_number(value):
    return type(value) in (int, float) and math.isfinite(value)


def close_number(value, expected, tolerance=1e-9):
    return finite_number(value) and math.isclose(value, expected, rel_tol=1e-9, abs_tol=tolerance)


def account_response(response, now):
    """Validate an original comparison response; never use its model to replace
    a collected forecast. The response timestamp is still file-supplied evidence.
    """
    required = {'fixture', 'market', 'settlement', 'model', 'quote', 'comparison', 'comparedAt'}
    if not isinstance(response, dict) or set(response) != required:
        raise ResearchError('Account comparison responses have missing or unsupported fields.')
    reject_secrets(response)
    fixture, model, quote, comparison, settlement = (response[key] for key in ('fixture', 'model', 'quote', 'comparison', 'settlement'))
    if any(not isinstance(value, dict) for value in (fixture, model, quote, comparison, settlement)):
        raise ResearchError('Account comparison response objects are malformed.')
    fixture_fields = {'id', 'sport', 'league', 'date', 'time', 'home', 'away', 'startMs', 'surface', 'tournament', 'round', 'neutral', 'homeLogo', 'awayLogo'}
    if set(fixture) - fixture_fields:
        raise ResearchError('Account comparison fixture has unsupported fields.')
    for key in ('id', 'sport', 'league', 'date', 'home', 'away'):
        text(fixture.get(key))
    if fixture['id'] != '|'.join(fixture[key] for key in ('league', 'date', 'home', 'away')) or fixture['home'] == fixture['away']:
        raise ResearchError('Account comparison fixture identity is inconsistent.')
    try:
        if not re.fullmatch(r'\d{4}-\d{2}-\d{2}', fixture['date']) or datetime.strptime(fixture['date'], '%Y-%m-%d').date().isoformat() != fixture['date']:
            raise ValueError()
    except ValueError:
        raise ResearchError('Account comparison fixture date is invalid.') from None
    compared = utc(response['comparedAt'])
    start = fixture.get('startMs')
    if compared > now or not finite_number(start) or compared.timestamp() * 1000 >= start:
        raise ResearchError('Account comparison needs an original pre-start response timestamp and scheduled start.')
    market = response['market']
    basis = expected_basis(fixture)
    if basis == 'regulation_time_1x2' and market == 'football_1x2_regulation':
        outcomes = OUTCOMES
        expected_settlement = {'outcomeBasis': basis, 'includesStoppageTime': True, 'includesExtraTime': False,
                               'includesPenaltyShootout': False, 'cancelledOrAbandoned': 'excluded', 'bookmakerRules': 'must_match_model_basis'}
    elif basis == 'completed_match_winner' and market == 'tennis_match_winner':
        outcomes = ('H', 'A')
        expected_settlement = {'outcomeBasis': basis, 'retirements': 'excluded', 'walkovers': 'excluded',
                               'cancelledOrAbandoned': 'excluded', 'bookmakerRules': 'must_match_model_basis'}
    else:
        raise ResearchError('Account comparison sport, competition and market do not match.')
    if canonical(settlement) != canonical(expected_settlement):
        raise ResearchError('Account comparison settlement rules do not match its market.')
    if set(model) - {'basis', 'generatedAt', 'ageMs', 'probs', 'fairOdds', 'provenance'} or model.get('basis') != 'latest_snapshot':
        raise ResearchError('Account comparison model metadata is unsupported.')
    generated = utc(model.get('generatedAt'))
    model_probs = probabilities(model.get('probs'))
    if generated > compared or not close_number(model.get('ageMs'), (compared - generated).total_seconds() * 1000, 1):
        raise ResearchError('Account comparison model timestamps disagree.')
    if model_probs['H'] <= 0 or model_probs['A'] <= 0 or (market == 'tennis_match_winner' and model_probs['D'] != 0) \
            or (market == 'football_1x2_regulation' and model_probs['D'] <= 0):
        raise ResearchError('Account comparison model probabilities do not match the market outcome space.')
    fair = model.get('fairOdds')
    if not isinstance(fair, dict) or set(fair) != set(outcomes) or any(not close_number(fair[key], 1 / model_probs[key], .00500001) for key in outcomes):
        raise ResearchError('Account comparison fair odds disagree with its model probabilities.')
    provenance = model.get('provenance')
    if provenance is not None:
        fields = {'modelVersion', 'inputHash', 'calibrationHash', 'featureCutoffAt', 'sourcePublicationTimesVerified'}
        if not isinstance(provenance, dict) or set(provenance) != fields or provenance.get('sourcePublicationTimesVerified') is not False:
            raise ResearchError('Account comparison provenance has unsupported verification claims.')
        for key in ('modelVersion', 'inputHash', 'calibrationHash'):
            text(provenance.get(key), 200)
        if utc(provenance.get('featureCutoffAt')) > compared:
            raise ResearchError('Account comparison feature cutoff is in the future.')
    quote_fields = {'source', 'timestampVerified', 'bookmaker', 'capturedAt', 'ageMs', 'odds'}
    if set(quote) != quote_fields or quote.get('source') != 'customer_supplied' or quote.get('timestampVerified') is not False:
        raise ResearchError('Account comparison quote verification qualifiers are inconsistent.')
    text(quote.get('bookmaker'), 100)
    captured = utc(quote.get('capturedAt'))
    if captured > compared + timedelta(seconds=60) or not close_number(quote.get('ageMs'), max(0, (compared - captured).total_seconds() * 1000), 1):
        raise ResearchError('Account comparison quote capture and response timestamps disagree.')
    odds = quote.get('odds')
    if not isinstance(odds, dict) or set(odds) != set(outcomes) or any(not finite_number(odds[key]) or not 1 < odds[key] <= 10_000 for key in outcomes):
        raise ResearchError('Account comparison quote prices are invalid or incomplete.')
    if set(comparison) != {'quotePredatesModel', 'overround', 'outcomes'} or type(comparison.get('quotePredatesModel')) is not bool \
            or comparison['quotePredatesModel'] != (captured < generated):
        raise ResearchError('Account comparison timing qualifiers are inconsistent.')
    normaliser = sum(1 / odds[key] for key in outcomes)
    if not close_number(comparison.get('overround'), normaliser - 1):
        raise ResearchError('Account comparison overround disagrees with the original prices.')
    values = comparison.get('outcomes')
    if not isinstance(values, dict) or set(values) != set(outcomes):
        raise ResearchError('Account comparison outcomes are missing or unsupported.')
    for key in outcomes:
        implied = 1 / odds[key]
        expected = {'modelProbability': model_probs[key], 'impliedProbability': implied,
                    'normalisedImpliedProbability': implied / normaliser,
                    'probabilityDifference': model_probs[key] - implied / normaliser,
                    'expectedReturnPerUnit': model_probs[key] * odds[key] - 1}
        if not isinstance(values[key], dict) or set(values[key]) != set(expected) \
                or any(not close_number(values[key].get(field), result) for field, result in expected.items()):
            raise ResearchError('Account comparison arithmetic disagrees with its recorded probabilities or prices.')
    return {'fixtureId': fixture['id'], 'market': market, 'bookmaker': quote['bookmaker'],
            'capturedAt': quote['capturedAt'], 'odds': odds}


def quote_records(raw, now):
    if len(raw) > MAX_BYTES:
        raise ResearchError('Each quote input file must be no larger than 32 MiB.')
    try:
        whole = json_object(raw)
    except ResearchError:
        whole = None
    if whole is None or not ({'data', 'version', 'captureTimesVerified'} & set(whole)):
        return [(row, None) for row in records(raw)]
    reject_secrets(whole)
    fields = {'version', 'exportedAt', 'scope', 'captureTimesVerified', 'usageRightsUrl', 'data'}
    if set(whole) - fields - {'syntheticExample'} or not fields.issubset(whole) or type(whole.get('version')) is not int or whole['version'] != 1 \
            or whole.get('scope') != 'This completed batch only' or whole.get('captureTimesVerified') is not False \
            or whole.get('usageRightsUrl') != 'https://matchprior.com/usage-rights.html':
        raise ResearchError('Use the version 1 completed-comparison JSON packet exported by the account workspace.')
    if 'syntheticExample' in whole and type(whole['syntheticExample']) is not bool:
        raise ResearchError('A packet synthetic-example declaration must be true or false.')
    exported = utc(whole['exportedAt'])
    if exported > now or not isinstance(whole['data'], list) or len(whole['data']) > MAX_PACKET_QUOTES:
        raise ResearchError('Account comparison packet has a future export time or exceeds 50 comparisons.')
    output = []
    for response in whole['data']:
        if len(canonical(response).encode('utf-8')) > MAX_LINE:
            raise ResearchError('An account comparison response exceeds the per-record limit.')
        request = account_response(response, now)
        if utc(response['comparedAt']) > exported:
            raise ResearchError('Account packet export time precedes its comparison response.')
        metadata = {'exportedAt': whole['exportedAt'], 'usageRightsUrl': whole['usageRightsUrl'],
                    'syntheticExampleDeclared': whole.get('syntheticExample')}
        # exportedAt is a later file-export declaration, not a substitute for the
        # actual server comparison timestamp or the caller's declared capture.
        output.append(({'request': request, 'comparison': response, 'savedAt': response['comparedAt']}, metadata))
    return output


def load_quotes(raw, now):
    output = {}
    for row, packet in quote_records(raw, now):
        quote = row.get('request')
        comparison = row.get('comparison')
        if not isinstance(quote, dict) or not isinstance(comparison, dict):
            raise ResearchError('Quote history must use the compare_odds.py saved-history format.')
        identity = text(quote.get('fixtureId'))
        text(quote.get('bookmaker'), 100)
        observed = max(utc(row.get('savedAt')), utc(comparison.get('comparedAt')))
        captured = utc(quote.get('capturedAt'))
        if observed > now or (packet is None and captured > observed):
            raise ResearchError('Quote capture and observation times are inconsistent or in the future.')
        market = quote.get('market')
        outcomes = OUTCOMES if market == 'football_1x2_regulation' else ('H', 'A') if market == 'tennis_match_winner' else None
        if outcomes is None or not isinstance(quote.get('odds'), dict) or set(quote['odds']) != set(outcomes):
            raise ResearchError('A quote has an unsupported market or incomplete outcome prices.')
        odds = quote['odds']
        if any(type(odds[key]) not in (int, float) or not math.isfinite(odds[key]) or not 1 < odds[key] <= 10_000 for key in outcomes):
            raise ResearchError('Quote prices must be finite decimals greater than one and at most 10000.')
        returned_fixture, returned_quote = comparison.get('fixture'), comparison.get('quote')
        if not isinstance(returned_fixture, dict) or not isinstance(returned_quote, dict) or returned_fixture.get('id') != identity \
                or comparison.get('market') != market or returned_quote.get('bookmaker') != quote['bookmaker'] \
                or returned_quote.get('odds') != odds or utc(returned_quote.get('capturedAt')) != captured:
            raise ResearchError('Saved quote request and comparison response disagree.')
        normaliser = sum(1 / odds[key] for key in outcomes)
        implied = {key: (1 / odds[key] / normaliser if key in outcomes else 0) for key in OUTCOMES}
        output.setdefault(identity, []).append({'market': market, 'bookmaker': quote['bookmaker'],
            'capturedAt': quote['capturedAt'], 'observedTime': observed,
            'observedAt': observed.isoformat().replace('+00:00', 'Z'), 'capturedTime': captured,
            'probs': implied, 'odds': odds, 'sha256': digest(comparison if packet else row),
            'serverComparedAt': comparison['comparedAt'], 'localSavedAt': None if packet else row['savedAt'],
            'exportedAt': packet['exportedAt'] if packet else None,
            'observationBasis': 'account_response_timestamp' if packet else 'saved_comparison_history',
            'captureAfterResponseDeclared': captured > utc(comparison['comparedAt']),
            'syntheticExampleDeclared': packet['syntheticExampleDeclared'] if packet else row.get('syntheticExample'),
            'usageRightsUrl': packet['usageRightsUrl'] if packet else None,
            'responseModelSnapshotAt': comparison.get('model', {}).get('generatedAt') if isinstance(comparison.get('model'), dict) else None})
    return output


def result_for(forecast, evidence):
    if not evidence:
        return None, 'missing_outcome'
    unique = {digest({key: e[key] for key in ('status', 'actual', 'outcomeBasis')}) for e in evidence}
    if len(unique) > 1:
        return None, 'conflicting_outcome_records'
    candidates = [e for e in evidence if e['verifiedDeclared']]
    if not candidates:
        return None, 'outcome_not_verified_by_customer'
    chosen = min(candidates, key=lambda e: (e['observedTime'], e['sha256']))
    if chosen['status'] != 'completed':
        return chosen, 'outcome_' + chosen['status']
    if chosen['actual'] not in OUTCOMES:
        return chosen, 'missing_completed_result'
    basis = expected_basis(forecast['fixture'])
    if basis is None:
        return chosen, 'outcome_basis_not_supported'
    recorded = forecast['recordedSettlement']
    if chosen['outcomeBasis'] != basis or recorded and recorded.get('outcomeBasis') != basis:
        return chosen, 'outcome_basis_mismatch'
    if basis == 'completed_match_winner' and chosen['actual'] == 'D':
        return chosen, 'draw_not_supported_for_completed_tennis_match'
    if chosen['observedTime'] < forecast['startTime']:
        return chosen, 'outcome_observed_before_scheduled_start'
    if chosen['sourcePublicationTimeVerifiedDeclared'] and utc(chosen['sourcePublishedAt']) < forecast['startTime']:
        return chosen, 'outcome_published_before_scheduled_start_review'
    return chosen, None


def quote_for(forecast, quotes):
    if not quotes:
        return None, 'no_quote_supplied'
    required = 'football_1x2_regulation' if expected_basis(forecast['fixture']) == 'regulation_time_1x2' else 'tennis_match_winner'
    by_identity = {}
    for quote in quotes:
        identity = (quote['bookmaker'], quote['market'], quote['capturedAt'])
        by_identity.setdefault(identity, set()).add(digest(quote['odds']))
    if any(len(values) > 1 for values in by_identity.values()):
        return None, 'conflicting_quote_records'
    if not forecast['syntheticExampleDeclared'] and any(q.get('syntheticExampleDeclared') is True for q in quotes):
        return None, 'synthetic_quote_not_real_observation'
    eligible = [q for q in quotes if q['market'] == required and q['observedTime'] < forecast['startTime']
                and q['capturedTime'] < forecast['startTime'] and q['capturedTime'] <= q['observedTime']]
    if not eligible:
        if any(q['market'] == required and q['capturedTime'] > q['observedTime'] for q in quotes):
            return None, 'quote_capture_after_response_requires_review'
        return None, 'no_pre_start_quote_with_matching_outcome_basis'
    return min(eligible, key=lambda q: (q['observedTime'], q['capturedTime'], q['sha256'])), None


def summary(rows):
    included = [row for row in rows if row['status'] == 'graded']
    quoted = [row for row in included if row['quoteBrier'] is not None]
    reasons = {}
    for row in rows:
        if row['exclusionReason']:
            reasons[row['exclusionReason']] = reasons.get(row['exclusionReason'], 0) + 1
    average = lambda field, values: sum(row[field] for row in values) / len(values) if values else None
    model, baseline = average('modelBrier', included), average('uniformBrier', included)
    return {'selectedForecasts': len(rows), 'graded': len(included), 'excluded': len(rows) - len(included),
            'hitRate': sum(row['hit'] for row in included) / len(included) if included else None,
            'meanBrier': model, 'uniformMeanBrier': baseline,
            'brierSkillVsUniform': 1 - model / baseline if baseline else None,
            'quoteCohort': {'graded': len(quoted), 'modelMeanBrier': average('modelBrier', quoted),
                            'normalisedQuoteMeanBrier': average('quoteBrier', quoted)},
            'exclusionReasons': reasons}


def evaluate(prediction_rows, outcomes, quotes=None, now=None):
    now = now or datetime.now(timezone.utc)
    if now.tzinfo is None:
        raise ResearchError('Evaluation time must have a UTC timezone.')
    quotes = quotes or {}
    synthetic = [row.get('syntheticExample') is True for row in prediction_rows]
    if any(synthetic) and not all(synthetic):
        raise ResearchError('Keep synthetic examples in a separate file from real observations.')
    by_cohort = {}
    for record in prediction_rows:
        parsed = prediction(record, now)
        by_cohort.setdefault((parsed['cohort'], parsed['fixtureId']), []).append(parsed)
    output = []
    for (cohort, identity), originals in sorted(by_cohort.items()):
        chosen = min(originals, key=lambda p: (p['observedTime'], utc(p['snapshotAt']), p['originalRowSha256']))
        snapshots = {}
        for record in originals:
            snapshots.setdefault(record['snapshotAt'], set()).add(record['snapshotContentSha256'])
        conflicting = any(len(values) > 1 for values in snapshots.values())
        outcome, reason = result_for(chosen, outcomes.get(identity, []))
        if conflicting:
            reason = 'conflicting_original_forecasts_in_same_snapshot'
        quote, quote_reason = quote_for(chosen, quotes.get(identity, []))
        actual = outcome['actual'] if outcome and outcome['status'] == 'completed' else None
        graded = reason is None
        basis = expected_basis(chosen['fixture'])
        uniform = {'H': .5, 'D': 0, 'A': .5} if basis == 'completed_match_winner' else {key: 1 / 3 for key in OUTCOMES}
        output.append({'cohort': cohort, 'fixtureId': identity, 'sport': chosen['fixture']['sport'],
            'league': chosen['fixture']['league'], 'fixtureDate': chosen['fixture']['date'],
            'status': 'graded' if graded else 'excluded', 'exclusionReason': reason,
            'outcomeBasis': basis, 'actual': actual, 'pick': chosen['pick'], 'confidence': chosen['confidence'],
            'modelProbabilities': chosen['probs'], 'modelVersion': chosen['modelVersion'],
            'snapshotAt': chosen['snapshotAt'], 'observedAt': chosen['observedAt'],
            'serverObservedAt': chosen['serverObservedAt'], 'scheduledStartMs': chosen['fixture']['startMs'],
            'originalObservations': len(originals), 'selectedOriginalRowSha256': chosen['originalRowSha256'],
            'sourcePublicationTimesVerifiedDeclared': chosen['sourcePublicationTimesVerifiedDeclared'],
            'hit': chosen['pick'] == actual if graded else None,
            'modelBrier': score(chosen['probs'], actual) if graded else None,
            'uniformBrier': score(uniform, actual) if graded else None,
            'outcomeObservedAt': outcome['observedAt'] if outcome else None,
            'outcomeSource': outcome['source'] if outcome else None,
            'outcomeVerifiedDeclared': outcome['verifiedDeclared'] if outcome else False,
            'outcomeSourcePublicationTimeVerifiedDeclared': outcome['sourcePublicationTimeVerifiedDeclared'] if outcome else False,
            'outcomeSourcePublishedAt': outcome['sourcePublishedAt'] if outcome else None,
            'outcomeEvidenceSha256': outcome['sha256'] if outcome else None,
            'quoteBrier': score(quote['probs'], actual) if graded and quote else None,
            'quoteExclusionReason': quote_reason,
            'quoteBookmaker': quote['bookmaker'] if quote else None,
            'quoteCapturedAtDeclared': quote['capturedAt'] if quote else None,
            'quoteFirstObservedAt': quote['observedAt'] if quote else None,
            'quoteServerComparedAt': quote.get('serverComparedAt') if quote else None,
            'quoteLocalSavedAt': quote.get('localSavedAt') if quote else None,
            'quoteExportedAt': quote.get('exportedAt') if quote else None,
            'quoteObservationBasis': quote.get('observationBasis') if quote else None,
            'quoteObservationTimestampsIndependentlyVerified': False,
            'quoteExcludedCaptureAfterResponseCount': len({q['sha256'] for q in quotes.get(identity, []) if q.get('captureAfterResponseDeclared')}),
            'quoteSyntheticExampleDeclared': quote.get('syntheticExampleDeclared') if quote else None,
            'quoteComparisonModelSnapshotAt': quote.get('responseModelSnapshotAt') if quote else None,
            'quoteComparisonModelUsedForForecast': False,
            'quoteUsageRightsUrl': quote.get('usageRightsUrl') if quote else None,
            'quoteTimestampIndependentlyVerified': False,
            'quotePredatesForecastObservation': quote['observedTime'] < chosen['observedTime'] if quote else None,
            'selectedQuoteRowSha256': quote['sha256'] if quote else None})
    cohorts = {}
    for cohort in sorted({row['cohort'] for row in output}):
        selected = [row for row in output if row['cohort'] == cohort]
        cohorts[cohort] = {'bySport': {sport: summary([r for r in selected if r['sport'] == sport]) for sport in sorted({r['sport'] for r in selected})},
                           'byLeague': {league: summary([r for r in selected if r['league'] == league]) for league in sorted({r['league'] for r in selected})}}
    return {'schemaVersion': 1, 'measuredAt': now.isoformat().replace('+00:00', 'Z'), 'networkRequests': False,
            'syntheticExample': bool(synthetic) and all(synthetic),
            'cohorts': cohorts, 'rows': output, 'definitions': {
                'selection': 'First observed original forecast within each fixture/cohort; later model snapshots never replace it. Conflicting versions in one snapshot are excluded. First observed matching pre-start quote is selected without looking at the outcome. A report labelled syntheticExample demonstrates mechanics only and is not a performance record.',
                'prospective': 'Collector-declared local, server and snapshot observations precede the stored scheduled start. This does not independently verify provider publication, source availability, transport or a later reschedule.',
                'historical': 'Explicit historical replays and current forecasts first observed at/after the stored start are separate cohorts. No combined prospective/historical or combined-sport score is produced.',
                'verification': 'All outcome/source verification flags are supplied by the customer. This offline tool does not independently authenticate results, timestamps, original file history or rights. Unknown publication times remain unknown.',
                'scoring': 'Brier is the sum of H/D/A squared errors (0–2, lower is better). Uniform baseline is thirds for reviewed regulation football and H/A halves for completed ATP/WTA matches. Scores use exactly the same graded forecasts within each cohort.',
                'quotes': 'Optional quotes are customer-authorised inputs from compare_odds.py JSONL or a version 1 account comparison JSON packet. Quote benchmark and original collector-model scores use the same quote subset; the comparison response model never substitutes for the original forecast. Capture time is customer-declared. For account packets comparedAt is the server-response timestamp, while exportedAt is a separate later browser-file export declaration. The API permits capture declarations up to sixty seconds after its response clock with age zero; this tool accepts those records but excludes them from quote scores pending chronology review. No independent authentication of these file-supplied times is established. Scored quote observation and capture must precede the original stored start, with declared capture no later than observation. Normalisation removes proportional overround only; this is not verified market fair probability or profit.',
                'exclusions': 'Missing, unverified, conflicting, void, non-completed or outcome-basis-mismatched results stay excluded. They are never treated as losses. A disappeared fixture is not evidence of cancellation.',
                'permissions': 'Keep files private and use only data you are entitled to retain. No raw source feed or customer credential is retrieved. Existing licence and attribution requirements still apply.'}}


def csv_bytes(rows):
    columns = ['cohort', 'fixtureId', 'sport', 'league', 'fixtureDate', 'status', 'exclusionReason',
               'outcomeBasis', 'actual', 'pick', 'confidence', 'modelBrier', 'uniformBrier', 'quoteBrier',
               'modelVersion', 'snapshotAt', 'observedAt', 'serverObservedAt', 'scheduledStartMs',
               'selectedOriginalRowSha256', 'outcomeObservedAt', 'outcomeSource', 'outcomeVerifiedDeclared',
               'outcomeSourcePublicationTimeVerifiedDeclared', 'quoteBookmaker', 'quoteCapturedAtDeclared',
               'quoteFirstObservedAt', 'quoteTimestampIndependentlyVerified', 'quoteExclusionReason']
    columns += ['quoteServerComparedAt', 'quoteLocalSavedAt', 'quoteExportedAt', 'quoteObservationBasis',
                'quoteObservationTimestampsIndependentlyVerified', 'quoteSyntheticExampleDeclared',
                'quoteExcludedCaptureAfterResponseCount',
                'quoteComparisonModelSnapshotAt', 'quoteComparisonModelUsedForForecast', 'quoteUsageRightsUrl']
    handle = io.StringIO(newline='')
    writer = csv.DictWriter(handle, fieldnames=columns, lineterminator='\n')
    writer.writeheader()
    for row in rows:
        safe = {key: row.get(key) for key in columns}
        for key, value in safe.items():
            if isinstance(value, str) and value.startswith(('=', '+', '-', '@', '\t', '\r')):
                safe[key] = "'" + value
        writer.writerow(safe)
    return handle.getvalue().encode('utf-8')


def write_outputs(outputs, input_paths):
    targets = [Path(path).expanduser() for path, _ in outputs]
    inputs = {Path(path).expanduser().resolve() for path in input_paths}
    if len({target.resolve() for target in targets}) != len(targets) or any(target.resolve() in inputs for target in targets):
        raise ResearchError('Output paths must be distinct from every input and each other.')
    if any(target.exists() or target.is_symlink() for target in targets):
        raise ResearchError('Output paths must be new files; existing files are preserved.')
    created = []
    try:
        for target, (_, raw) in zip(targets, outputs):
            fd = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, 'O_NOFOLLOW', 0), 0o600)
            created.append(target)
            with os.fdopen(fd, 'wb') as handle:
                if not stat.S_ISREG(os.fstat(handle.fileno()).st_mode):
                    raise ResearchError('Outputs must be regular local files.')
                handle.write(raw); handle.flush(); os.fsync(handle.fileno())
    except Exception:
        for target in created:
            try:
                target.unlink()
            except OSError:
                pass
        raise


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('--predictions', required=True)
    parser.add_argument('--outcomes', required=True)
    parser.add_argument('--quotes', help='compare_odds.py JSONL history or account export matchprior-comparisons.json.')
    parser.add_argument('--report', required=True, help='New JSON report path in a private local folder.')
    parser.add_argument('--rows', help='Optional new CSV export path.')
    args = parser.parse_args(argv)
    try:
        now = datetime.now(timezone.utc)
        prediction_raw, outcome_raw = read_input(args.predictions), read_input(args.outcomes)
        quote_raw = read_input(args.quotes) if args.quotes else None
        report = evaluate(records(prediction_raw), parse_results(outcome_raw, now), load_quotes(quote_raw, now) if quote_raw is not None else {}, now)
        report['inputs'] = {'predictionsSha256': hashlib.sha256(prediction_raw).hexdigest(),
                            'outcomesSha256': hashlib.sha256(outcome_raw).hexdigest(),
                            'quotesSha256': hashlib.sha256(quote_raw).hexdigest() if quote_raw is not None else None}
        outputs = [(args.report, (json.dumps(report, indent=2, ensure_ascii=False, allow_nan=False) + '\n').encode('utf-8'))]
        if args.rows:
            outputs.append((args.rows, csv_bytes(report['rows'])))
        write_outputs(outputs, [args.predictions, args.outcomes] + ([args.quotes] if args.quotes else []))
        print(json.dumps({'selectedForecasts': len(report['rows']), 'cohorts': report['cohorts'], 'networkRequests': False,
                          'syntheticExample': report['syntheticExample']}, indent=2, allow_nan=False))
        return 0
    except ResearchError as error:
        print(str(error), file=sys.stderr)
    except (OSError, ValueError, TypeError, OverflowError, RecursionError):
        print('Could not evaluate or save the local files safely. Original inputs were preserved.', file=sys.stderr)
    return 1


if __name__ == '__main__':
    raise SystemExit(main())
