"""Wise payment integration via Wise API."""

import time
import httpx
from typing import Dict, Any, Optional
from agenticlypay.config import config


class WiseManager:
    """Manages Wise transfers via Wise API."""

    def __init__(self):
        """Initialize the Wise manager."""
        self.api_key = config.wise_api_key
        self.api_base_url = config.wise_api_base_url

    def _get_headers(self) -> Dict[str, str]:
        """
        Get headers for Wise API requests.
        
        Returns:
            Dictionary with authorization headers
        """
        if not self.api_key:
            raise ValueError("Wise API key not configured")
        
        return {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json",
        }

    def send_transfer(
        self,
        email: str,
        amount: int,  # Amount in cents
        currency: str = "USD",
        reference: Optional[str] = None,
    ) -> Dict[str, Any]:
        """
        Send a Wise transfer to an email address.
        
        Args:
            email: Recipient email address
            amount: Amount in cents (e.g., 10000 for $100.00)
            currency: Currency code (default: USD)
            reference: Optional payment reference/description
            
        Returns:
            Dictionary with transfer status
        """
        headers = self._get_headers()
        
        # Convert cents to amount with decimals for Wise API
        amount_decimal = amount / 100.0
        
        # Wise API flow: Create quote -> Create recipient -> Create transfer
        # For email-based transfers, we'll create a recipient with email first
        
        with httpx.Client() as client:
            # Step 1: Get profile ID (required for transfers)
            # Note: This may need to be configured or retrieved from account
            profile_response = client.get(
                f"{self.api_base_url}/v1/profiles",
                headers=headers,
            )
            if profile_response.status_code != 200:
                raise Exception(f"Failed to get Wise profile: {profile_response.status_code} {profile_response.text}")
            profiles = profile_response.json()
            profile_id = profiles[0].get("id") if profiles else None
            if not profile_id:
                raise Exception("No Wise profile found")
            
            # Step 2: Create quote for the transfer
            quote_data = {
                "sourceCurrency": currency,
                "targetCurrency": currency,
                "sourceAmount": amount_decimal,
            }
            quote_response = client.post(
                f"{self.api_base_url}/v3/profiles/{profile_id}/quotes",
                json=quote_data,
                headers=headers,
            )
            if quote_response.status_code not in [200, 201]:
                raise Exception(f"Failed to create Wise quote: {quote_response.status_code} {quote_response.text}")
            quote = quote_response.json()
            quote_id = quote.get("id")
            
            # Step 3: Create recipient account with email
            recipient_data = {
                "currency": currency,
                "type": "email",
                "accountHolderName": email.split("@")[0],  # Use email prefix as name
                "email": email,
            }
            recipient_response = client.post(
                f"{self.api_base_url}/v1/accounts",
                json=recipient_data,
                headers=headers,
            )
            if recipient_response.status_code not in [200, 201]:
                raise Exception(f"Failed to create Wise recipient: {recipient_response.status_code} {recipient_response.text}")
            recipient = recipient_response.json()
            recipient_id = recipient.get("id")
            
            # Step 4: Create transfer
            transfer_data = {
                "targetAccount": recipient_id,
                "quoteUuid": quote_id,
                "customerTransactionId": reference or f"payout-{int(time.time())}",
                "details": {
                    "reference": reference or f"Monthly payout to {email}",
                },
            }
            transfer_response = client.post(
                f"{self.api_base_url}/v1/transfers",
                json=transfer_data,
                headers=headers,
            )
            
            if transfer_response.status_code not in [200, 201]:
                raise Exception(f"Failed to create Wise transfer: {transfer_response.status_code} {transfer_response.text}")
            
            result = transfer_response.json()
        
        transfer_id = result.get("id")
        
        return {
            "success": True,
            "transfer_id": transfer_id,
            "email": email,
            "amount": amount,
            "amount_decimal": amount_decimal,
            "currency": currency,
            "status": result.get("status", "incoming_payment_waiting"),
            "reference": reference,
            "timestamp": time.time(),
        }

    def get_transfer_status(self, transfer_id: str) -> Dict[str, Any]:
        """
        Get the status of a Wise transfer.
        
        Args:
            transfer_id: Transfer ID from send_transfer
            
        Returns:
            Dictionary with transfer status
        """
        headers = self._get_headers()
        
        with httpx.Client() as client:
            response = client.get(
                f"{self.api_base_url}/v1/transfers/{transfer_id}",
                headers=headers,
            )

            if response.status_code != 200:
                raise Exception(f"Failed to get transfer status: {response.status_code} {response.text}")

            return response.json()
