#!/usr/bin/env python3
"""Collect current pre-match MatchPrior predictions for your own paper tracker.

Python 3.9+, standard library only. Set MATCHPRIOR_API_KEY, then run:
  python paper_tracker.py --sport football --output private-football.jsonl
  python paper_tracker.py --sport tennis --output private-tennis.jsonl

Each successful prediction page uses one normal plan request. No automatic
retries, bookmaker requests, past reconstruction, betting or settlement occurs.
"""
import argparse
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
import json
import math
import os
from pathlib import Path
import stat
import sys
import urllib.error
import urllib.parse
import urllib.request

BASE = 'https://api.matchprior.com/v1'
MAX_BYTES = 4 * 1024 * 1024
MAX_HISTORY_BYTES = 32 * 1024 * 1024
MAX_PAGES = 25


class TrackerError(Exception):
    """A message safe to display without credentials or request headers."""


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


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


def decode_json(raw):
    try:
        return json.loads(raw, parse_float=finite_float,
                          parse_constant=lambda value: (_ for _ in ()).throw(ValueError(value)))
    except (ValueError, UnicodeError, RecursionError):
        raise TrackerError('Expected valid JSON containing finite numbers.') from None


def date_time(value):
    try:
        if not isinstance(value, str) or not value.endswith('Z'):
            raise ValueError()
        return datetime.fromisoformat(value[:-1] + '+00:00')
    except (ValueError, TypeError):
        raise TrackerError('The service returned an invalid snapshot timestamp.') from None


def server_time(headers):
    try:
        value = next(value for key, value in headers.items() if key.lower() == 'date')
        parsed = parsedate_to_datetime(value)
        if parsed.tzinfo is None:
            raise ValueError()
        return parsed.astimezone(timezone.utc)
    except (StopIteration, ValueError, TypeError, AttributeError):
        raise TrackerError('A valid server Date header is required for the pre-match check.') from None


def requester(key):
    opener = urllib.request.build_opener(NoRedirect())

    def get(path, authenticated=True):
        headers = {'Accept': 'application/json', 'User-Agent': 'MatchPrior-paper-tracker/1.0'}
        if authenticated:
            headers['X-API-Key'] = key
        request = urllib.request.Request(BASE + path, headers=headers)
        try:
            with opener.open(request, timeout=20) as response:
                raw = response.read(MAX_BYTES + 1)
                if len(raw) > MAX_BYTES:
                    raise TrackerError('The API response was unexpectedly large.')
                if key.encode() in raw:
                    raise TrackerError('Refusing a response containing your API key.')
                return decode_json(raw), dict(response.headers.items())
        except urllib.error.HTTPError as error:
            messages = {401: 'Check MATCHPRIOR_API_KEY.', 403: 'Your key may be limited to another sport.',
                        429: 'Check your remaining allowance in the account workspace.',
                        503: 'Check service freshness before running again.'}
            raise TrackerError('HTTP %s. %s No automatic retry was made.' %
                               (error.code, messages.get(error.code, 'Check the service status.'))) from None
        except (urllib.error.URLError, OSError, TimeoutError):
            raise TrackerError('The connection failed. A request may have consumed quota; check usage before retrying.') from None
    return get


def collect(sport, get, observed_at=None):
    observed_at = observed_at or datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z')
    health, health_headers = get('/health', False)
    if not isinstance(health, dict) or health.get('ok') is not True or health.get('stale') is True:
        raise TrackerError('The current model snapshot is unavailable or stale.')
    snapshot_at = health.get('generatedAt')
    date_time(snapshot_at)
    server_time(health_headers)
    cursor = None
    seen_cursors = set()
    seen_fixtures = set()
    records = []
    skipped = {'unknownStart': 0, 'started': 0}
    pages = 0
    for _ in range(MAX_PAGES):
        params = {'sport': sport, 'limit': '200'}
        if cursor:
            params['since'] = cursor
        body, response_headers = get('/predictions?' + urllib.parse.urlencode(params))
        pages += 1
        current_time = server_time(response_headers)
        if not isinstance(body, dict) or not isinstance(body.get('data'), list) or not isinstance(body.get('page'), dict):
            raise TrackerError('The prediction page has an unexpected shape; no history was written.')
        data, page = body['data'], body['page']
        if len(data) > 200 or page.get('count') != len(data):
            raise TrackerError('The prediction page count is inconsistent; no history was written.')
        for prediction in data:
            if not isinstance(prediction, dict) or not isinstance(prediction.get('fixture'), dict):
                raise TrackerError('A prediction is malformed; no history was written.')
            fixture = prediction['fixture']
            identity = fixture.get('id')
            if not isinstance(identity, str) or not identity or len(identity) > 512 or fixture.get('sport') != sport:
                raise TrackerError('A fixture identity or sport is invalid; no history was written.')
            if identity in seen_fixtures:
                raise TrackerError('A fixture repeated across pages; refresh the snapshot before trying again.')
            seen_fixtures.add(identity)
            start = fixture.get('startMs')
            if type(start) not in (int, float) or not math.isfinite(start):
                skipped['unknownStart'] += 1
                continue
            if start <= current_time.timestamp() * 1000:
                skipped['started'] += 1
                continue
            probs = prediction.get('probs')
            if not isinstance(probs, dict) or any(type(probs.get(k)) not in (int, float)
                   or not math.isfinite(probs[k]) or not 0 <= probs[k] <= 1 for k in ('H', 'D', 'A')):
                raise TrackerError('Model probabilities are invalid; no history was written.')
            if abs(sum(probs[k] for k in ('H', 'D', 'A')) - 1) > 0.000001:
                raise TrackerError('Model probabilities do not sum to one; no history was written.')
            # Copy only fields already public in the customer API. Never retain an
            # unknown future field or use internal bookmaker data as a substitute.
            model = {k: prediction[k] for k in ('probs', 'fairOdds', 'pick', 'confidence',
                     'settlement', 'provenance') if k in prediction}
            public_fixture = {k: fixture[k] for k in ('id', 'sport', 'league', 'date', 'time',
                              'startMs', 'home', 'away', 'tournament', 'round', 'surface') if k in fixture}
            records.append({'schemaVersion': 1, 'fixtureId': identity, 'sport': sport,
                            'snapshotAt': snapshot_at, 'observedAt': observed_at,
                            'serverObservedAt': current_time.isoformat().replace('+00:00', 'Z'),
                            'observationBasis': 'current_snapshot_observation',
                            'fixture': public_fixture, 'model': model})
        cursor = page.get('nextCursor')
        if cursor is None:
            break
        if not isinstance(cursor, str) or not cursor or len(cursor) > 2048 or cursor in seen_cursors:
            raise TrackerError('The pagination cursor is invalid or repeated; no history was written.')
        seen_cursors.add(cursor)
    else:
        raise TrackerError('The page safety limit was reached; no incomplete history was written.')
    final_health, _ = get('/health', False)
    if not isinstance(final_health, dict) or final_health.get('generatedAt') != snapshot_at or final_health.get('ok') is not True:
        raise TrackerError('The model snapshot changed while paging. No mixed history was written; no automatic retry was made.')
    return records, {'snapshotAt': snapshot_at, 'predictionPages': pages,
                     'eligiblePredictions': len(records), 'skipped': skipped}


def append_history(path, records):
    target = Path(path).expanduser()
    if target.is_symlink():
        raise TrackerError('Choose a regular history file in a private folder, not a symbolic link.')
    existing = set()
    original = b''
    if target.exists():
        if not target.is_file() or target.stat().st_size > MAX_HISTORY_BYTES:
            raise TrackerError('History must be a regular file no larger than32MiB; archive it before continuing.')
        original = target.read_bytes()
        for line in original.splitlines():
            row = decode_json(line)
            if not isinstance(row, dict) or not all(k in row for k in ('sport', 'fixtureId', 'snapshotAt')):
                raise TrackerError('Existing history is malformed; it was preserved without changes.')
            existing.add((row['sport'], row['fixtureId'], row['snapshotAt']))
    pending = [row for row in records if (row['sport'], row['fixtureId'], row['snapshotAt']) not in existing]
    if not pending:
        return 0
    payload = (b'\n' if original and not original.endswith(b'\n') else b'') + ''.join(
        json.dumps(row, allow_nan=False, separators=(',', ':')) + '\n' for row in pending).encode()
    if len(payload) + (target.stat().st_size if target.exists() else 0) > MAX_HISTORY_BYTES:
        raise TrackerError('Appending would exceed32MiB. Archive the existing file first.')
    descriptor = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_APPEND | getattr(os, 'O_NOFOLLOW', 0)
                         | getattr(os, 'O_NONBLOCK', 0), 0o600)
    try:
        if not stat.S_ISREG(os.fstat(descriptor).st_mode):
            raise TrackerError('The output must be a regular file.')
        if os.name == 'posix':
            os.fchmod(descriptor, 0o600)
        with os.fdopen(descriptor, 'ab', closefd=False) as handle:
            handle.write(payload)
            handle.flush()
            os.fsync(handle.fileno())
    finally:
        os.close(descriptor)
    return len(pending)


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--sport', choices=['football', 'tennis'], required=True)
    parser.add_argument('--output', required=True, help='Private local JSONL history path.')
    args = parser.parse_args(argv)
    key = os.environ.get('MATCHPRIOR_API_KEY', '').strip()
    if not key or not key.isascii() or len(key) > 256 or any(char.isspace() for char in key):
        print('Set a valid MATCHPRIOR_API_KEY environment variable first.', file=sys.stderr)
        return 1
    try:
        records, summary = collect(args.sport, requester(key))
        summary['appended'] = append_history(args.output, records)
    except (TrackerError, OSError, ValueError, TypeError) as error:
        print(str(error) if isinstance(error, TrackerError) else 'Could not save the local history safely. Check usage before retrying.', file=sys.stderr)
        return 1
    print(json.dumps(summary, indent=2))
    return 0


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