# -*- coding: utf-8 -*-
"""RiskByPass API Client"""

import time
import requests


class RiskByPassClient:
    """Client for the RiskByPass task API.

    Args:
        token: Your API key.
        base_url: API base URL (default: https://riskbypass.com).
    """

    def __init__(self, token: str, base_url: str = "https://riskbypass.com"):
        self._token = token
        self._base_url = base_url.rstrip("/")

    # ------------------------------------------------------------------
    # Internal helpers
    # ------------------------------------------------------------------

    def _headers(self):
        return {
            "Content-Type": "application/json",
            "x-api-key": self._token,
        }

    def _submit_task(self, payload: dict) -> dict:
        url = f"{self._base_url}/task/submit"
        return requests.post(url, headers=self._headers(), json=payload).json()

    def _get_task_result(self, task_id: str) -> dict:
        url = f"{self._base_url}/task/result/{task_id}"
        return requests.get(url, headers=self._headers()).json()

    # ------------------------------------------------------------------
    # Public API
    # ------------------------------------------------------------------

    def run_task(self, payload: dict, timeout: int = 180) -> dict:
        """Submit a task and poll until completion.

        Args:
            payload: Task parameters (must include ``task_type``).
            timeout: Max seconds to wait before raising an error.

        Returns:
            The task result dict on success.

        Raises:
            Exception: On submission failure, timeout, or task failure.
        """
        try:
            result = self._submit_task(payload)
        except Exception as e:
            raise Exception(f"Failed to submit task: {e}")

        if not result.get("ok"):
            raise Exception(f"Failed to submit task: {result}")

        task_id = result.get("task_id")
        if not task_id:
            raise Exception(f"No task_id in response: {result}")

        start_time = time.time()
        while True:
            if time.time() - start_time > timeout:
                raise Exception(f"Task timed out after {timeout} seconds")
            time.sleep(1)
            try:
                res = self._get_task_result(task_id)
            except Exception:
                continue

            status = res.get("status")
            if status == "SUCCESS":
                return res.get("result")
            elif status in ("RUNNING", "QUEUED"):
                continue
            elif status == "FAILED":
                raise Exception(res.get("error"))
            elif status == "NOT_FOUND":
                raise Exception(f"Task expired or not exists: {task_id}")
            else:
                raise Exception(f"Unknown task status: {status}")

    def check_balance(self) -> float:
        """Return the current account balance."""
        url = f"{self._base_url}/api/user/balance"
        try:
            r = requests.post(url, json={"token": self._token}, timeout=5)
            data = r.json()
            if data.get("ok"):
                return data.get("balance")
            raise Exception(data.get("error"))
        except Exception as e:
            raise Exception(f"Failed to check balance: {e}")

    def get_topup_address(self) -> str:
        """Return the TRC-20 USDT top-up address."""
        url = f"{self._base_url}/api/usdt/wallet"
        try:
            r = requests.post(url, json={"token": self._token}, timeout=5)
            data = r.json()
            if data.get("ok"):
                return data.get("wallet", {}).get("trc20_address")
            raise Exception(data.get("error"))
        except Exception as e:
            raise Exception(f"Failed to get topup address: {e}")
