import json
import socket
import urllib.error
import urllib.parse
import urllib.request
from decimal import Decimal
from typing import Any, Dict, List, Optional, Union

from .errors import AuthenticationError, HBankConnectionError, HBankError
from .models import (Payment, PaymentCode, Rate, Refund, RefundResult, Subscription, SubscriptionCheckout,
                     SubscriptionsCheckout, _dec)

DEFAULT_BASE_URL = "https://bank.thehsi.cloud"
Amount = Union[Decimal, int, str, float]


def _amount(value: Amount) -> str:
    """Amounts go over the wire as strings, which the API accepts, so no digits are lost to floats."""
    if isinstance(value, bool):
        raise TypeError("amount must be a number")
    if isinstance(value, float):
        value = repr(value)  # shortest round-trip text: 24.9 -> "24.9"
    return str(value)


class HBank:
    """Client for the HBank merchant API (v1).

    >>> bank = HBank(api_key=os.environ["HBANK_API_KEY"])
    >>> tid = bank.create_payment("24.90", "EUR", description="Order 1042",
    ...                           callback_url="https://shop.example.com/hbank/callback")
    >>> redirect(bank.checkout_url(tid))

    Thread-safe: one instance can be shared by the whole app.
    """

    def __init__(self, api_key: str, base_url: str = DEFAULT_BASE_URL, timeout: float = 30.0,
                 user_agent: str = "hbank-python/1.0"):
        if not api_key:
            raise ValueError("api_key is required")
        self.api_key = api_key
        self.base_url = base_url.rstrip("/")
        self.timeout = timeout
        self.user_agent = user_agent

    # ── Payments ─────────────────────────────────────────────

    def create_payment(self, amount: Amount, currency: str, description: Optional[str] = None,
                       callback_url: Optional[str] = None) -> str:
        """Creates a pending payment request and returns its transaction id: a random string like
        ``tx_8fK2mQ7xRb4Tn9WcYz3LpH6v`` (store it as text). It stays payable for one hour."""
        body = {"amount": _amount(amount), "currency": currency}
        _put(body, description=description, callback_url=callback_url)
        return self._post("payment/request", body)["transaction_id"]

    def create_payment_code(self, transaction_id: str) -> PaymentCode:
        """A QR code / link for a pending payment. Calling it again returns the same code."""
        d = self._post("payment/code", {"transaction_id": transaction_id})
        return PaymentCode(code=d["code"], url=d["url"], qr_svg=d["qr_svg"])

    def get_payment(self, transaction_id: str) -> Payment:
        """The current state of one of your payments. Check ``.completed`` here before handing out goods."""
        return Payment.from_json(self._post("payment/details", {"transaction_id": transaction_id})["transaction"])

    def refund(self, transaction_id: str, amount: Optional[Amount] = None, reason: Optional[str] = None) -> RefundResult:
        """Refunds a completed payment: ``amount`` in its currency, or everything that's left if omitted.

        Not safe to blindly retry after a timeout: check ``get_payment(id).refunded`` first.
        """
        body: Dict[str, Any] = {"transaction_id": transaction_id}
        if amount is not None:
            body["amount"] = _amount(amount)
        _put(body, reason=reason)
        d = self._post("payment/refund", body)
        r = d["refund"]
        return RefundResult(
            refund=Refund(id=r["id"], amount=_dec(r["amount"]), currency=r["currency"], reference=r["reference"],
                          reason=r.get("reason")),
            payment=Payment.from_json(d["transaction"]))

    def checkout_url(self, transaction_id: str) -> str:
        """The hosted checkout (card number + PIN) for a payment. Needs a ``callback_url`` on the payment."""
        return f"{self.base_url}/api/payment?tid={urllib.parse.quote(str(transaction_id), safe='')}"

    # ── Subscriptions ────────────────────────────────────────

    def create_subscription(self, amount: Amount, currency: str, interval: str, interval_count: int = 1,
                            description: Optional[str] = None) -> Subscription:
        """Offers a subscription (``interval``: day, week, month or year). Send the customer its ``url``."""
        return Subscription.from_json(
            self._post("subscriptions", _offer(amount, currency, interval, interval_count, description))["subscription"])

    def create_subscription_checkout(self, amount: Amount, currency: str, interval: str, interval_count: int = 1,
                                     description: Optional[str] = None,
                                     callback_url: Optional[str] = None) -> SubscriptionCheckout:
        """Offers a subscription and creates its first payment, for the pay button / hosted checkout."""
        body = _offer(amount, currency, interval, interval_count, description)
        _put(body, callback_url=callback_url)
        return _checkout(self._post("subscriptions/checkout", body))

    def create_subscriptions_checkout(self, subscriptions: List[Union[str, Dict[str, Any]]],
                                      description: Optional[str] = None,
                                      callback_url: Optional[str] = None) -> SubscriptionsCheckout:
        """One first payment for several subscriptions (up to 20, one currency): each item is the id of a subscription
        you offered (``"sub_…"``) or a new offer's fields as a dict (``amount``, ``currency``, ``interval``, optional
        ``interval_count`` and ``description``). Paying it starts them all; after that each renews on its own. When one
        is refused nothing is offered.

        >>> c = bank.create_subscriptions_checkout(["sub_Hk3…", {"amount": "2.50", "currency": "EUR", "interval": "week"}])
        """
        items: List[Any] = []
        for item in subscriptions:
            if isinstance(item, str):
                items.append(item)
            else:
                items.append(_offer(item["amount"], item["currency"], item["interval"], item.get("interval_count", 1),
                                    item.get("description")))
        body: Dict[str, Any] = {"subscriptions": items}
        _put(body, description=description, callback_url=callback_url)
        d = self._post("subscriptions/checkout", body)
        return SubscriptionsCheckout(transaction_id=d["transaction_id"],
                                     subscriptions=[Subscription.from_json(s) for s in d["subscriptions"]])

    def checkout_subscription(self, subscription_id: str, callback_url: Optional[str] = None) -> SubscriptionCheckout:
        """A new first payment for a subscription already offered (``not_open`` once someone subscribed)."""
        body: Dict[str, Any] = {}
        _put(body, callback_url=callback_url)
        return _checkout(self._post(f"subscriptions/{urllib.parse.quote(str(subscription_id), safe='')}/checkout", body))

    def list_subscriptions(self) -> List[Subscription]:
        """Your subscriptions, newest first (up to 100)."""
        return [Subscription.from_json(s) for s in self._get("subscriptions")["subscriptions"]]

    def get_subscription(self, subscription_id: str) -> Subscription:
        return Subscription.from_json(self._get(f"subscriptions/{urllib.parse.quote(str(subscription_id), safe='')}")["subscription"])

    def cancel_subscription(self, subscription_id: str) -> Subscription:
        """No more charges. It stays in its ``active_period`` until ``current_period_end``."""
        return Subscription.from_json(self._post(f"subscriptions/{urllib.parse.quote(str(subscription_id), safe='')}/cancel", {})["subscription"])

    # ── Currencies ───────────────────────────────────────────

    def convert(self, amount: Amount, currency_from: str, currency_to: str) -> Decimal:
        d = self._get("currency/convert", {"amount": _amount(amount), "currency_from": currency_from,
                                            "currency_to": currency_to})
        return _dec(d["amount"])

    def rate(self, currency_from: str, currency_to: str) -> Rate:
        d = self._get("currency/rate", {"currency_from": currency_from, "currency_to": currency_to})
        return Rate(to_rate=_dec(d["to_rate"]), from_rate=_dec(d["from_rate"]))

    # ── Transport ────────────────────────────────────────────

    def _get(self, path: str, query: Optional[Dict[str, str]] = None) -> Dict[str, Any]:
        suffix = "?" + urllib.parse.urlencode(query) if query else ""
        return self._send("GET", path + suffix, None)

    def _post(self, path: str, body: Dict[str, Any]) -> Dict[str, Any]:
        return self._send("POST", path, json.dumps(body).encode())

    def _send(self, method: str, path: str, data: Optional[bytes]) -> Dict[str, Any]:
        headers = {"Authorization": f"Bearer {self.api_key}", "Accept": "application/json",
                   "User-Agent": self.user_agent}
        if data is not None:
            headers["Content-Type"] = "application/json"
        req = urllib.request.Request(f"{self.base_url}/api/v1/{path}", data=data, method=method, headers=headers)
        try:
            with urllib.request.urlopen(req, timeout=self.timeout) as res:
                status, raw = res.status, res.read()
        except urllib.error.HTTPError as e:
            with e:
                status, raw = e.code, e.read()
        except (urllib.error.URLError, socket.timeout, TimeoutError, OSError) as e:
            raise HBankConnectionError("connection_failed", None, str(getattr(e, "reason", e))) from e

        text = raw.decode("utf-8", "replace")
        try:
            body = json.loads(text, parse_float=Decimal)
        except ValueError:
            body = None

        if status == 401:
            raise AuthenticationError("missing_api_key", status, text.strip() or None, text)
        if status == 403:
            raise AuthenticationError("invalid_api_key", status, text.strip() or None, text)
        if not isinstance(body, dict):
            raise HBankError("invalid_response", status, text[:200] or None, text)
        if not (200 <= status < 300) or body.get("success") is False:
            raise HBankError(str(body.get("error") or f"http_{status}"), status, body.get("message"), body)
        return body


def _put(body: Dict[str, Any], **fields: Any) -> None:
    for key, value in fields.items():
        if value is not None:
            body[key] = value


def _offer(amount: Amount, currency: str, interval: str, interval_count: int, description: Optional[str]) -> Dict[str, Any]:
    body: Dict[str, Any] = {"amount": _amount(amount), "currency": currency, "interval": interval,
                            "interval_count": interval_count}
    _put(body, description=description)
    return body


def _checkout(d: Dict[str, Any]) -> SubscriptionCheckout:
    return SubscriptionCheckout(transaction_id=d["transaction_id"], subscription=Subscription.from_json(d["subscription"]))
