#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""应用程序启动Skill"""

import sys
import os
import subprocess

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(__file__))))

from skills.base_skill import BaseSkill


class AppLauncherSkill(BaseSkill):
    """应用程序启动Skill"""
    
    def __init__(self, toolkit_instance=None):
        # 应用映射表 - 必须在super().__init__之前定义
        self.app_map = {
            "记事本": "notepad",
            "计算器": "calc",
            "画图": "mspaint",
            "远程桌面": "mstsc",
            "任务管理器": "taskmgr",
            "控制面板": "control",
            "服务": "services.msc",
            "注册表": "regedit",
            "设备管理器": "devmgmt.msc",
            "磁盘管理": "diskmgmt.msc",
            "事件查看器": "eventvwr",
            "性能监视器": "perfmon",
            "资源监视器": "resmon",
            "命令提示符": "cmd",
            "powershell": "powershell",
            "资源管理器": "explorer"
        }
        super().__init__(toolkit_instance)
    
    def get_metadata(self):
        # 生成支持的应用列表
        apps_list = ", ".join(list(self.app_map.keys())[:10])
        
        return {
            "name": "app_launcher",
            "display_name": "应用启动器",
            "description": f"启动Windows应用程序,支持:{apps_list}等",
            "category": "system",
            "keywords": ["打开", "启动", "运行", "应用", "程序"] + list(self.app_map.keys()),
            "parameters": [
                {
                    "name": "app",
                    "type": "string",
                    "required": True,
                    "description": f"应用名称,支持:{apps_list}等"
                }
            ],
            "examples": [
                "打开记事本",
                "启动计算器",
                "打开远程桌面",
                "运行任务管理器"
            ],
            "requires_admin": False,
            "requires_ui": False
        }
    
    def execute(self, app: str) -> str:
        """启动应用"""
        # 查找应用命令
        command = self.app_map.get(app, app)
        
        try:
            subprocess.Popen(command, shell=True)
            return f"✅ 已启动: {app}"
        except Exception as e:
            return f"❌ 启动失败: {str(e)}\n\n支持的应用:\n" + "\n".join(
                f"  • {name}" for name in list(self.app_map.keys())[:15]
            )
    
    def match_query(self, query: str) -> float:
        """增强的匹配逻辑"""
        query_lower = query.lower()
        
        # 检查是否包含"打开"、"启动"等关键词
        launch_keywords = ["打开", "启动", "运行"]
        has_launch_keyword = any(kw in query_lower for kw in launch_keywords)
        
        # 检查是否匹配应用名称
        for app_name in self.app_map.keys():
            if app_name in query_lower or app_name.lower() in query_lower:
                return 0.9 if has_launch_keyword else 0.7
        
        # 使用基类的匹配逻辑
        return super().match_query(query)
