import os
import sys
import argparse
import subprocess
import time
from pathlib import Path
import platform
import threading
# 使用importlib.resources替代弃用的pkg_resources
import importlib.resources

# 导入psutil用于进程检查（Windows平台需要）
try:
    import psutil
except ImportError:
    # 在非Windows平台或没有安装psutil时，可以正常运行
    psutil = None

# 添加项目根目录到系统路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# 导入日志模块
from shortcutkey.logger import logger

from shortcutkey.config_manager import ConfigManager
from shortcutkey.hotkey_listener import HotkeyListener
from shortcutkey.app_manager import AppManager
from shortcutkey.autostart import AutoStartManager
# 导入语言管理器
from shortcutkey.lang_manager import get_lang_manager, _

def parse_arguments():
    """解析命令行参数"""
    try:
        parser = argparse.ArgumentParser(description='快捷键启动程序')
        parser.add_argument('-c', '--config', action='store_true', help='配置快捷键')
        parser.add_argument('-l', '--list', action='store_true', help='列出所有监听的快捷键')
        parser.add_argument('-d', '--stop', action='store_true', help='退出后台程序运行')
        parser.add_argument('-r', '--restart', action='store_true', help='重新启动后台程序')
        parser.add_argument('-s', '--status', action='store_true', help='查询当前程序状态')
        args = parser.parse_args()
        logger.info(f"命令行参数: {args}")
        return args
    except Exception as e:
        logger.error(f"解析命令行参数失败: {str(e)}")
        raise


def run_in_background():
    """在后台运行程序，创建标准守护进程"""
    logger.info("准备在后台运行程序")
    
    # 设置环境变量标记，避免递归创建守护进程
    env = os.environ.copy()
    env['SHORTCUTKEY_DAEMON'] = '1'
    
    # 在不同操作系统上创建守护进程的方式
    if sys.platform == 'win32':
        # Windows - 使用pythonw.exe无窗口模式
        try:
            pythonw_path = os.path.join(sys.prefix, 'pythonw.exe')
            process = subprocess.Popen(
                [pythonw_path, __file__],  # 直接运行当前脚本
                env=env,
                creationflags=subprocess.CREATE_NO_WINDOW,
                stdout=subprocess.DEVNULL,
                stderr=subprocess.DEVNULL,
                stdin=subprocess.DEVNULL
            )
            logger.info(f"守护进程已在Windows后台启动，PID: {process.pid}")
            print(f"守护进程已在后台运行，PID: {process.pid}")
            return process
        except Exception as e:
            logger.error(f"Windows守护进程启动失败: {e}")
            # 回退方案
            process = subprocess.Popen(
                [sys.executable, __file__],  # 直接运行当前脚本
                env=env,
                stdout=subprocess.DEVNULL,
                stderr=subprocess.DEVNULL,
                stdin=subprocess.DEVNULL
            )
            print(f"守护进程已在后台运行，PID: {process.pid}")
            return process
    else:
        # macOS 和 Linux - 创建标准守护进程
        # 1. 重定向所有标准流
        # 2. 创建新的会话和进程组
        # 3. 完全脱离控制终端
        process = subprocess.Popen(
            [sys.executable, __file__],  # 直接运行当前脚本
            env=env,
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
            stdin=subprocess.DEVNULL,
            start_new_session=True
        )
        logger.info(f"守护进程已在Unix系统后台启动，PID: {process.pid}")
        print(f"守护进程已在后台运行，PID: {process.pid}")
        return process


def configure_hotkeys(config_manager, app_manager):
    """Configure hotkeys"""
    logger.info("开始配置快捷键")
    print(_('configure_hotkeys.title'))
    
    try:
        # 获取现有配置
        config = config_manager.get_config()
        logger.info("已加载现有配置")
        
        while True:
            print(f"\n{_('configure_hotkeys.current_configs')}")
            if not config.get('hotkeys'):
                print(f"  {_('configure_hotkeys.no_configs')}")
            else:
                for i, hotkey in enumerate(config['hotkeys'], 1):
                    print(f"  {i}. {hotkey['shortcut']} -> {hotkey['application']}")
            
            print(f"\n{_('configure_hotkeys.select_operation')}")
            print(f"1. {_('configure_hotkeys.add_hotkey')}")
            print(f"2. {_('configure_hotkeys.delete_hotkey')}")
            current_lang_text = '中文' if get_lang_manager().language == 'zh' else 'English'
            print(f"3. {_('configure_hotkeys.set_language')} ({_('configure_hotkeys.current')}: {current_lang_text})")
            print(f"4. {_('configure_hotkeys.exit_config')}")
            
            choice = input(_('configure_hotkeys.enter_choice')).strip()
            
            if choice == '1':
                # Add hotkey
                shortcut = input(_('configure_hotkeys.enter_hotkey')).strip()
                logger.info(f"用户输入快捷键: {shortcut}")
            
                # Let user select application
                print(f"\n{_('configure_hotkeys.retrieving_apps')}")
                try:
                    apps = app_manager.find_applications()
                    logger.info(f"成功获取系统应用程序列表，共 {len(apps)} 个应用")
                except Exception as e:
                    logger.error(f"获取系统应用程序列表失败: {str(e)}")
                    print(_('configure_hotkeys.apps_error', error=str(e)))
                    continue
                
                # 分批显示应用程序列表
                batch_size = 20
                current_batch = 0
                app_location = None
                app_name = None
                
                while True:
                    start = current_batch * batch_size
                    end = start + batch_size
                    batch_apps = apps[start:end]
                    
                    if not batch_apps:
                        print(_('configure_hotkeys.no_more_apps'))
                        break
                    
                    print(f"\n{_('configure_hotkeys.app_list_page', page=current_batch + 1)}")
                    for i, app in enumerate(batch_apps, 1):
                        print(f"  {start + i}. {app['name']}")
                    
                    print(f"  {len(apps) + 1}. {_('configure_hotkeys.manual_path')}")
                    print(f"  {len(apps) + 2}. {_('configure_hotkeys.prev_page')}")
                    print(f"  {len(apps) + 3}. {_('configure_hotkeys.next_page')}")
                    
                    app_choice = input(_('configure_hotkeys.enter_app_choice')).strip()
                    
                    try:
                        app_index = int(app_choice) - 1
                        
                        if app_index == len(apps):  # 手动输入应用路径
                            app_location = input(_('configure_hotkeys.enter_app_path')).strip()
                            app_name = os.path.basename(app_location)
                            logger.info(f"用户手动输入应用路径: {app_location}")
                            break
                        elif app_index == len(apps) + 1:  # 上一页
                            if current_batch > 0:
                                current_batch -= 1
                            continue
                        elif app_index == len(apps) + 2:  # 下一页
                            if end < len(apps):
                                current_batch += 1
                            continue
                        elif 0 <= app_index < len(apps):
                            app_location = apps[app_index]['location']
                            app_name = apps[app_index]['name']
                            logger.info(f"用户选择应用: {app_name}, 路径: {app_location}")
                            break
                        else:
                            print(_('configure_hotkeys.invalid_choice'))
                    except ValueError:
                        # 处理搜索关键词
                        search_term = app_choice.lower()
                        logger.info(f"用户输入搜索关键词: {search_term}")
                        
                        # 过滤匹配的应用
                        matched_apps = [app for app in apps if search_term in app['name'].lower()]
                        
                        if matched_apps:
                            print(f"\n{_('configure_hotkeys.search_results', count=len(matched_apps))}")
                            for i, app in enumerate(matched_apps, 1):
                                print(f"  {i}. {app['name']}")
                            
                            # Let user select from search results
                            while True:
                                try:
                                    search_choice = int(input(_('configure_hotkeys.enter_selection_number')).strip()) - 1
                                    if 0 <= search_choice < len(matched_apps):
                                        app_location = matched_apps[search_choice]['location']
                                        app_name = matched_apps[search_choice]['name']
                                        logger.info(f"用户从搜索结果选择应用: {app_name}, 路径: {app_location}")
                                        break
                                    else:
                                        print(_('configure_hotkeys.invalid_number'))
                                except ValueError:
                                    print(_('configure_hotkeys.enter_valid_number'))
                            if app_location and app_name:
                                break
                        else:
                            print(_('configure_hotkeys.no_apps_found', term=search_term))
                            continue
                
                if app_location and app_name:
                    # 添加到配置
                    if 'hotkeys' not in config:
                        config['hotkeys'] = []
                    
                    config['hotkeys'].append({
                        'shortcut': shortcut,
                        'application': app_name,
                        'location': app_location
                    })
                    
                    logger.info(f"添加快捷键配置: {shortcut} -> {app_name} ({app_location})")
                    print(_('configure_hotkeys.added_hotkey', shortcut=shortcut, app=app_name))
            
            elif choice == '2':
                # 删除快捷键
                if not config.get('hotkeys'):
                    print(_('configure_hotkeys.no_hotkeys_to_delete'))
                    continue
                
                try:
                    index = int(input(_('configure_hotkeys.enter_delete_index')).strip()) - 1
                    if 0 <= index < len(config['hotkeys']):
                        removed = config['hotkeys'].pop(index)
                        logger.info(f"删除快捷键: {removed['shortcut']} -> {removed['application']}")
                        print(_('configure_hotkeys.deleted_hotkey', shortcut=removed['shortcut'], app=removed['application']))
                    else:
                        print(_('configure_hotkeys.invalid_index'))
                except ValueError:
                    print(_('configure_hotkeys.enter_valid_index'))
                    continue
            
            elif choice == '3':
                # Set language
                print(f"\n{_('configure_hotkeys.choose_language')}")
                print(f"1. {_('configure_hotkeys.chinese')}")
                print(f"2. {_('configure_hotkeys.english')}")
                lang_choice = input(_('configure_hotkeys.enter_lang_choice')).strip()
                
                if lang_choice == '1':
                    lang = 'zh'
                elif lang_choice == '2':
                    lang = 'en'
                else:
                    print("无效的选择，返回主菜单")
                    continue
                
                # 设置语言
                get_lang_manager().set_language(lang)
                
                # 将语言设置保存到配置文件
                try:
                    config['language'] = lang
                    config_manager.save_config(config)
                    logger.info(f"语言设置已保存到配置文件: {lang}")
                    print(f"\n语言已切换为: {'中文' if lang == 'zh' else 'English'}")
                except Exception as e:
                    logger.error(f"保存语言设置失败: {e}")
                    print(f"保存语言设置失败: {e}")
                continue
            elif choice == '4':
                # 保存配置并退出
                config_manager.save_config(config)
                logger.info("配置已保存")
                print(_('configure_hotkeys.config_saved'))
                break
            else:
                print(_('configure_hotkeys.invalid_choice_retry'))
    except Exception as e:
        logger.error(f"配置过程中发生错误: {str(e)}")
        print(_('configure_hotkeys.config_error', error=str(e)))

# 为ConfigManager添加configure_hotkeys方法
original_setup_configuration = ConfigManager.setup_configuration

def patched_setup_configuration(self):
    from shortcutkey.app_manager import AppManager
    app_manager = AppManager()
    configure_hotkeys(self, app_manager)

# 替换原始方法
ConfigManager.setup_configuration = patched_setup_configuration

def is_process_running():
    """检查程序是否已经在运行"""
    # 获取用户配置目录作为PID文件存储位置
    user_home = os.path.expanduser("~")
    pid_dir = os.path.join(user_home, ".shortcutkey")
    pid_file = os.path.join(pid_dir, "shortcutkey.pid")
    
    # 确保目录存在
    if not os.path.exists(pid_dir):
        os.makedirs(pid_dir)
    
    # 检查PID文件是否存在
    if os.path.exists(pid_file):
        try:
            with open(pid_file, 'r') as f:
                pid = int(f.read().strip())
            
            # 尝试检查进程是否存在
            if sys.platform == 'win32':
                # Windows上使用psutil检查
                if psutil:
                    is_running = psutil.pid_exists(pid)
                else:
                    # 如果没有psutil，尝试使用tasklist命令
                    try:
                        output = subprocess.check_output(['tasklist', '/FI', f'PID eq {pid}'])
                        is_running = f"{pid}" in output.decode('utf-8')
                    except:
                        is_running = False
            else:
                # Unix系统上使用os.kill(0)检查
                try:
                    os.kill(pid, 0)
                    is_running = True
                except ProcessLookupError:
                    is_running = False
            
            # 如果进程正在运行，记录PID信息
            if is_running:
                logger.info(f"发现程序已在运行，PID: {pid}")
                print(_('program_status.already_running', pid=pid))
            
            return is_running
        except (ValueError, FileNotFoundError):
            # PID文件无效或不存在
            logger.info(f"PID文件存在但无效，将创建新的PID文件")
            return False
    
    return False

def write_pid_file():
    """写入PID文件"""
    user_home = os.path.expanduser("~")
    pid_dir = os.path.join(user_home, ".shortcutkey")
    pid_file = os.path.join(pid_dir, "shortcutkey.pid")
    current_pid = os.getpid()
    
    # 确保目录存在
    if not os.path.exists(pid_dir):
        os.makedirs(pid_dir)
    
    with open(pid_file, 'w') as f:
        f.write(str(current_pid))
    
    logger.info(f"已写入PID文件: {pid_file}, PID: {current_pid}")
    
    # Always print PID information
    print(_('program_status.program_started', pid=current_pid))

def get_resource_path(relative_path):
    """获取资源文件的绝对路径，兼容开发环境和打包后的环境"""
    try:
        # 使用importlib.resources替代pkg_resources获取包内资源
        with importlib.resources.as_file(importlib.resources.files('shortcutkey') / relative_path) as resource_path:
            return str(resource_path)
    except Exception:
        # 回退到直接路径
        base_path = os.path.dirname(os.path.abspath(__file__))
        return os.path.join(base_path, relative_path)

def run_daemon():
    """守护进程主函数，在后台运行并监听热键"""
    logger.info("启动守护进程")
    current_pid = os.getpid()
    logger.info(f"守护进程PID: {current_pid}")
    
    # 首先检查系统权限，特别是在macOS上的辅助功能权限
    if platform.system() == 'Darwin':  # macOS
        logger.info("在守护进程中检查macOS辅助功能权限")
        # 导入keyboard模块进行权限测试
        try:
            from pynput import keyboard
            # 尝试创建一个临时监听器来测试权限
            temp_listener = keyboard.Listener()
            temp_listener.start()
            temp_listener.stop()
            temp_listener.join(timeout=1)
            logger.info("守护进程权限检查通过，可以监听键盘事件")
        except Exception as e:
            logger.error(f"守护进程权限检查失败: {str(e)}")
            # 在日志中记录详细的权限获取步骤
            logger.warning("守护进程缺少辅助功能权限，请确保在系统偏好设置中授权")
            logger.warning("权限路径: 系统偏好设置 > 安全性与隐私 > 隐私 > 辅助功能")
    
    try:
        # 写入PID文件
        write_pid_file()
        
        # 初始化配置管理器
        config_path = get_resource_path('config/default_config.yaml')
        config_manager = ConfigManager(config_path)
        
        # 设置开机自启动
        try:
            autostart_manager = AutoStartManager()
            autostart_manager.setup_autostart()
            logger.info("开机自启动设置完成")
        except Exception as e:
            logger.warning(f"设置开机自启动失败: {str(e)}")
        
        # 定义reload_signal文件路径
        user_home = os.path.expanduser("~")
        pid_dir = os.path.join(user_home, ".shortcutkey")
        reload_signal_file = os.path.join(pid_dir, "reload_signal")
        
        # 启动热键监听器
        logger.info("启动热键监听器")
        # 将热键监听器放在单独的线程中运行
        hotkey_thread = threading.Thread(target=start_hotkey_listener, args=(config_manager,), daemon=True)
        hotkey_thread.start()
        
        # 添加冷却机制，防止频繁重启
        last_restart_time = time.time()
        cool_down_period = 15  # 冷却时间延长到15秒
        
        # 保持主进程运行，确保守护进程不退出
        logger.info("守护进程进入主循环")
        consecutive_failures = 0  # 连续失败计数器
        max_consecutive_failures = 3  # 最大连续失败次数
        check_interval = 3  # 检查间隔设为3秒
        
        while True:
            time.sleep(check_interval)
            current_time = time.time()
            
            # 检查是否在冷却期内
            if current_time - last_restart_time < cool_down_period:
                # 检查线程状态但不立即重启
                if not hotkey_thread.is_alive():
                    consecutive_failures += 1
                    logger.warning(f"热键监听线程已退出，但处于冷却期({cool_down_period}秒)，将在冷却期后重启。连续失败次数: {consecutive_failures}")
                    # 如果连续失败次数过多，强制重启
                    if consecutive_failures >= max_consecutive_failures:
                        logger.warning(f"连续失败次数达到上限({max_consecutive_failures})，将提前重启热键监听器")
                        consecutive_failures = 0
                    else:
                        continue
            else:
                # 冷却期结束，重置连续失败计数
                consecutive_failures = 0
            
            # 检查是否有配置重载信号
            if os.path.exists(reload_signal_file):
                logger.info("检测到配置重载信号，准备重新加载配置")
                try:
                    # 删除信号文件
                    os.remove(reload_signal_file)
                    logger.info("已删除配置重载信号文件")
                    
                    # 停止当前热键线程
                    logger.info("正在停止当前热键监听器")
                    # 尝试停止当前的HotkeyListener实例，无论线程是否活着
                    if HotkeyListener._instance is not None:
                        try:
                            logger.info("尝试停止HotkeyListener实例")
                            HotkeyListener._instance.stop()
                            time.sleep(2)  # 给停止过程足够时间
                        except Exception as stop_error:
                            logger.error(f"停止HotkeyListener实例时出错: {stop_error}")
                    # 等待线程结束
                    if hotkey_thread.is_alive():
                        try:
                            logger.info("等待热键线程结束")
                            hotkey_thread.join(timeout=3)
                        except Exception as join_error:
                            logger.error(f"等待热键线程结束时出错: {join_error}")
                    
                    # 重新创建ConfigManager实例以加载最新配置
                    config_manager = ConfigManager(config_path)
                    logger.info("已加载最新配置")
                    
                    # 重新启动热键监听器
                    logger.info("准备重新启动热键监听器")
                    # 确保实例引用为None
                    HotkeyListener._instance = None
                    hotkey_thread = threading.Thread(target=start_hotkey_listener, args=(config_manager,), daemon=True)
                    hotkey_thread.start()
                    logger.info("热键监听器线程已启动")
                    # 给更多时间初始化
                    time.sleep(5)
                    logger.info("配置重载完成，新配置已生效")
                    
                    # 更新最后重启时间
                    last_restart_time = current_time
                except Exception as e:
                    logger.error(f"处理配置重载失败: {str(e)}")
                    # 出错时也更新冷却时间，避免频繁重试
                    last_restart_time = current_time
                    # 增加额外冷却时间
                    time.sleep(3)
            
            # 检查热键线程是否还在运行，如果不在则重新启动
            if not hotkey_thread.is_alive():
                consecutive_failures += 1
                logger.warning(f"热键监听线程已退出，准备重新启动。连续失败次数: {consecutive_failures}")
                try:
                    # 等待更长时间，确保线程完全退出
                    time.sleep(3)
                    
                    # 首先尝试停止当前的HotkeyListener实例（如果存在）
                    if HotkeyListener._instance is not None:
                        logger.info("尝试停止当前的HotkeyListener实例")
                        try:
                            HotkeyListener._instance.stop()
                            time.sleep(3)  # 给停止过程足够时间
                        except Exception as stop_error:
                            logger.error(f"停止HotkeyListener实例时出错: {stop_error}")
                    
                    # 重新创建ConfigManager实例以加载最新配置
                    config_manager = ConfigManager(config_path)
                    logger.info("重新初始化配置管理器")
                    
                    # 确保实例引用为None
                    with HotkeyListener._lock:
                        HotkeyListener._instance = None
                    
                    # 创建并启动新的热键线程
                    logger.info("创建并启动新的热键线程")
                    hotkey_thread = threading.Thread(target=start_hotkey_listener, args=(config_manager,), daemon=True)
                    hotkey_thread.start()
                    logger.info("热键监听线程已重新启动")
                    
                    # 线程初始化时间，新的start_hotkey_listener函数会自己保持活跃
                    time.sleep(2)  # 给线程一些初始化时间
                    
                    # 记录线程启动状态，不再立即检查是否活着
                    # 因为新的start_hotkey_listener会保持线程活跃，直到监听器停止
                    logger.info("热键监听线程初始化完成")
                    
                    # 更新最后重启时间
                    last_restart_time = current_time
                    
                    # 成功启动后重置连续失败计数
                    consecutive_failures = 0
                except Exception as e:
                    logger.error(f"重启热键监听器失败: {str(e)}", exc_info=True)
                    # 出错时也更新冷却时间，避免频繁重试
                    last_restart_time = current_time
                    # 根据失败次数增加额外冷却时间
                    extra_cool_down = min(consecutive_failures * 3, 15)  # 0-15秒额外冷却
                    logger.info(f"增加额外冷却时间: {extra_cool_down}秒")
                    time.sleep(5 + extra_cool_down)
    except KeyboardInterrupt:
        logger.info("收到中断信号，守护进程退出")
    except Exception as e:
        logger.error(f"守护进程运行出错: {str(e)}")
        # 出错时不立即退出，尝试继续运行
        time.sleep(5)
        logger.info("尝试恢复运行")
    finally:
        logger.info("守护进程执行完毕")
        # 清理PID文件，统一使用~/.shortcutkey/shortcutkey.pid路径
        user_home = os.path.expanduser("~")
        pid_dir = os.path.join(user_home, ".shortcutkey")
        pid_file = os.path.join(pid_dir, "shortcutkey.pid")
        if os.path.exists(pid_file):
            try:
                os.remove(pid_file)
                logger.info("已清理PID文件")
            except Exception as e:
                logger.warning(f"清理PID文件失败: {e}")


def list_hotkeys():
    """列出所有快捷键配置"""
    config_path = get_resource_path('config/default_config.yaml')
    config_manager = ConfigManager(config_path)
    
    if not config_manager.has_config():
        print(_('list_hotkeys.no_config_file'))
        return
    
    # 直接获取配置，ConfigManager的get_config方法会重新读取文件
    config = config_manager.get_config()
    # 兼容不同配置格式
    shortcuts = []
    if 'hotkeys' in config:
        for hotkey in config['hotkeys']:
            shortcuts.append({
                'hotkey': hotkey['shortcut'],
                'path': hotkey['location'],
                'name': hotkey['application']
            })
    elif 'shortcuts' in config:
        shortcuts = config['shortcuts']
    
    if not shortcuts:
        print(_('list_hotkeys.no_hotkeys'))
        return
    
    print(_('list_hotkeys.title'))
    for i, shortcut in enumerate(shortcuts, 1):
        print(f"{i}. 快捷键: {shortcut.get('hotkey', '未设置')}")
        print(f"   应用: {shortcut.get('name', '未命名')}")
        print(f"   路径: {shortcut.get('path', '未设置')}")
        print()
    # print("=======================")

def check_process_status():
    """检查进程状态"""
    logger.info("检查程序运行状态")
    
    # 检查PID文件，统一使用~/.shortcutkey/shortcutkey.pid路径
    user_home = os.path.expanduser("~")
    pid_dir = os.path.join(user_home, ".shortcutkey")
    pid_file = os.path.join(pid_dir, "shortcutkey.pid")
    
    if not os.path.exists(pid_file):
        # 使用语言管理器显示状态
        print(_('program_status.program_not_running'))
        return False
    
    try:
        with open(pid_file, 'r') as f:
            pid = int(f.read().strip())
        
        # 检查进程是否存在
        if platform.system() == 'win32':
            # Windows系统
            if psutil:
                process_exists = psutil.pid_exists(pid)
            else:
                try:
                    import ctypes
                    kernel32 = ctypes.windll.kernel32
                    process_exists = kernel32.OpenProcess(1, 0, pid) != 0
                except:
                    process_exists = False
        else:
            # Unix系统 (macOS/Linux)
            try:
                os.kill(pid, 0)
                process_exists = True
            except OSError:
                process_exists = False
        
        if process_exists:
            # 使用语言管理器显示状态
            print(_('program_status.program_running', pid=pid))
            return True
        else:
            print(_('program_status.program_not_running'))
            # 清理PID文件
            if os.path.exists(pid_file):
                os.remove(pid_file)
            return False
    except Exception as e:
        logger.error(f"检查程序状态失败: {e}")
        print(_('errors.stop_failed', error=str(e)))
        return False

def stop_background_process():
    """停止后台运行的程序"""
    logger.info("尝试停止后台运行的程序")
    
    # 检查PID文件，统一使用~/.shortcutkey/shortcutkey.pid路径
    user_home = os.path.expanduser("~")
    pid_dir = os.path.join(user_home, ".shortcutkey")
    pid_file = os.path.join(pid_dir, "shortcutkey.pid")
    
    if not os.path.exists(pid_file):
        print(_("program_status.program_not_running"))
        return False
    
    try:
        with open(pid_file, 'r') as f:
            pid = int(f.read().strip())
        
        # 检查进程是否存在
        if platform.system() == 'win32':
            # Windows系统
            import ctypes
            kernel32 = ctypes.windll.kernel32
            process_exists = kernel32.OpenProcess(1, 0, pid) != 0
        else:
            # Unix系统 (macOS/Linux)
            try:
                os.kill(pid, 0)
                process_exists = True
            except OSError:
                process_exists = False
        
        if process_exists:
            # 发送终止信号
            if platform.system() == 'win32':
                import ctypes
                PROCESS_TERMINATE = 1
                handle = ctypes.windll.kernel32.OpenProcess(PROCESS_TERMINATE, False, pid)
                ctypes.windll.kernel32.TerminateProcess(handle, 0)
                ctypes.windll.kernel32.CloseHandle(handle)
            else:
                os.kill(pid, 15)  # SIGTERM
            
            # 等待进程终止
            time.sleep(1)
            print(_('program_status.program_stopped', pid=pid))
            # 删除PID文件
            if os.path.exists(pid_file):
                os.remove(pid_file)
            return True
        else:
            print(_('program_status.program_not_running'))
            # 清理PID文件
            if os.path.exists(pid_file):
                os.remove(pid_file)
            return False
    except Exception as e:
        logger.error(f"停止后台程序失败: {e}")
        print(_('errors.stop_failed', error=str(e)))
        return False

def main():
    """主函数"""
    current_pid = os.getpid()
    logger.info(f"尝试启动程序，当前进程PID: {current_pid}")
    
    # 检查是否是守护进程模式
    if os.environ.get('SHORTCUTKEY_DAEMON') == '1':
        logger.info("检测到守护进程模式，直接运行run_daemon函数")
        run_daemon()
        return
    
    # 解析命令行参数
    args = parse_arguments()
    
    # 初始化配置管理器
    config_manager = ConfigManager()
    
    # 设置语言（从配置文件读取）
    lang_manager = get_lang_manager()
    try:
        config = config_manager.get_config()
        language = config.get('language', 'zh')  # 默认中文
        lang_manager.set_language(language)
        logger.info(f"程序语言已设置为: {language}")
    except Exception as e:
        logger.warning(f"读取语言配置失败，使用默认语言: {e}")
        lang_manager.set_language('zh')  # 默认使用中文
    
    # 处理新的命令行参数
    if args.list:
        list_hotkeys()
        return

    if args.status:
        check_process_status()
        return
    
    if args.stop:
        stop_background_process()
        return
    
    if args.restart:
        # 先停止现有的后台程序
        stop_background_process()
        # 然后重新启动
        print(_('program_status.restarting'))
        # 设置一个标志，用于指示这是重启操作
        os.environ['SHORTCUTKEY_RESTART'] = '1'
    
    # 如果是带参数运行，不要显示进程ID等信息
    show_process_info = not (args.list or args.stop or args.restart)
    
    # 在主程序中预先检查权限，确保用户在启动守护进程前已经授权
    if platform.system() == 'Darwin':  # macOS
        logger.info("在主程序中预先检查macOS辅助功能权限")
        try:
            from pynput import keyboard
            # 尝试创建一个临时监听器来测试权限
            temp_listener = keyboard.Listener()
            temp_listener.start()
            temp_listener.stop()
            temp_listener.join(timeout=1)
            logger.info("主程序权限检查通过")
        except Exception as e:
            logger.warning(f"主程序权限检查失败: {str(e)}")
            print(f"\n{_('macos_permission.important_note')}")
            print(f"\n{_('macos_permission.opening_settings')}")
            
            try:
                # 使用subprocess运行命令打开系统偏好设置的辅助功能页面
                import subprocess
                subprocess.run(["open", "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility"])
                logger.info("已成功打开系统偏好设置的辅助功能页面")
            except Exception as open_error:
                logger.error(f"无法打开系统偏好设置: {str(open_error)}")
            
            print(_('macos_permission.authorization_steps'))
            print(f"1. {_('macos_permission.step1')}")
            print(f"2. {_('macos_permission.step2')}")
            print(f"3. {_('macos_permission.step3')}")
            print(f"4. {_('macos_permission.step4')}")
            print(f"5. {_('macos_permission.step5')}")
            print(f"\n{_('macos_permission.authorize_both')}")
            input(_('macos_permission.press_enter'))
            
            # 再次检查权限
            try:
                temp_listener = keyboard.Listener()
                temp_listener.start()
                temp_listener.stop()
                temp_listener.join(timeout=1)
                logger.info("重新检查权限通过")
            except Exception:
                logger.error("权限仍然不足，无法继续")
                print("错误: 权限仍然不足，请确保已经正确授权后重试")
                sys.exit(1)
    
    # 如果是配置模式，在前台运行配置向导
    if args.config:
        logger.info("进入配置模式")
        # 初始化配置管理器
        config_path = get_resource_path('config/default_config.yaml')
        config_manager = ConfigManager(config_path)
        config_manager.setup_configuration()
        logger.info("配置模式完成")
        # print(_('configure_hotkeys.config_saved'))
        # 提示配置已生效
        # print(_('config_effective'))
        return
    
    # 检查配置是否存在
    config_path = get_resource_path('config/default_config.yaml')
    config_manager = ConfigManager(config_path)
    
    # 如果配置不存在，先在前台引导用户配置
    if not config_manager.has_config():
        print(_('no_config_found'))
        config_manager.setup_configuration()
        print(_('config_completed'))
        print(_('config_effective'))
    
    # 检查程序是否已经在运行（重启模式除外）
    if not args.restart and is_process_running():
        logger.info("程序已在运行，无需重复启动")
        print(_('program_already_running'))
        sys.exit(0)
    
    # 启动后台守护进程
    logger.info("准备启动后台守护进程")
    process = run_in_background()
    
    # 等待2秒确保子进程已启动
    time.sleep(2)
    logger.info("主进程退出，守护进程在后台运行")
    
    # Indicate configuration has taken effect
    if args.restart:
        print("Program has been restarted and is listening for hotkeys")
    else:
        print("Program has started in background and is listening for hotkeys")
    print("Configuration is now in effect!")
    
    # 主进程退出，让守护进程独立运行
    sys.exit(0)


def start_hotkey_listener(config_manager):
    """启动热键监听器"""
    logger.info("启动热键监听器")
    try:
        config = config_manager.get_config()
        # 兼容不同配置格式
        if 'hotkeys' in config:
            # 转换为统一格式
            shortcuts = []
            for hotkey in config['hotkeys']:
                shortcuts.append({
                    'hotkey': hotkey['shortcut'],
                    'path': hotkey['location'],
                    'name': hotkey['application']
                })
            config['shortcuts'] = shortcuts
            logger.info(f"转换配置格式，共 {len(shortcuts)} 个快捷键")
        
        logger.info(f"加载配置成功，共有 {len(config.get('shortcuts', []))} 个快捷键配置")
        app_manager = AppManager()
        logger.info("应用管理器初始化成功")
        
        # 初始化新的热键监听器（不再检查现有实例，由调用者负责停止）
        hotkey_listener = HotkeyListener(config, app_manager)
        # 直接运行监听器，不再创建额外线程
        logger.info("热键监听器开始运行")
        hotkey_listener.start()
        
        # 在macOS上的日志记录权限提示
        if platform.system() == 'Darwin':
            logger.info("在macOS上运行，请确保程序已获得辅助功能权限")
        
        # 保持线程活跃，等待热键监听器的主循环
        # 定期检查监听器状态，避免线程过早退出
        while HotkeyListener.is_running():
            time.sleep(2)  # 定期检查，避免CPU占用过高
        
        logger.info("热键监听线程正常退出")
    except KeyboardInterrupt:
        logger.info("热键监听线程收到中断信号，准备退出")
        if HotkeyListener._instance:
            HotkeyListener._instance.stop()
    except Exception as e:
        logger.error(f"热键监听器运行失败: {e}", exc_info=True)
        print(f"热键监听器启动失败: {e}")
        # 出错时确保清理资源
        if HotkeyListener._instance:
            try:
                HotkeyListener._instance.stop()
            except Exception:
                pass


if __name__ == "__main__":
    main()