import httpx
from tenacity import retry, stop_after_attempt, wait_exponential
from app.channels.base import NotificationChannel, DeliveryResult
from app.core.config import get_settings
from app.services.vk_sender import get_vk_token

settings = get_settings()


class VKAdapter(NotificationChannel):
    """VK Messages API adapter with retry logic"""
    
    @property
    def channel_name(self) -> str:
        return "vk"
    
    @retry(
        stop=stop_after_attempt(3),
        wait=wait_exponential(multiplier=1, min=2, max=10)
    )
    async def send(self, target: str, content: str, **kwargs) -> DeliveryResult:
        """
        Send message via VK Messages API
        
        Args:
            target: vk_user_id (customer.vk_user_id)
            content: message text
            kwargs: tenant_id (required)
        
        API docs: https://dev.vk.com/method/messages.send
        """
        tenant_id = kwargs.get("tenant_id")
        if not tenant_id:
            return DeliveryResult(
                success=False,
                error="tenant_id is required for VK sending"
            )
        
        # Получаем токен из БД (из активной VK группы)
        access_token = await get_vk_token(tenant_id)
        if not access_token:
            return DeliveryResult(
                success=False,
                error="No VK group configured for this tenant. Add VK group in settings."
            )
        
        url = "https://api.vk.com/method/messages.send"
        params = {
            "user_id": target,
            "message": content,
            "random_id": kwargs.get("random_id", 0),
            "access_token": access_token,
            "v": "5.131",
        }
        
        try:
            async with httpx.AsyncClient(timeout=30.0) as client:
                response = await client.post(url, params=params)
                response.raise_for_status()
                data = response.json()
                
                if "error" in data:
                    error_code = data["error"].get("error_code")
                    error_msg = data["error"].get("error_msg", "Unknown VK error")
                    
                    # Rate limit check
                    if error_code == 6:  # Too many requests per second
                        raise httpx.HTTPStatusError(
                            f"VK rate limit: {error_msg}",
                            request=response.request,
                            response=response
                        )
                    
                    return DeliveryResult(
                        success=False,
                        error=f"VK API error {error_code}: {error_msg}"
                    )
                
                if "response" in data:
                    return DeliveryResult(
                        success=True,
                        message_id=str(data["response"]),
                        response_meta=data
                    )
                else:
                    return DeliveryResult(
                        success=False,
                        error="Unexpected VK response format"
                    )
        
        except httpx.HTTPError as e:
            return DeliveryResult(
                success=False,
                error=f"HTTP error: {str(e)}"
            )
        except Exception as e:
            return DeliveryResult(
                success=False,
                error=f"Unexpected error: {str(e)}"
            )





























