#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Ping测试Skill"""

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

from skills.base_skill import BaseSkill
from network_tools import run_ping


class PingSkill(BaseSkill):
    """Ping测试Skill(包含ICMP Ping和TCP Ping)"""
    
    def get_metadata(self):
        return {
            "name": "ping",
            "display_name": "Ping测试",
            "description": "测试网络连通性和延迟(支持ICMP Ping和TCP Ping)",
            "category": "network",
            "keywords": ["ping", "测试", "连通性", "延迟", "网络", "丢包", "tcp"],
            "parameters": [
                {
                    "name": "host",
                    "type": "string",
                    "required": True,
                    "description": "目标主机IP或域名"
                },
                {
                    "name": "count",
                    "type": "int",
                    "required": False,
                    "default": 4,
                    "description": "发送数据包数量"
                },
                {
                    "name": "timeout",
                    "type": "int",
                    "required": False,
                    "default": 1000,
                    "description": "超时时间(毫秒)"
                },
                {
                    "name": "mode",
                    "type": "string",
                    "required": False,
                    "default": "icmp",
                    "description": "模式:icmp(普通Ping)或tcp(TCP Ping)"
                },
                {
                    "name": "port",
                    "type": "int",
                    "required": False,
                    "default": 80,
                    "description": "TCP Ping的目标端口(仅mode=tcp时有效)"
                }
            ],
            "examples": [
                "ping 8.8.8.8",
                "测试百度的网络",
                "ping一下baidu.com",
                "ping 192.168.1.1 10次",
                "tcp ping baidu.com 443"
            ],
            "requires_admin": False,
            "requires_ui": False
        }
    
    def execute(self, host: str, count: int = 4, timeout: int = 1000, 
                mode: str = "icmp", port: int = 80) -> str:
        """执行Ping测试"""
        mode = mode.lower()
        
        if mode == "tcp":
            # TCP Ping功能
            return self._tcp_ping(host, port, count, timeout)
        else:
            # 普通ICMP Ping
            return run_ping(host, count, timeout)
    
    def _tcp_ping(self, host: str, port: int, count: int, timeout_ms: int) -> str:
        """TCP Ping实现"""
        import socket
        import time
        
        results = []
        results.append(f"TCP Ping {host}:{port} - 共{count}次")
        results.append("=" * 60)
        
        success_count = 0
        total_time = 0
        min_time = float('inf')
        max_time = 0
        
        for i in range(count):
            try:
                start = time.time()
                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                sock.settimeout(timeout_ms / 1000)
                sock.connect((host, port))
                sock.close()
                elapsed = (time.time() - start) * 1000
                
                results.append(f"✅ 第{i+1}次: 连接成功, 时间={elapsed:.2f}ms")
                success_count += 1
                total_time += elapsed
                min_time = min(min_time, elapsed)
                max_time = max(max_time, elapsed)
                
            except socket.timeout:
                results.append(f"❌ 第{i+1}次: 超时")
            except Exception as e:
                results.append(f"❌ 第{i+1}次: 失败 - {str(e)}")
            
            if i < count - 1:
                time.sleep(1)
        
        results.append("=" * 60)
        results.append(f"\n📊 统计结果:")
        results.append(f"  • 发送: {count}次")
        results.append(f"  • 成功: {success_count}次")
        results.append(f"  • 失败: {count - success_count}次")
        results.append(f"  • 成功率: {success_count/count*100:.1f}%")
        
        if success_count > 0:
            avg_time = total_time / success_count
            results.append(f"\n⏱️ 延迟统计:")
            results.append(f"  • 最小: {min_time:.2f}ms")
            results.append(f"  • 最大: {max_time:.2f}ms")
            results.append(f"  • 平均: {avg_time:.2f}ms")
        
        return "\n".join(results)
