#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Syslog服务器Skill - 通过AI助手控制Syslog日志收集服务的启动/停止"""

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 SyslogServerSkill(BaseSkill):
    """Syslog服务器控制Skill"""

    def get_metadata(self):
        return {
            "name": "syslog_server",
            "display_name": "Syslog服务器",
            "description": "启动或停止Syslog日志收集服务器,用于接收网络设备日志",
            "category": "advanced",
            "keywords": [
                "syslog", "syslog服务器", "日志服务器", "日志收集",
                "启动syslog", "停止syslog", "syslog server",
                "日志接收", "设备日志", "514"
            ],
            "parameters": [
                {
                    "name": "action",
                    "type": "string",
                    "required": False,
                    "default": "start",
                    "description": "操作: start(启动) 或 stop(停止)"
                },
                {
                    "name": "port",
                    "type": "int",
                    "required": False,
                    "default": 514,
                    "description": "监听端口,默认514"
                },
                {
                    "name": "protocol",
                    "type": "string",
                    "required": False,
                    "default": "UDP",
                    "description": "协议: UDP 或 TCP"
                }
            ],
            "examples": [
                "启动syslog服务器",
                "开启日志收集服务",
                "停止syslog",
                "syslog服务器 UDP 514",
                "启动日志服务器",
            ],
            "requires_admin": True,
            "requires_ui": True
        }

    def execute(self, action: str = "start", port: int = 514, protocol: str = "UDP") -> str:
        action = action.strip().lower()
        stop_keywords = ("stop", "停止", "关闭", "停", "close", "off")
        is_stop = any(k in action for k in stop_keywords)
        protocol = protocol.upper() if protocol else "UDP"

        if self.toolkit:
            try:
                if is_stop:
                    if hasattr(self.toolkit, 'stop_syslog_server'):
                        self._switch_to_server_panel("syslog")
                        self.toolkit.stop_syslog_server()
                        return "✅ Syslog服务器已停止"
                    return "❌ 未找到stop_syslog_server方法"
                else:
                    if hasattr(self.toolkit, 'start_syslog_server'):
                        self._switch_to_server_panel("syslog")
                        if port and port != 514 and hasattr(self.toolkit, 'syslog_port_var'):
                            self.toolkit.syslog_port_var.set(str(port))
                        if hasattr(self.toolkit, 'syslog_protocol_var'):
                            self.toolkit.syslog_protocol_var.set(protocol)
                        self.toolkit.start_syslog_server()
                        return (
                            f"✅ Syslog服务器已启动\n"
                            f"• 协议: {protocol}\n"
                            f"• 端口: {port}\n"
                            f"• 设备配置: logging host <本机IP>\n"
                            f"• 日志将实时显示在界面中"
                        )
            except Exception as e:
                return f"❌ 操作失败: {e}"

        action_cn = "停止" if is_stop else "启动"
        return (
            f"📋 Syslog服务器 — {action_cn}\n\n"
            f"请切换到 [🖥️ 服务器] → [📋 Syslog服务器] 手动操作。\n"
            f"• 协议: {protocol}  端口: {port}\n"
            f"• 用途: 收集路由器/交换机/服务器日志"
        )

    def _switch_to_server_panel(self, panel_type: str):
        try:
            if hasattr(self.toolkit, 'switch_server_panel'):
                self.toolkit.root.after(0, lambda: self.toolkit.switch_server_panel(panel_type))
        except Exception:
            pass

    def match_query(self, query: str) -> float:
        q = query.lower()
        if "syslog" in q:
            return 0.95
        if any(k in q for k in ("日志服务器", "日志收集", "设备日志", "日志接收")):
            return 0.9
        return super().match_query(query)
