# llm_manager/cli.py
"""命令行接口"""

import argparse
import sys
import json
from pathlib import Path
from typing import Optional

from .config import ConfigManager, APIEndpoint
from .api_client import APIClient
from .chat import ChatSession


def cmd_add(args, config: ConfigManager):
    """添加新的 API 端点"""
    client = APIClient(config)
    
    endpoint = APIEndpoint(
        name=args.name,
        url=args.url,
        token=args.token,
        models=[]
    )
    
    print(f"正在获取 {args.name} 的可用模型...")
    try:
        models = client.fetch_models(endpoint)
        endpoint.models = models
        print(f"发现 {len(models)} 个模型")
    except Exception as e:
        print(f"警告: 无法获取模型列表: {e}")
        if not args.force:
            print("使用 --force 强制添加")
            return 1
    
    config.add_endpoint(endpoint)
    print(f"已添加端点: {args.name}")
    return 0


def cmd_remove(args, config: ConfigManager):
    """删除 API 端点"""
    if config.remove_endpoint(args.name):
        print(f"已删除端点: {args.name}")
        return 0
    else:
        print(f"未找到端点: {args.name}")
        return 1


def cmd_list(args, config: ConfigManager):
    """列出所有端点和模型"""
    endpoints = config.get_all_endpoints()
    
    if not endpoints:
        print("没有配置任何端点")
        return 0
    
    for name, endpoint in endpoints.items():
        print(f"\n[{name}]")
        print(f"  URL: {endpoint.url}")
        print(f"  Token: {endpoint.token[:8]}...{endpoint.token[-4:]}" if len(endpoint.token) > 12 else f"  Token: {endpoint.token}")
        print(f"  模型 ({len(endpoint.models)}):")
        for model in endpoint.models:
            print(f"    - {model}")
    
    return 0


def cmd_refresh(args, config: ConfigManager):
    """刷新模型列表"""
    client = APIClient(config)
    
    if args.name:
        endpoints = {args.name: config.get_endpoint(args.name)}
        if endpoints[args.name] is None:
            print(f"未找到端点: {args.name}")
            return 1
    else:
        endpoints = config.get_all_endpoints()
    
    for name, endpoint in endpoints.items():
        print(f"正在刷新 {name} 的模型列表...")
        try:
            models = client.fetch_models(endpoint)
            config.update_models(name, models)
            print(f"  发现 {len(models)} 个模型")
        except Exception as e:
            print(f"  错误: {e}")
    
    return 0


def cmd_chat(args, config: ConfigManager):
    """开始聊天"""
    try:
        session = ChatSession(
            config,
            endpoint_name=args.name,
            model=args.model,
            random_mode=args.random
        )
        
        if args.message:
            # 单次消息模式
            session.chat(args.message, stream=not args.no_stream)
        else:
            # 交互模式
            session.run_interactive()
        
        return 0
    except Exception as e:
        print(f"错误: {e}")
        return 1


def cmd_import(args, config: ConfigManager):
    """从配置文件导入"""
    try:
        with open(args.file, "r", encoding="utf-8") as f:
            data = json.load(f)
    except Exception as e:
        print(f"读取文件失败: {e}")
        return 1
    
    client = APIClient(config)
    
    for item in data.get("endpoints", []):
        name = item.get("name")
        url = item.get("url")
        token = item.get("token")
        
        if not all([name, url, token]):
            print(f"跳过无效配置: {item}")
            continue
        
        endpoint = APIEndpoint(name=name, url=url, token=token, models=[])
        
        print(f"正在添加 {name}...")
        try:
            models = client.fetch_models(endpoint)
            endpoint.models = models
            print(f"  发现 {len(models)} 个模型")
        except Exception as e:
            print(f"  警告: 无法获取模型列表: {e}")
        
        config.add_endpoint(endpoint)
    
    print("导入完成")
    return 0


def main():
    parser = argparse.ArgumentParser(
        prog="llm",
        description="OpenAI 兼容 API 管理工具"
    )
    parser.add_argument("--config-dir", type=Path, help="自定义配置目录")
    
    subparsers = parser.add_subparsers(dest="command", help="可用命令")
    
    # add 命令
    add_parser = subparsers.add_parser("add", help="添加 API 端点")
    add_parser.add_argument("name", help="端点名称（分组标识）")
    add_parser.add_argument("--url", "-u", required=True, help="API URL")
    add_parser.add_argument("--token", "-t", required=True, help="API Token")
    add_parser.add_argument("--force", "-f", action="store_true", help="即使获取模型失败也添加")
    
    # remove 命令
    remove_parser = subparsers.add_parser("remove", help="删除 API 端点")
    remove_parser.add_argument("name", help="端点名称")
    
    # list 命令
    subparsers.add_parser("list", help="列出所有端点和模型")
    
    # refresh 命令
    refresh_parser = subparsers.add_parser("refresh", help="刷新模型列表")
    refresh_parser.add_argument("--name", "-n", help="指定端点名称（不指定则刷新全部）")
    
    # chat 命令
    chat_parser = subparsers.add_parser("chat", help="开始对话")
    chat_parser.add_argument("--name", "-n", help="指定端点名称")
    chat_parser.add_argument("--model", "-m", help="指定模型")
    chat_parser.add_argument("--random", "-r", action="store_true", help="随机选择端点和模型")
    chat_parser.add_argument("--message", "-M", help="单次消息（不进入交互模式）")
    chat_parser.add_argument("--no-stream", action="store_true", help="禁用流式输出")
    
    # import 命令
    import_parser = subparsers.add_parser("import", help="从 JSON 文件导入配置")
    import_parser.add_argument("file", type=Path, help="配置文件路径")
    
    args = parser.parse_args()
    
    if not args.command:
        parser.print_help()
        return 0
    
    config = ConfigManager(args.config_dir)
    
    commands = {
        "add": cmd_add,
        "remove": cmd_remove,
        "list": cmd_list,
        "refresh": cmd_refresh,
        "chat": cmd_chat,
        "import": cmd_import,
    }
    
    return commands[args.command](args, config)


if __name__ == "__main__":
    sys.exit(main())
