"""CLI 工具 - 使用 click 构建"""

import os
import sys
import threading
from pathlib import Path

import click
import uvicorn
import yaml


def get_default_config():
    """获取默认配置"""
    return {
        "version": "1.0",
        "settings": {
            "app_name": "LumiDesktop",
            "language": "zh-CN",
            "theme": "auto",
            "auto_start": False,
            "webui_port": 52342,
            "api_port": 52341,
            "data_dir": "./",
        },
        "providers": {
            "deepseek": {
                "name": "DeepSeek",
                "base_url": "https://api.deepseek.com/v1",
                "api_key": "",  # 直接填写 API Key，或留空
                "models": ["deepseek-chat", "deepseek-reasoner"],
                "enabled": True,
                "default_model": "deepseek-chat",
                "max_tokens": 4096,
                "temperature": 0.7,
            },
            "openai": {
                "name": "OpenAI",
                "base_url": "https://api.openai.com/v1",
                "api_key": "",  # 直接填写 API Key，或留空
                "models": ["gpt-4o-mini", "gpt-4o"],
                "enabled": False,
                "default_model": "gpt-4o-mini",
                "max_tokens": 4096,
                "temperature": 0.7,
            },
        },
        "prompts": {
            "assistant": {
                "name": "智能助手",
                "content": "你是一个友好的AI助手，乐于帮助用户解决问题。",
                "enabled": True,
                "default": True,
            },
            "translator": {
                "name": "翻译专家",
                "content": "你是一个专业的翻译助手，精通多种语言，能够准确翻译并保持原文风格。",
                "enabled": True,
                "default": False,
            },
            "creative": {
                "name": "创意伙伴",
                "content": "你是一个富有创造力的伙伴，擅长讲故事、写诗和创意写作。",
                "enabled": True,
                "default": False,
            },
        },
        "live2d_models": [
            {
                "id": "shizuku",
                "name": "Shizuku",
                "path": "models/shizuku/shizuku.model3.json",
                "scale": 1.0,
                "x": 0,
                "y": 0,
                "enabled": True,
                "default": True,
            }
        ],
        "chat": {"max_history": 50, "save_history": True, "history_file": "chat_history.json"},
    }


@click.group()
@click.version_option(version="1.0.0", prog_name="lumi")
def main():
    """LumiServer - LumiDesktop 后端服务 CLI 工具"""
    pass


@main.command()
@click.option("--force", is_flag=True, help="强制覆盖已存在的配置文件")
@click.option("--data-dir", default=None, help="指定数据目录（默认为当前目录）")
def init(force, data_dir):
    """初始化配置文件和数据目录"""
    # 确定数据目录
    if data_dir:
        data_path = Path(data_dir).resolve()
    else:
        data_path = Path.cwd()
    
    # 创建数据目录（如果不存在）
    data_path.mkdir(parents=True, exist_ok=True)
    
    config_file = data_path / "config.yaml"
    models_dir = data_path / "models"
    backups_dir = data_path / "backups"

    click.echo(f"📁 数据目录: {data_path}")

    # 检查配置文件是否已存在
    if config_file.exists() and not force:
        click.echo(f"⚠️  配置文件已存在: {config_file}")
        if not click.confirm("是否覆盖现有配置？"):
            click.echo("❌ 初始化已取消")
            return

    # 创建配置文件
    try:
        config_data = get_default_config()
        # 更新数据目录路径
        config_data["settings"]["data_dir"] = str(data_path)
        
        with open(config_file, "w", encoding="utf-8") as f:
            yaml.safe_dump(config_data, f, allow_unicode=True, default_flow_style=False, sort_keys=False)
        click.echo(f"✅ 配置文件已创建: {config_file}")
    except Exception as e:
        click.echo(f"❌ 创建配置文件失败: {e}", err=True)
        sys.exit(1)

    # 创建必要的子目录
    try:
        models_dir.mkdir(exist_ok=True)
        (models_dir / ".gitkeep").touch()
        click.echo(f"✅ 模型目录已创建: {models_dir}")
        
        backups_dir.mkdir(exist_ok=True)
        (backups_dir / ".gitkeep").touch()
        click.echo(f"✅ 备份目录已创建: {backups_dir}")
    except Exception as e:
        click.echo(f"❌ 创建目录失败: {e}", err=True)
        sys.exit(1)



    # 创建 README
    readme_file = data_path / "README.txt"
    try:
        with open(readme_file, "w", encoding="utf-8") as f:
            f.write("LumiDesktop 数据目录\n")
            f.write("=" * 50 + "\n\n")
            f.write("目录结构:\n")
            f.write("  config.yaml       - 配置文件（包含 API 密钥）\n")
            f.write("  models/           - Live2D 模型文件\n")
            f.write("  backups/          - 配置备份\n")
            f.write("  chat_history.json - 聊天历史（运行后生成）\n\n")
            f.write("使用说明:\n")
            f.write("  1. 编辑 config.yaml，在 providers 中填入 API 密钥\n")
            f.write("     例如: api_key: \"sk-xxxxx\"\n")
            f.write("  2. 将 Live2D 模型放入 models/ 目录\n")
            f.write("  3. 运行 'lumi serve' 启动服务\n\n")
            f.write(f"数据目录: {data_path}\n")
        click.echo(f"✅ 说明文件已创建: {readme_file}")
    except Exception as e:
        click.echo(f"⚠️  创建说明文件失败: {e}")

    click.echo("\n🎉 初始化完成！")
    click.echo(f"\n📂 数据目录: {data_path}")
    click.echo("\n目录结构:")
    click.echo("  ├── config.yaml       (配置文件，包含 API 密钥)")
    click.echo("  ├── models/           (Live2D 模型)")
    click.echo("  ├── backups/          (配置备份)")
    click.echo("  └── README.txt        (说明文件)")
    click.echo("\n下一步:")
    click.echo("  1. 编辑 config.yaml，在 providers 中填入 API 密钥")
    click.echo("     例如: deepseek.api_key: \"sk-xxxxx\"")
    click.echo("  2. 将 Live2D 模型文件放入 models/ 目录")
    click.echo("  3. 运行 'lumi serve' 启动服务")


@main.command()
@click.option("--host", default="0.0.0.0", help="监听地址")
@click.option("--port", default=52341, help="监听端口")
@click.option("--config", default="config.yaml", help="配置文件路径")
@click.option("--no-tray", is_flag=True, help="不显示系统托盘图标")
def serve(host, port, config, no_tray):
    """启动 FastAPI 服务器"""
    config_path = Path(config)

    # 检查配置文件是否存在
    if not config_path.exists():
        click.echo(f"❌ 配置文件不存在: {config_path}", err=True)
        click.echo("💡 请先运行 'lumi init' 初始化配置", err=True)
        sys.exit(1)

    # 设置环境变量
    os.environ["LUMI_CONFIG_PATH"] = str(config_path.absolute())

    click.echo(f"🚀 启动 LumiServer...")
    click.echo(f"📁 配置文件: {config_path.absolute()}")
    click.echo(f"🌐 监听地址: {host}:{port}")

    if no_tray:
        # 直接运行 Uvicorn（前台模式）
        from .main import app

        uvicorn.run(app, host=host, port=port, log_level="info")
    else:
        # 后台运行 + 系统托盘
        run_with_tray(host, port, config_path)


def run_with_tray(host: str, port: int, config_path: Path):
    """在后台运行服务并显示系统托盘图标"""
    try:
        import pystray
        from PIL import Image, ImageDraw
    except ImportError:
        click.echo("❌ 系统托盘功能需要 pystray 和 Pillow 库", err=True)
        click.echo("💡 请运行: pip install pystray pillow", err=True)
        sys.exit(1)

    # 创建托盘图标
    def create_icon_image():
        """创建简单的托盘图标"""
        width = 64
        height = 64
        image = Image.new("RGB", (width, height), "white")
        dc = ImageDraw.Draw(image)
        dc.rectangle([0, 0, width, height], fill="blue")
        dc.ellipse([16, 16, 48, 48], fill="white")
        return image

    # Uvicorn 服务器线程
    server_thread = None
    server_should_stop = threading.Event()

    def start_server():
        """启动 FastAPI 服务器"""
        from .main import app

        config = uvicorn.Config(app, host=host, port=port, log_level="info")
        server = uvicorn.Server(config)
        server.run()

    def on_open_data_dir(icon, item):
        """打开数据目录"""
        data_dir = config_path.parent
        if sys.platform == "win32":
            os.startfile(data_dir)
        elif sys.platform == "darwin":
            os.system(f'open "{data_dir}"')
        else:
            os.system(f'xdg-open "{data_dir}"')

    def on_open_desktop_app(icon, item):
        """打开桌面应用"""
        click.echo("💡 桌面应用启动功能待实现")
        # TODO: 启动 Tauri 应用

    def on_quit(icon, item):
        """退出应用"""
        click.echo("👋 正在关闭服务...")
        server_should_stop.set()
        icon.stop()

    # 创建托盘菜单
    menu = pystray.Menu(
        pystray.MenuItem("LumiServer", lambda: None, enabled=False),
        pystray.Menu.SEPARATOR,
        pystray.MenuItem("打开数据目录", on_open_data_dir),
        pystray.MenuItem("打开桌面应用", on_open_desktop_app),
        pystray.Menu.SEPARATOR,
        pystray.MenuItem("退出", on_quit),
    )

    # 创建托盘图标
    icon = pystray.Icon("lumiserver", create_icon_image(), "LumiServer", menu)

    # 启动服务器线程
    server_thread = threading.Thread(target=start_server, daemon=True)
    server_thread.start()

    click.echo("✅ 服务已启动（后台运行）")
    click.echo(f"📡 API 地址: http://{host}:{port}")
    click.echo(f"📚 API 文档: http://{host}:{port}/docs")
    click.echo("💡 查看系统托盘图标以管理服务")

    # 运行托盘图标（阻塞）
    icon.run()

    # 等待服务器线程结束
    if server_thread and server_thread.is_alive():
        server_thread.join(timeout=5)


if __name__ == "__main__":
    main()
