"""Minimal synchronous Flex client. Python 3.10+, standard library only.

Never retries, creates keys, or generates idempotency identities. Persist each
intent and returned quote ID before accepting. A timeout is not a rejection.

OMNI_API_SECRET is the secret from Settings → API keys: 64 hex characters.
"""
from __future__ import annotations

import base64
import hashlib
import hmac
import http.client
import json
import os
import time
import urllib.error
import urllib.parse
import urllib.request
from decimal import Decimal

API_ORIGIN = "https://api.omnibook.xyz"
MAX_RESPONSE_BYTES = 2_000_000


class APIError(Exception):
    """Response is available explicitly; exception text never includes credentials/body."""
    def __init__(self, status: int | None, response=None, *, quote_id=None):
        self.status = status
        self.response = response
        self.quote_id = quote_id
        super().__init__(f"Flex request failed (HTTP {status or 'unavailable'})")


class Rejected(APIError):
    """HTTP 409: terminal rejection for this request; no automatic replacement."""


class UnknownOutcome(APIError):
    """Execution may have happened. Reconcile only the original accept quote ID."""


class RateLimited(APIError):
    @property
    def retry_after_ms(self):
        return self.response.get("retry_after_ms") if isinstance(self.response, dict) else None


class _NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None  # Never forward signed credentials or change a signed target.


def _reject_constant(value):
    raise ValueError("Nonfinite JSON")


def _integer(value, name, low, high):
    if type(value) is not int or not low <= value <= high:
        raise ValueError(f"{name} must be an integer from {low} to {high}")
    return value


def _id(value, name):
    if not isinstance(value, str) or not value.isascii() or not value.isdecimal():
        raise ValueError(f"{name} must be a positive decimal string")
    if not 0 < int(value) <= 2**63 - 1:
        raise ValueError(f"{name} is out of range")
    return value


def _request_id(value):
    if not isinstance(value, str) or not value or len(value.encode("utf-8")) > 128:
        raise ValueError("request_id must contain 1–128 UTF-8 bytes")
    return value


def _decimal(value):
    if isinstance(value, (float, bool)):
        raise TypeError("Use Decimal, integer or decimal string, never float")
    result = Decimal(value)
    if not result.is_finite():
        raise ValueError("Money must be finite")
    return result


def cents_to_usd(value):
    """Quote/position cost, price, proceeds and payout are cents, possibly fractional."""
    return _decimal(value) / Decimal(100)


def pips_to_usd(value):
    """Portfolio amounts are pip strings: 10,000 pips = $1."""
    return _decimal(value) / Decimal(10_000)


def decode_secret(secret: str) -> bytes:
    """Turn the key secret from Settings → API keys into the 32 HMAC key bytes.

    The secret is 64 hex characters (accountsd shows it once, as hex). Older
    copies of this client took base64; a base64 string of 32 bytes still works.
    """
    if not isinstance(secret, str):
        raise ValueError("Secret must be a string")
    text = secret.strip()
    if len(text) == 64 and all(c in "0123456789abcdefABCDEF" for c in text):
        return bytes.fromhex(text)
    try:
        raw = base64.b64decode(text, validate=True)
    except (ValueError, TypeError):
        raise ValueError("Secret must be 64 hex characters") from None
    if len(raw) != 32:
        raise ValueError("Secret must be 64 hex characters")
    return raw


class FlexClient:
    def __init__(self, access_key: str, secret: str, *, origin=API_ORIGIN, timeout=5):
        parsed = urllib.parse.urlsplit(origin)
        if (parsed.scheme != "https" or not parsed.hostname or parsed.username is not None
                or parsed.password is not None or parsed.path not in ("", "/")
                or parsed.query or parsed.fragment):
            raise ValueError("origin must be an HTTPS origin without credentials/path/query")
        if not isinstance(access_key, str) or not access_key or any(ord(c) < 33 or ord(c) > 126 for c in access_key):
            raise ValueError("Invalid access key")
        secret = decode_secret(secret)
        if not isinstance(timeout, (int, float)) or not 0 < timeout <= 60:
            raise ValueError("timeout must be in (0, 60] seconds")
        self._access_key, self._secret = access_key, secret
        self._origin, self._timeout = origin.rstrip("/"), timeout
        self._opener = urllib.request.build_opener(_NoRedirect())

    @classmethod
    def from_env(cls, **kwargs):
        return cls(os.environ["OMNI_ACCESS_KEY"], os.environ["OMNI_API_SECRET"], **kwargs)

    def _request(self, method, target, payload=None, *, accept_id=None):
        parsed = urllib.parse.urlsplit(target)
        if (not target.startswith("/flex/") or parsed.scheme or parsed.netloc
                or parsed.fragment or any(ord(c) < 33 or ord(c) > 126 for c in target)):
            raise ValueError("Target must be an ASCII Flex path with an optional encoded query")
        if method not in ("GET", "POST") or (method == "GET" and payload is not None):
            raise ValueError("Unsupported method/body")
        body = b"" if payload is None else json.dumps(
            payload, ensure_ascii=False, separators=(",", ":"), allow_nan=False).encode("utf-8")
        timestamp = str(time.time_ns() // 1_000_000)
        canonical = f"{timestamp}\n{method}\n{target}\n".encode("ascii") + body
        signature = base64.b64encode(hmac.new(self._secret, canonical, hashlib.sha256).digest()).decode("ascii")
        request = urllib.request.Request(self._origin + target,
            data=None if method == "GET" else body, method=method,
            headers={"DX-ACCESS-KEY": self._access_key, "DX-ACCESS-TIMESTAMP": timestamp,
                     "DX-ACCESS-SIGNATURE": signature, "Content-Type": "application/json",
                     "Accept": "application/json"})
        try:
            try:
                response = self._opener.open(request, timeout=self._timeout)
            except urllib.error.HTTPError as error:
                response = error
            with response:
                status = response.code
                raw = response.read(MAX_RESPONSE_BYTES + 1)
            try:
                if len(raw) > MAX_RESPONSE_BYTES:
                    raise ValueError("Response limit")
                data = json.loads(raw, parse_float=Decimal,
                    parse_constant=_reject_constant)
            except (ValueError, UnicodeError):
                data = None
            if status == 409:
                raise Rejected(status, data, quote_id=accept_id)
            if status == 429:
                raise RateLimited(status, data, quote_id=accept_id)
            if status == 503 or (accept_id is not None and (status >= 500 or (200 <= status < 300 and not isinstance(data, dict)))):
                raise UnknownOutcome(status, data, quote_id=accept_id)
            if status != 200 or not isinstance(data, dict):
                raise APIError(status, data, quote_id=accept_id)
            # A proxy's 200 page/object is not authoritative proof of execution.
            if accept_id is not None:
                expected = "exit_id" if target == "/flex/exit/accept" else "id"
                if data.get(expected) != accept_id or data.get("state") not in ("open", "unresolved", "settled", "exited"):
                    raise UnknownOutcome(status, data, quote_id=accept_id)
                if expected == "exit_id" and data.get("state") != "exited":
                    raise UnknownOutcome(status, data, quote_id=accept_id)
            return data
        except (urllib.error.URLError, OSError, http.client.HTTPException):
            raise UnknownOutcome(None, quote_id=accept_id) from None

    def state(self):
        return self._request("GET", "/flex/state")

    def portfolio(self):
        return self._request("GET", "/flex/portfolio")

    def quote(self, *, request_id, side, tenor, budget_cents=None, contracts=None):
        if side not in ("above", "below"):
            raise ValueError("side must be above or below")
        if (budget_cents is None) == (contracts is None):
            raise ValueError("Choose exactly one of budget_cents or contracts")
        terms = {"request_id": _request_id(request_id), "side": side,
                 "tenor": _integer(tenor, "tenor", 60, 3600)}
        if budget_cents is not None:
            terms["budget"] = _integer(budget_cents, "budget_cents", 100, 10000)
        else:
            terms["contracts"] = _integer(contracts, "contracts", 1, 100)
        return self._request("POST", "/flex/quote", terms)

    def accept(self, quote_id):
        quote_id = _id(quote_id, "quote_id")
        return self._request("POST", "/flex/accept", {"quote_id": quote_id}, accept_id=quote_id)

    def exit_quote(self, *, request_id, position_id):
        return self._request("POST", "/flex/exit/quote", {
            "request_id": _request_id(request_id), "position_id": _id(position_id, "position_id")})

    def exit_accept(self, quote_id):
        quote_id = _id(quote_id, "quote_id")
        return self._request("POST", "/flex/exit/accept", {"quote_id": quote_id}, accept_id=quote_id)
