"""Answering HBank's callback: right before charging a customer, HBank POSTs the payment to its ``callback_url``
and charges only if you answer 200 with ``{"resume": true}`` (as ``application/json``) within 10 seconds.

It's signed: check the ``HBank-Signature`` header with your business's signing secret (business settings → Callback
URLs) before you approve, with ``verify_signature``. Also check that ``id`` and ``amount`` match an order you created,
and confirm with ``HBank.get_payment`` before handing out goods.
"""

import hashlib
import hmac
import json
import time
from dataclasses import dataclass
from decimal import Decimal
from typing import Any, Dict, Mapping, Optional, Union

from .errors import HBankError


@dataclass(frozen=True)
class Callback:
    id: str  # the transaction id you got from create_payment ("tx_…")
    amount: Decimal
    currency: str
    status: str
    description: str


def parse_callback(body: Union[bytes, str, Mapping[str, Any]]) -> Callback:
    """Reads a callback request body. Raises HBankError("invalid_callback") if it doesn't look like one."""
    try:
        data = json.loads(body, parse_float=Decimal) if isinstance(body, (bytes, str)) else dict(body)
        return Callback(id=str(data["id"]), amount=Decimal(str(data["amount"])), currency=str(data["currency"]),
                        status=str(data.get("status") or ""), description=str(data.get("description") or ""))
    except (ValueError, KeyError, TypeError, ArithmeticError) as e:
        raise HBankError("invalid_callback", None, str(e)) from e


def verify_signature(secret: str, header: Optional[str], body: Union[bytes, str], tolerance: int = 300,
                     now: Optional[float] = None) -> bool:
    """Whether ``header`` (the request's ``HBank-Signature``: ``t=<unix time>,v1=<hex>``) signs ``body`` (the raw request
    body, exactly as received) with ``secret``, and was made within ``tolerance`` seconds."""
    if not secret or not header:
        return False
    parts = dict(p.split("=", 1) for p in header.split(",") if "=" in p)
    try:
        timestamp = int(parts.get("t", ""))
    except ValueError:
        return False
    if abs((time.time() if now is None else now) - timestamp) > tolerance:
        return False
    raw = body if isinstance(body, bytes) else body.encode("utf-8")
    expected = hmac.new(secret.encode("utf-8"), str(timestamp).encode("ascii") + b"." + raw, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, parts.get("v1", ""))


def approve() -> Dict[str, Any]:
    """The answer that lets HBank charge the customer. Send it as JSON with status 200."""
    return {"resume": True}


def refuse(error: Optional[str] = None) -> Dict[str, Any]:
    """The answer that refuses the payment; the customer sees ``error``. Send it as JSON with status 200."""
    return {"resume": False, "error": error} if error else {"resume": False}
