#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""环路检测Skill(需要UI交互)"""

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

from skills.base_skill import BaseSkill


class LoopDetectionSkill(BaseSkill):
    """环路检测Skill"""
    
    def get_metadata(self):
        return {
            "name": "loop_detection",
            "display_name": "环路检测",
            "description": "检测网络环路(ARP/UDP/ICMP/以太网帧)",
            "category": "advanced",
            "keywords": ["环路", "检测", "loop", "network"],
            "parameters": [
                {
                    "name": "interface",
                    "type": "string",
                    "required": False,
                    "default": "全部网卡",
                    "description": "网卡名称、IP地址或'全部网卡'"
                }
            ],
            "examples": [
                "环路检测",
                "检测网络环路",
                "查找环路"
            ],
            "requires_admin": True,
            "requires_ui": True
        }
    
    def execute(self, interface: str = "全部网卡") -> str:
        """执行环路检测"""
        # 环路检测需要访问UI组件,引导用户到界面操作
        if self.toolkit:
            # 尝试调用主程序的环路检测方法
            try:
                if hasattr(self.toolkit, '_check_network_loop_ethernet_for_interface'):
                    # 解析网卡参数
                    interface_info = None
                    if interface and interface != "全部网卡":
                        if hasattr(self.toolkit, 'loop_interface_map'):
                            if interface in self.toolkit.loop_interface_map:
                                interface_info = self.toolkit.loop_interface_map[interface]
                            else:
                                # 尝试IP或名称匹配
                                for display_name, info in self.toolkit.loop_interface_map.items():
                                    if isinstance(info, dict):
                                        if info.get('ip') == interface or interface.lower() in info.get('name', '').lower():
                                            interface_info = info
                                            break
                    
                    # 调用检测
                    return self.toolkit._check_network_loop_ethernet_for_interface(interface_info)
            except Exception as e:
                return f"❌ 环路检测失败: {str(e)}"
        
        # 如果无法调用,引导用户到UI
        return """📍 环路检测需要在图形界面中操作

请按以下步骤操作:
1. 切换到'🔍 单独环路检测'标签页
2. 选择要检测的网卡(或选择'全部网卡')
3. 点击'开始检测'按钮

环路检测包括:
• ARP表环路检测
• UDP广播环路检测
• ICMP广播环路检测
• 以太网帧环路检测

⚠️ 此功能需要管理员权限"""
