#!/usr/bin/env python3
"""Compare your own pre-match prices with MatchPrior's current model.

Python 3.9+, standard library only. Set MATCHPRIOR_API_KEY in your environment.
Usage: python compare_odds.py quote.json [--history private-history.jsonl]
The optional history stays on your computer. No automatic retries or feed access.
"""
import argparse
import json
import math
import os
from pathlib import Path
import stat
import sys
import urllib.error
import urllib.request
from datetime import datetime, timezone

ENDPOINT = "https://api.matchprior.com/v1/odds/compare"
MAX_QUOTE_BYTES = 8_192
MAX_RESPONSE_BYTES = 262_144


class ComparisonError(Exception):
    """An error safe to display without request headers or credentials."""


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        # Never forward an API key to a redirect target.
        return None


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


def reject_constant(value):
    raise ValueError("Non-finite JSON constant.")


def strict_json(raw):
    return json.loads(raw, parse_float=finite_float, parse_constant=reject_constant)


def load_quote(path, key):
    with Path(path).open("rb") as handle:
        raw = handle.read(MAX_QUOTE_BYTES + 1)
    if len(raw) > MAX_QUOTE_BYTES:
        raise ComparisonError("Quote file exceeds 8 KiB.")
    try:
        quote = strict_json(raw)
    except (ValueError, UnicodeError, RecursionError):
        raise ComparisonError("Quote file must contain valid JSON with finite numbers.") from None
    if not isinstance(quote, dict):
        raise ComparisonError("Quote file must contain a JSON object.")
    try:
        encoded = json.dumps(quote, allow_nan=False, separators=(",", ":")).encode("utf-8")
    except (ValueError, UnicodeError, RecursionError):
        raise ComparisonError("Quote file cannot be encoded as finite JSON.") from None
    if len(encoded) > MAX_QUOTE_BYTES:
        raise ComparisonError("Encoded quote exceeds 8 KiB.")
    if key.encode("utf-8") in encoded:
        raise ComparisonError("Remove your API key from the quote file; it belongs only in the environment.")
    return quote, encoded


def compare(encoded, key, opener=None):
    request = urllib.request.Request(ENDPOINT, data=encoded, method="POST", headers={
        "X-API-Key": key, "Content-Type": "application/json", "Accept": "application/json",
        "User-Agent": "MatchPrior-customer-odds-example/1.0",
    })
    opener = opener or urllib.request.build_opener(NoRedirect())
    try:
        with opener.open(request, timeout=15) as response:
            raw = response.read(MAX_RESPONSE_BYTES + 1)
            if len(raw) > MAX_RESPONSE_BYTES:
                raise ComparisonError("API response was unexpectedly large.")
    except urllib.error.HTTPError as error:
        # Avoid echoing arbitrary remote text, redirects, headers or credentials.
        messages = {
            400: "Check the quote fields, prices and UTC timestamp.",
            401: "Check MATCHPRIOR_API_KEY.",
            403: "Your key does not permit this sport.",
            404: "Use an exact fixture ID from the current prediction list.",
            405: "This route requires POST.",
            408: "The request body timed out.",
            409: "The fixture, market or quote timing cannot be compared. Refresh the prediction and quote.",
            413: "The quote is too large.",
            415: "The API requires application/json.",
            422: "The fixture or market is not eligible for comparison.",
            429: "Your monthly allowance is exhausted. Check /v1/usage before retrying.",
            503: "The model snapshot is unavailable or stale. Check /v1/health before retrying.",
        }
        raise ComparisonError("HTTP %s. %s No automatic retry was made." % (
            error.code, messages.get(error.code, "Check the service status before retrying."))) from None
    except (urllib.error.URLError, TimeoutError, OSError):
        raise ComparisonError("Connection failed. The request may have reached the API; check usage before retrying.") from None
    if key.encode("utf-8") in raw:
        raise ComparisonError("Refusing to display a response containing your API key.")
    try:
        result = strict_json(raw)
    except (ValueError, UnicodeError, RecursionError):
        raise ComparisonError("API returned an invalid JSON response.") from None
    if not isinstance(result, dict):
        raise ComparisonError("API returned an unexpected response shape.")
    return result


def append_history(path, quote, result):
    target = Path(path).expanduser()
    if target.is_symlink():
        raise ComparisonError("History path must be a regular file, not a symbolic link.")
    flags = os.O_WRONLY | os.O_CREAT | os.O_APPEND | getattr(os, "O_NOFOLLOW", 0)
    descriptor = os.open(target, flags, 0o600)
    try:
        if not stat.S_ISREG(os.fstat(descriptor).st_mode):
            raise ComparisonError("History path must be a regular file.")
        if os.name == "posix":
            os.fchmod(descriptor, 0o600)
        row = {"savedAt": datetime.now(timezone.utc).isoformat(), "request": quote, "comparison": result}
        payload = (json.dumps(row, allow_nan=False, separators=(",", ":")) + "\n").encode("utf-8")
        with os.fdopen(descriptor, "ab", closefd=False) as handle:
            handle.write(payload)
            handle.flush()
            os.fsync(handle.fileno())
    finally:
        os.close(descriptor)


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("quote", help="Your JSON quote file; preserve its actual capture timestamp.")
    parser.add_argument("--history", help="Append the input and comparison to this local JSONL file. Use a private folder.")
    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(character.isspace() for character in key):
        print("Set a valid MATCHPRIOR_API_KEY environment variable first.", file=sys.stderr)
        return 1
    try:
        quote, encoded = load_quote(args.quote, key)
        result = compare(encoded, key)
        try:
            output = json.dumps(result, indent=2, allow_nan=False)
        except (ValueError, UnicodeError, RecursionError):
            raise ComparisonError("API response cannot be displayed as finite JSON.") from None
    except (ComparisonError, OSError) as error:
        print(str(error) if isinstance(error, ComparisonError) else "Could not read the quote file.", file=sys.stderr)
        return 1
    history_failed = False
    if args.history:
        try:
            append_history(args.history, quote, result)
        except (ComparisonError, OSError, ValueError):
            print("Comparison succeeded, but local history could not be saved. Do not resubmit just to save history.", file=sys.stderr)
            history_failed = True
    print(output)
    return 2 if history_failed else 0


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