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

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

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

    def execute(self, action: str = "start", port: int = 21, 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_ftp_server'):
                        self._switch_to_server_panel("ftp")
                        self.toolkit.stop_ftp_server()
                        return "✅ FTP服务器已停止"
                    return "❌ 未找到stop_ftp_server方法"
                else:
                    if hasattr(self.toolkit, 'start_ftp_server'):
                        self._switch_to_server_panel("ftp")
                        if port and port != 21 and hasattr(self.toolkit, 'ftp_port_var'):
                            self.toolkit.ftp_port_var.set(str(port))
                        if root_dir and hasattr(self.toolkit, 'ftp_root_var'):
                            self.toolkit.ftp_root_var.set(root_dir)
                        self.toolkit.start_ftp_server()
                        return (
                            f"✅ FTP服务器已启动\n"
                            f"• 端口: {port}\n"
                            f"• 根目录: {root_dir or '(使用默认目录)'}\n"
                            f"• 客户端连接: ftp <本机IP>"
                        )
            except Exception as e:
                return f"❌ 操作失败: {e}"

        action_cn = "停止" if is_stop else "启动"
        return (
            f"📂 FTP服务器 — {action_cn}\n\n"
            f"请切换到 [🖥️ 服务器] → [📂 FTP服务器] 手动操作。\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 "ftp" in q:
            return 0.95
        if any(k in q for k in ("文件共享服务", "ftp服务", "文件服务器")):
            return 0.88
        return super().match_query(query)
