import os
from typing import Optional, Dict, Any
from backend.config import config


class LLMService:
    """LLM服务封装"""
    
    _instance: Optional['LLMService'] = None
    
    def __init__(self, api_key: Optional[str] = None, model: str = "gpt-4"):
        self.api_key = api_key or config.llm_api_key
        self.model = model
        self.client = None
    
    @classmethod
    def get_instance(cls) -> 'LLMService':
        if cls._instance is None:
            cls._instance = cls()
        return cls._instance
    
    def _get_client(self):
        """获取OpenAI客户端"""
        if self.client is None and self.api_key:
            try:
                from openai import OpenAI
                self.client = OpenAI(api_key=self.api_key)
            except ImportError:
                return None
        return self.client
    
    def chat(self, prompt: str, system: Optional[str] = None) -> str:
        """通用对话"""
        client = self._get_client()
        
        if client is None:
            raise Exception("LLM client not available. Please check OPENAI_API_KEY.")
        
        messages = []
        if system:
            messages.append({"role": "system", "content": system})
        messages.append({"role": "user", "content": prompt})
        
        response = client.chat.completions.create(
            model=self.model,
            messages=messages
        )
        
        return response.choices[0].message.content
    
    def analyze_image(self, image_path: str, prompt: str) -> str:
        """分析图片"""
        client = self._get_client()
        
        if client is None:
            raise Exception("LLM client not available")
        
        response = client.chat.completions.create(
            model="gpt-4-vision-preview",
            messages=[{
                "role": "user",
                "content": [
                    {"type": "text", "text": prompt},
                    {"type": "image_url", "image_url": {"url": f"file://{image_path}"}}
                ]
            }]
        )
        return response.choices[0].message.content
    
    def is_available(self) -> bool:
        """检查LLM是否可用"""
        try:
            client = self._get_client()
            if client is None:
                return False
            # 简单测试
            self.chat("Hello")
            return True
        except Exception:
            return False


def get_llm_service() -> LLMService:
    """获取LLM服务实例"""
    return LLMService.get_instance()
