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

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

    def get_metadata(self):
        return {
            "name": "tftp_server",
            "display_name": "TFTP服务器",
            "description": "启动或停止TFTP文件传输服务器",
            "category": "advanced",
            "keywords": [
                "tftp", "tftp服务器", "tftp服务", "文件传输", "启动tftp",
                "停止tftp", "tftp server", "tftpd"
            ],
            "parameters": [
                {
                    "name": "action",
                    "type": "string",
                    "required": False,
                    "default": "start",
                    "description": "操作: start(启动) 或 stop(停止)"
                },
                {
                    "name": "port",
                    "type": "int",
                    "required": False,
                    "default": 69,
                    "description": "监听端口,默认69"
                },
                {
                    "name": "root_dir",
                    "type": "string",
                    "required": False,
                    "default": "",
                    "description": "TFTP根目录路径,默认使用程序配置"
                }
            ],
            "examples": [
                "启动TFTP服务器",
                "停止TFTP服务器",
                "开启TFTP服务",
                "tftp服务器启动 端口69",
            ],
            "requires_admin": True,
            "requires_ui": True
        }

    def execute(self, action: str = "start", port: int = 69, root_dir: str = "") -> str:
        action = action.strip().lower()

        # 判断是否停止
        stop_keywords = ("stop", "停止", "关闭", "停", "close", "off")
        is_stop = any(k in action for k in stop_keywords)

        if self.toolkit:
            try:
                if is_stop:
                    if hasattr(self.toolkit, 'stop_tftp_server'):
                        # 切换到服务器页面
                        self._switch_to_server_panel("tftp")
                        self.toolkit.stop_tftp_server()
                        return "✅ TFTP服务器已停止"
                    return "❌ 未找到stop_tftp_server方法"
                else:
                    if hasattr(self.toolkit, 'start_tftp_server'):
                        self._switch_to_server_panel("tftp")
                        # 如果传入了端口或目录则预先填写
                        if port and port != 69 and hasattr(self.toolkit, 'tftp_port_var'):
                            self.toolkit.tftp_port_var.set(str(port))
                        if root_dir and hasattr(self.toolkit, 'tftp_root_var'):
                            self.toolkit.tftp_root_var.set(root_dir)
                        self.toolkit.start_tftp_server()
                        return (
                            f"✅ TFTP服务器已启动\n"
                            f"• 端口: {port}\n"
                            f"• 根目录: {root_dir or '(使用默认目录)'}\n"
                            f"• 客户端连接: tftp <本机IP>"
                        )
            except Exception as e:
                return f"❌ 操作失败: {e}"

        action_cn = "停止" if is_stop else "启动"
        return (
            f"📁 TFTP服务器 — {action_cn}\n\n"
            f"请切换到 [🖥️ 服务器] → [📁 TFTP服务器] 手动操作。\n"
            f"• 端口: {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 "tftp" in q:
            return 0.95
        if any(k in q for k in ("文件传输服务", "tftp服务")):
            return 0.9
        return super().match_query(query)
