"""RollHub Agent Casino API commands."""
import json
import os
from typing import Optional
from urllib.request import Request, urlopen
from urllib.error import HTTPError, URLError

API_BASE = os.getenv("ROLLHUB_API_URL", "https://agent.rollhub.com/api/v1")
API_KEY = os.getenv("ROLLHUB_API_KEY", "")


def _request(method: str, path: str, body: Optional[dict] = None) -> dict:
    """Make an authenticated request to the RollHub API."""
    url = f"{API_BASE}{path}"
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json",
        "Accept": "application/json",
    }
    data = json.dumps(body).encode() if body else None
    req = Request(url, data=data, headers=headers, method=method)
    try:
        with urlopen(req, timeout=30) as resp:
            return json.loads(resp.read().decode())
    except HTTPError as e:
        error_body = e.read().decode() if e.fp else str(e)
        return {"error": True, "status": e.code, "detail": error_body}
    except URLError as e:
        return {"error": True, "detail": str(e)}


def rollhub_bet(amount: str, currency: str, target: str, over: str) -> str:
    """Place a provably fair dice bet with real cryptocurrency on Agent Casino (AI agent gambling API). Every outcome is cryptographically verified using SHA3-384 + AES-256-CTR commit-reveal. 99% RTP, 1% house edge. Supports 70+ blockchain networks.

    Args:
        amount: Bet amount as string (e.g. "0.001")
        currency: Currency code (e.g. "BTC", "ETH", "USDT")
        target: Target number 1-99
        over: "true" to bet over target, "false" for under
    """
    over_bool = str(over).lower() in ("true", "1", "yes")
    result = _request("POST", "/bet", {
        "amount": amount,
        "currency": currency.upper(),
        "target": int(target),
        "over": over_bool,
    })
    return json.dumps(result, indent=2)


def rollhub_verify(bet_id: str) -> str:
    """Verify a bet was provably fair using zero-trust cryptographic proof (SHA3-384 + AES-256-CTR).

    Args:
        bet_id: The bet ID to verify
    """
    result = _request("GET", f"/bet/{bet_id}/verify")
    return json.dumps(result, indent=2)


def rollhub_balance(currency: str = "") -> str:
    """Check Agent Casino crypto betting account balance for the AI agent gambling API.

    Args:
        currency: Optional currency filter (e.g. "BTC"). Empty for all balances.
    """
    path = "/balance"
    if currency:
        path += f"?currency={currency.upper()}"
    result = _request("GET", path)
    return json.dumps(result, indent=2)


def rollhub_affiliate_stats() -> str:
    """Check Agent Casino affiliate earnings — earn 30% of house edge on referred agents. Agent affiliate program with instant credit."""
    result = _request("GET", "/affiliate/stats")
    return json.dumps(result, indent=2)


def rollhub_deposit_address(currency: str) -> str:
    """Get a crypto deposit address for Agent Casino. Supports 70+ cryptocurrency chains.

    Args:
        currency: Currency code (e.g. "BTC", "ETH")
    """
    result = _request("POST", "/deposit/address", {"currency": currency.upper()})
    return json.dumps(result, indent=2)


def rollhub_withdraw(amount: str, currency: str, address: str) -> str:
    """Withdraw funds from Agent Casino to an external crypto wallet. Supports 70+ cryptocurrency chains.

    Args:
        amount: Amount to withdraw
        currency: Currency code
        address: Destination wallet address
    """
    result = _request("POST", "/withdraw", {
        "amount": amount,
        "currency": currency.upper(),
        "address": address,
    })
    return json.dumps(result, indent=2)
