import httpx
import json
import base64
import os
from typing import Optional
from backend.config import config


class SiliconFlowClient:
    """硅基流动API客户端 - 支持语音转写"""
    
    def __init__(
        self,
        api_key: Optional[str] = None,
        base_url: str = "https://api.siliconflow.cn/v1"
    ):
        self.api_key = api_key or config.siliconflow_api_key or ""
        if not self.api_key:
            raise ValueError("SiliconFlow API Key未配置，请设置环境变量 SILICONFLOW_API_KEY 或在配置文件中设置")
        self.base_url = base_url
        self._client: Optional[httpx.AsyncClient] = None
    
    async def _get_client(self) -> httpx.AsyncClient:
        if self._client is None:
            self._client = httpx.AsyncClient(timeout=300.0)
        return self._client
    
    async def close(self):
        if self._client:
            await self._client.aclose()
            self._client = None
    
    async def transcribe_audio(
        self,
        audio_file_path: str,
        model: str = "FunAudioLLM/SenseVoiceSmall"
    ) -> str:
        """
        语音转写 - 使用硅基流动API (OpenAI兼容格式)
        支持的中文模型:
        - FunAudioLLM/SenseVoiceSmall (推荐，对中文效果好)
        - paraformer/paraformer-v2 (讯飞模型)
        """
        client = await self._get_client()
        
        # 获取文件扩展名
        ext = os.path.splitext(audio_file_path)[1].lower()
        format_map = {
            '.mp3': 'mp3', '.wav': 'wav', '.m4a': 'm4a', 
            '.ogg': 'ogg', '.flac': 'flac', '.webm': 'webm'
        }
        audio_format = format_map.get(ext, 'mp3')
        
        # 使用multipart/form-data格式
        url = f"{self.base_url}/audio/transcriptions"
        
        with open(audio_file_path, "rb") as f:
            audio_data = f.read()
        
        files = {
            'file': (os.path.basename(audio_file_path), audio_data, f'audio/{audio_format}'),
            'model': (None, model)
        }
        
        headers = {
            "Authorization": f"Bearer {self.api_key}"
        }
        
        try:
            response = await client.post(url, files=files, headers=headers)
        except Exception as e:
            raise Exception(f"API request failed: {e}")
        
        if response.status_code != 200:
            raise Exception(f"SiliconFlow transcription failed: {response.status_code} - {response.text}")
        
        result = response.json()
        
        # 提取转写文本
        text = ""
        if "text" in result:
            text = result["text"]
        
        return text
    
    async def is_available(self) -> bool:
        """检查服务是否可用"""
        try:
            client = await self._get_client()
            url = f"{self.base_url}/user/info"
            headers = {"Authorization": f"Bearer {self.api_key}"}
            response = await client.get(url, headers=headers)
            return response.status_code == 200
        except Exception:
            return False


# 全局客户端
_siliconflow_client: Optional[SiliconFlowClient] = None


def get_siliconflow_client() -> SiliconFlowClient:
    global _siliconflow_client
    if _siliconflow_client is None:
        _siliconflow_client = SiliconFlowClient()
    return _siliconflow_client
