# llm_manager/chat.py
"""交互式聊天模块"""

import sys
from typing import Optional
from .config import ConfigManager
from .api_client import APIClient


class ChatSession:
    """交互式聊天会话"""
    
    def __init__(
        self,
        config: ConfigManager,
        endpoint_name: Optional[str] = None,
        model: Optional[str] = None,
        random_mode: bool = False
    ):
        self.config = config
        self.client = APIClient(config)
        self.messages: list[dict] = []
        self.random_mode = random_mode
        
        if random_mode:
            self.endpoint, self.model = self.client.get_random_endpoint_and_model(endpoint_name)
        else:
            if endpoint_name is None:
                raise ValueError("非随机模式必须指定端点名称")
            
            self.endpoint = config.get_endpoint(endpoint_name)
            if self.endpoint is None:
                raise ValueError(f"未找到端点: {endpoint_name}")
            
            if model:
                if model not in self.endpoint.models:
                    raise ValueError(f"模型 '{model}' 不在端点 '{endpoint_name}' 的可用模型列表中")
                self.model = model
            else:
                if not self.endpoint.models:
                    raise ValueError(f"端点 '{endpoint_name}' 没有可用的模型")
                self.model = self.endpoint.models[0]
    
    def chat(self, user_message: str, stream: bool = True) -> str:
        """发送消息并获取回复"""
        self.messages.append({"role": "user", "content": user_message})
        
        full_response = ""
        
        if stream:
            for chunk in self.client.chat_completion(
                self.endpoint,
                self.model,
                self.messages,
                stream=True
            ):
                print(chunk, end="", flush=True)
                full_response += chunk
            print()  # 换行
        else:
            response = self.client.chat_completion(
                self.endpoint,
                self.model,
                self.messages,
                stream=False
            )
            full_response = response["choices"][0]["message"]["content"]
            print(full_response)
        
        self.messages.append({"role": "assistant", "content": full_response})
        return full_response
    
    def run_interactive(self):
        """运行交互式聊天"""
        print(f"开始与 {self.endpoint.name}/{self.model} 对话")
        print("输入 'quit' 或 'exit' 退出，'clear' 清除历史\n")
        
        while True:
            try:
                user_input = input("\n你: ").strip()
                
                if not user_input:
                    continue
                
                if user_input.lower() in ("quit", "exit"):
                    print("再见！")
                    break
                
                if user_input.lower() == "clear":
                    self.messages = []
                    print("历史已清除")
                    continue
                
                print("\n助手: ", end="")
                self.chat(user_input)
                
            except KeyboardInterrupt:
                print("\n再见！")
                break
            except Exception as e:
                print(f"\n错误: {e}")
