"""DeepSeek API client for enhancement service."""

import asyncio
import logging
from typing import Any, Dict

import deepseek
from tenacity import AsyncRetrying, stop_after_attempt, wait_exponential, retry_if_exception_type

from .errors import EnhancementError

logger = logging.getLogger(__name__)


class DeepSeekAPIClient:
    """DeepSeek API client for transcript enhancement."""

    def __init__(self, api_key: str, model: str = "deepseek-chat"):
        """Initialize DeepSeek API client.

        Args:
            api_key: DeepSeek API key
            model: Model to use for enhancement

        """
        self.client = deepseek.DeepSeekAPI(
            api_key=api_key,
            base_url="https://api.deepseek.com"
        )
        self.model = model

    async def enhance_text(self, prompt: str, **kwargs) -> str:
        """Enhance text using DeepSeek API.

        Args:
            prompt: Enhancement prompt
            **kwargs: API parameters

        Returns:
            Enhanced text from API

        Raises:
            EnhancementError: If API call fails

        """
        max_retries = kwargs.get("max_retries", 3)
        retry_delay = kwargs.get("retry_delay", 1.0)

        async for attempt in AsyncRetrying(
            stop=stop_after_attempt(max_retries),
            wait=wait_exponential(multiplier=retry_delay),
            retry=retry_if_exception_type((Exception,))
        ):
            with attempt:
                try:
                    response = await self.client.chat.completions.create(
                        model=self.model,
                        messages=[
                            {
                                "role": "system",
                                "content": "You are an expert at improving transcript quality. Fix punctuation, capitalization, technical terms, and formatting while preserving the original meaning and structure."
                            },
                            {
                                "role": "user",
                                "content": prompt
                            }
                        ],
                        temperature=kwargs.get("temperature", 0.0),
                        max_tokens=kwargs.get("max_tokens", 4096),
                        stream=False
                    )

                    if not response.choices:
                        raise EnhancementError(
                            "Empty response from DeepSeek API",
                            error_type="api_error"
                        )

                    enhanced_text = response.choices[0].message.content.strip()
                    
                    if not enhanced_text:
                        raise EnhancementError(
                            "Empty enhanced text from DeepSeek API",
                            error_type="api_error"
                        )

                    return enhanced_text

                except Exception as e:
                    logger.warning(f"DeepSeek API call failed (attempt {attempt.retry_state.attempt_number}): {e}")
                    if attempt.retry_state.attempt_number == max_retries:
                        raise EnhancementError(
                            f"DeepSeek API call failed after {max_retries} attempts: {e}",
                            error_type="api_error",
                            retry_count=max_retries
                        )
                    raise
