#!/usr/bin/env python3
"""Bet-Flow Merchant API — example signed requests."""

from __future__ import annotations

import hashlib
import hmac
import json
import time
import uuid
from typing import Any
from urllib.parse import urlencode

try:
    import requests
except ImportError:
    requests = None  # type: ignore


API_KEY = "YOUR_PUBLIC_KEY"
SECRET = "YOUR_SECRET_KEY"
BASE_URL = "https://api.bet-flow.com/v1"


def sign_headers(method: str, body: dict[str, Any] | None = None, query: dict[str, str] | None = None) -> dict[str, str]:
    expires = str(int(time.time()) + 300)
    nonce = str(uuid.uuid4())

    if method.upper() == "GET":
        payload = urlencode(query or {})
    else:
        payload = json.dumps(body or {}, separators=(",", ":"), ensure_ascii=False)

    message = expires + payload
    signature = hmac.new(SECRET.encode(), message.encode(), hashlib.sha256).hexdigest()

    return {
        "Content-Type": "application/json",
        "X-API-Key": API_KEY,
        "Expires": expires,
        "X-API-Sign": signature,
        "X-Nonce": nonce,
    }


def verify_webhook(secret: str, raw_body: bytes, signature: str) -> bool:
    expected = hmac.new(secret.encode(), raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, signature)


def create_payin(external_id: str, amount: str, currency: str = "RUB") -> dict[str, Any]:
    if requests is None:
        raise RuntimeError("pip install requests")

    body = {
        "externalID": external_id,
        "currency": currency,
        "amount": amount,
        "type": "card",
        "bank": "any",
    }
    headers = sign_headers("POST", body=body)
    resp = requests.post(f"{BASE_URL}/payin", json=body, headers=headers, timeout=30)
    resp.raise_for_status()
    return resp.json()


def get_payin(order_id: str) -> dict[str, Any]:
    if requests is None:
        raise RuntimeError("pip install requests")

    query = {"id": order_id}
    headers = sign_headers("GET", query=query)
    resp = requests.get(f"{BASE_URL}/payin", params=query, headers=headers, timeout=30)
    resp.raise_for_status()
    return resp.json()


if __name__ == "__main__":
    print("Example: create PayIn")
    print(create_payin("demo-order-001", "1000.00"))
