"""
状态栏图标模块 - 使用 rumps 实现 macOS 状态栏图标
"""
try:
    import rumps
    import threading
    from typing import Callable, Optional
    import logging
    logger = logging.getLogger(__name__)
    RUMPS_AVAILABLE = True
except ImportError:
    rumps = None
    import logging
    logger = logging.getLogger(__name__)
    logger.warning("rumps 未安装，状态栏功能将不可用。请运行: pip install rumps")
    RUMPS_AVAILABLE = False


if RUMPS_AVAILABLE:
    class MenuBarApp(rumps.App):
        """状态栏应用"""
        
        def __init__(self, on_open_gui: Optional[Callable] = None, on_test_speech: Optional[Callable] = None):
            """
            初始化状态栏应用
            
            Args:
                on_open_gui: 打开GUI的回调函数
                on_test_speech: 测试语音的回调函数
            """
            super(MenuBarApp, self).__init__("J", title="J")
            self.on_open_gui = on_open_gui
            self.on_test_speech = on_test_speech
            self._create_menu()
            logger.info("状态栏图标初始化完成")
        
        def _create_menu(self):
            """创建菜单"""
            # 运行状态
            self.menu = [
                rumps.MenuItem("✅ 正在运行", callback=None),
                None,  # 分隔线
                rumps.MenuItem("🖥️ 打开主界面", callback=self._on_open_gui),
                rumps.MenuItem("🔊 测试语音", callback=self._on_test_speech),
                rumps.MenuItem("📄 查看日志", callback=self._on_view_logs),
                None,  # 分隔线
                rumps.MenuItem("❌ 退出", callback=self._on_quit)
            ]
        
        @rumps.clicked("🖥️ 打开主界面")
        def _on_open_gui(self, _):
            """打开GUI界面"""
            if self.on_open_gui:
                threading.Thread(target=self.on_open_gui, daemon=True).start()
            else:
                rumps.alert("提示", "GUI功能未启用")
        
        @rumps.clicked("🔊 测试语音")
        def _on_test_speech(self, _):
            """测试语音"""
            if self.on_test_speech:
                threading.Thread(target=self.on_test_speech, daemon=True).start()
            else:
                rumps.alert("提示", "语音功能未启用")
        
        @rumps.clicked("📄 查看日志")
        def _on_view_logs(self, _):
            """查看日志"""
            import subprocess
            import os
            log_dir = os.path.join(os.path.expanduser("~"), "Desktop", "MyJARVIS", "logs")
            if os.path.exists(log_dir):
                subprocess.run(["open", log_dir])
            else:
                rumps.alert("提示", "日志目录不存在")
        
        @rumps.clicked("❌ 退出")
        def _on_quit(self, _):
            """退出应用"""
            response = rumps.alert(
                "确认退出",
                "确定要退出 MyJARVIS 吗？",
                ok="退出",
                cancel="取消"
            )
            if response == 1:  # 点击了"退出"
                rumps.quit_application()
        
        def update_status(self, status: str):
            """
            更新状态显示
            
            Args:
                status: 状态文本
            """
            try:
                # 更新菜单项文本
                for item in self.menu:
                    if item and hasattr(item, 'title') and "正在运行" in item.title:
                        item.title = f"✅ {status}"
                        break
            except Exception as e:
                logger.error(f"更新状态失败: {e}")
else:
    # rumps 不可用时的占位类
    class MenuBarApp:
        """状态栏应用（rumps 未安装时的占位类）"""
        
        def __init__(self, on_open_gui=None, on_test_speech=None):
            logger.warning("状态栏功能不可用：rumps 未安装")
            self.on_open_gui = on_open_gui
            self.on_test_speech = on_test_speech
        
        def run(self):
            logger.warning("状态栏功能不可用：rumps 未安装。请运行: pip install rumps")
            # 如果没有GUI，至少启动GUI
            if self.on_open_gui:
                import threading
                threading.Thread(target=self.on_open_gui, daemon=True).start()
                # 保持运行
                import time
                try:
                    while True:
                        time.sleep(1)
                except KeyboardInterrupt:
                    pass
        
        def update_status(self, status: str):
            """更新状态（占位方法）"""
            pass
