#!/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 PacketCaptureSkill(BaseSkill):
    """数据包抓包分析Skill"""
    
    def get_metadata(self):
        return {
            "name": "packet_capture",
            "display_name": "数据包抓包",
            "description": "实时捕获和分析网络数据包",
            "category": "advanced",
            "keywords": ["抓包", "数据包", "packet", "capture", "分析", "wireshark", "抓取"],
            "parameters": [
                {
                    "name": "target",
                    "type": "string", 
                    "required": False,
                    "default": "",
                    "description": "目标IP地址(可选,用于过滤特定主机)"
                },
                {
                    "name": "count",
                    "type": "int",
                    "required": False,
                    "default": 100,
                    "description": "抓包数量"
                },
                {
                    "name": "interface",
                    "type": "string",
                    "required": False,
                    "default": "auto",
                    "description": "网卡名称或auto"
                },
                {
                    "name": "filter",
                    "type": "string",
                    "required": False,
                    "default": "",
                    "description": "过滤器(TCP/UDP/ICMP/ARP)"
                }
            ],
            "examples": [
                "抓包分析",
                "数据包抓包",
                "抓取100个数据包",
                "抓包192.168.1.100 50个包"
            ],
            "requires_admin": True,
            "requires_ui": False  # 可以尝试后台抓包
        }
    
    def execute(self, target: str = "", count: int = 100, interface: str = "auto", filter: str = "") -> str:
        """执行抓包"""
        # 如果有toolkit实例,尝试调用抓包功能
        if self.toolkit and hasattr(self.toolkit, '_capture_and_analyze_packets'):
            try:
                # 根据target构建filter
                if target:
                    # 如果指定了目标IP,添加到filter中
                    if filter:
                        filter = f"host {target} and ({filter})"
                    else:
                        filter = f"host {target}"
                
                # 调用抓包功能
                result = self.toolkit._capture_and_analyze_packets(count, interface, filter)
                return result
            except Exception as e:
                return f"❌ 抓包失败: {str(e)}\n\n请尝试在图形界面中手动抓包。"
        
        # 如果无法后台抓包,引导用户到UI
        target_info = f"\n目标主机: {target}" if target else ""
        return f"""📍 数据包抓包

抓包参数:{target_info}
• 数量: {count}个数据包
• 网卡: {interface}
{f'• 过滤器: {filter}' if filter else ''}

⚙️ 执行方式:
方式1: 后台抓包(自动)
• 正在尝试后台抓包...
• 如果失败,请使用方式2

方式2: 图形界面操作(推荐)
1. 切换到'📦 数据包抓包'标签页
2. 选择要抓包的网卡
3. 设置抓包数量: {count}
{f"4. 在'显示名称'中筛选: {target}" if target else "4. 根据需要选择协议过滤器"}
5. 点击'▶️ 开始抓包'按钮
6. 等待抓包完成后,可以:
   • 查看详细数据包信息
   • 💾 导出抓包结果
   • 💬 使用AI分析抓包数据

抓包功能特点:
• 实时显示数据包
• 支持协议过滤(TCP/UDP/ICMP/ARP)
• 显示源/目标IP和端口
• 支持保存和导出PCAP格式

⚠️ 注意事项:
• 需要管理员权限
• 需要Scapy库支持
• 建议抓包数量不超过1000个"""
    
    def match_query(self, query: str) -> float:
        """增强的匹配逻辑"""
        query_lower = query.lower()
        
        # 特殊匹配:包含IP地址和"包"/"抓"
        import re
        has_ip = bool(re.search(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', query))
        has_packet_keyword = any(kw in query_lower for kw in ["包", "抓", "capture", "packet"])
        
        if has_ip and has_packet_keyword:
            return 0.95
        
        # 使用基类匹配
        return super().match_query(query)
