import os
import secrets
from urllib.parse import quote
import aiohttp

class CryptAPIDeposit:
    """Create persistent USDT deposit addresses for supported networks.
    The merchant wallet is the Trust Wallet-compatible address that receives forwarded funds.
    Customer private keys are never stored by this bot.
    """

    def __init__(self, network):
        self.network = network.upper()
        self.api_base = "https://api.cryptapi.io"
        if self.network == "BEP20":
            self.ticker = "bep20_usdt"
            self.merchant_address = os.getenv("USDT_BEP20_FORWARD_ADDRESS", "").strip()
        elif self.network == "":
            self.ticker = "trc20/usdt"
            self.merchant_address = os.getenv("USDT__FORWARD_ADDRESS", "").strip()
        else:
            raise ValueError("Unsupported network")
        self.public_base = os.getenv("PUBLIC_BASE_URL", "").rstrip("/")
        self.api_key = os.getenv("CRYPTAPI_API_KEY", "").strip()
        self.confirmations = int(os.getenv("USDT_CONFIRMATIONS", "3"))

    def ready(self):
        return bool(self.merchant_address and self.public_base)

    async def create_address(self, user_id, nonce):
        if not self.ready():
            raise RuntimeError(f"{self.network} merchant address and PUBLIC_BASE_URL are required")
        callback = f"{self.public_base}/webhook/cryptapi?user_id={user_id}&network={self.network}&nonce={quote(nonce)}"
        params = {
            "callback": callback,
            "address": self.merchant_address,
            "pending": 1,
            "confirmations": self.confirmations,
            "post": 1,
            "json": 1,
        }
        if self.api_key:
            params["apikey"] = self.api_key
        url = f"{self.api_base}/{self.ticker}/create/"
        async with aiohttp.ClientSession() as session:
            async with session.get(url, params=params, timeout=30) as resp:
                data = await resp.json(content_type=None)
                if resp.status != 200 or data.get("status") != "success":
                    raise RuntimeError(f"CryptAPI error: {data}")
                return data

    @staticmethod
    def webhook_amount(data):
        try:
            return float(data.get("value_coin", 0))
        except (TypeError, ValueError):
            return 0.0
