"""Peak.fo API Client"""

import requests
from typing import Optional, Dict, Any
from .exceptions import PeakError, AuthenticationError, InsufficientBalanceError, SolveError, TaskDisabledError


class PeakClient:
    """
    Peak.fo API Client for solving captcha challenges.
    
    Usage:
        client = PeakClient("pk_your_api_key")
        
        # Solve Turnstile
        result = client.solve_turnstile(
            sitekey="0x4AAAAAAXXXXXXX",
            url="https://example.com/",
            proxy="http://user:pass@ip:port"
        )
        print(result["token"])
        
        # Solve CloudFlare WAF
        result = client.solve_cloudflare_waf(
            url="https://example.com/",
            proxy="http://user:pass@ip:port"
        )
        print(result["cookies"])
        
        # Solve AWS WAF
        result = client.solve_aws_waf(
            url="https://example.com/",
            sdk_url="https://xxx.edge.sdk.awswaf.com/xxx/xxx",
            proxy="http://user:pass@ip:port",
            user_agent="App/1.0 (iOS 17.0)",
            os="ios"
        )
        print(result["token"])
    """
    
    BASE_URL = "https://api.peak.fo"
    
    def __init__(self, api_key: str, base_url: Optional[str] = None):
        """
        Initialize Peak.fo client.
        
        Args:
            api_key: Your Peak.fo API key (starts with pk_)
            base_url: Optional custom base URL
        """
        self.api_key = api_key
        self.base_url = base_url or self.BASE_URL
        self.session = requests.Session()
        self.session.headers.update({
            "X-API-Key": api_key,
            "Content-Type": "application/json"
        })
    
    def _request(self, method: str, endpoint: str, data: Optional[Dict] = None) -> Dict[str, Any]:
        """Make API request and handle errors."""
        url = f"{self.base_url}{endpoint}"
        
        try:
            if method == "GET":
                response = self.session.get(url, timeout=120)
            else:
                response = self.session.post(url, json=data, timeout=120)
            
            result = response.json()
            
            if not result.get("success", False):
                error = result.get("error", "Unknown error")
                
                if "authentication" in error.lower() or "invalid api key" in error.lower():
                    raise AuthenticationError(error)
                elif "insufficient balance" in error.lower():
                    raise InsufficientBalanceError(error)
                elif "disabled" in error.lower():
                    raise TaskDisabledError(error)
                else:
                    raise SolveError(error)
            
            return result.get("data", result)
            
        except requests.exceptions.RequestException as e:
            raise PeakError(f"Request failed: {e}")
    
    def get_balance(self) -> Dict[str, Any]:
        """
        Get account balance information.
        
        Returns:
            dict: Balance info with 'type' and 'balance' or package details
        """
        return self._request("GET", "/balance")
    
    def solve_turnstile(
        self,
        sitekey: str,
        url: str,
        proxy: str,
        action: Optional[str] = None,
        cdata: Optional[str] = None
    ) -> Dict[str, str]:
        """
        Solve CloudFlare Turnstile challenge.
        
        Args:
            sitekey: Turnstile sitekey (0x4AAAAA...)
            url: Page URL where Turnstile appears
            proxy: Proxy in format http://user:pass@ip:port
            action: Optional Turnstile action parameter
            cdata: Optional Turnstile cdata parameter
            
        Returns:
            dict: {"token": "turnstile_token_here"}
        """
        data = {
            "task_type": "turnstiletask",
            "sitekey": sitekey,
            "url": url,
            "proxy": proxy
        }
        
        if action:
            data["action"] = action
        if cdata:
            data["cdata"] = cdata
            
        return self._request("POST", "/solve", data)
    
    def solve_cloudflare_waf(
        self,
        url: str,
        proxy: str
    ) -> Dict[str, Any]:
        """
        Solve CloudFlare WAF 5-second challenge.
        
        Note: URL must end with trailing slash. Only Windows Chrome user agents supported.
        
        Args:
            url: Target URL (must end with /)
            proxy: Proxy in format http://user:pass@ip:port
            
        Returns:
            dict: {"cookies": {...}, "user_agent": "..."}
        """
        # Ensure trailing slash
        if not url.endswith("/"):
            url += "/"
            
        data = {
            "task_type": "cloudflare5stask",
            "url": url,
            "proxy": proxy
        }
        
        return self._request("POST", "/solve", data)
    
    def solve_aws_waf(
        self,
        url: str,
        sdk_url: str,
        proxy: str,
        user_agent: str,
        os: str = "ios"
    ) -> Dict[str, str]:
        """
        Solve AWS WAF challenge for mobile SDK.
        
        Note: This is for iOS/Android mobile apps only, not web browsers.
        
        Args:
            url: App's base URL (e.g., https://app.example.com/)
            sdk_url: AWS WAF SDK endpoint (https://xxx.edge.sdk.awswaf.com/xxx/xxx)
            proxy: Proxy in format http://user:pass@ip:port
            user_agent: Mobile app user agent (e.g., "AppName/1.0 (iOS 17.0)")
            os: Operating system - "ios" or "android"
            
        Returns:
            dict: {"token": "aws_waf_token_here"}
        """
        data = {
            "task_type": "awswaftask",
            "url": url,
            "sdk_url": sdk_url,
            "proxy": proxy,
            "user_agent": user_agent,
            "os": os
        }
        
        return self._request("POST", "/solve", data)
