"""
MCP示例服务器 - 文件系统访问
"""
from pathlib import Path
from typing import Optional
from ..base import MCPServer, MCPResource


class FileSystemMCPServer(MCPServer):
    """文件系统MCP服务器"""
    
    def __init__(self, root_path: Path):
        super().__init__(name="filesystem", version="1.0.0")
        self.root_path = root_path
    
    async def initialize(self):
        """初始化"""
        # 注册工具
        self.register_tool(
            name="read_file",
            description="读取文件内容",
            input_schema={
                "type": "object",
                "properties": {
                    "path": {
                        "type": "string",
                        "description": "文件路径"
                    }
                },
                "required": ["path"]
            },
            handler=self.read_file
        )
        
        self.register_tool(
            name="write_file",
            description="写入文件内容",
            input_schema={
                "type": "object",
                "properties": {
                    "path": {
                        "type": "string",
                        "description": "文件路径"
                    },
                    "content": {
                        "type": "string",
                        "description": "文件内容"
                    }
                },
                "required": ["path", "content"]
            },
            handler=self.write_file
        )
        
        self.register_tool(
            name="list_directory",
            description="列出目录内容",
            input_schema={
                "type": "object",
                "properties": {
                    "path": {
                        "type": "string",
                        "description": "目录路径"
                    }
                },
                "required": ["path"]
            },
            handler=self.list_directory
        )
    
    def _resolve_path(self, path: str) -> Path:
        """解析路径"""
        full_path = (self.root_path / path).resolve()
        
        # 安全检查：确保路径在root_path内
        if not str(full_path).startswith(str(self.root_path)):
            raise ValueError("路径超出允许范围")
        
        return full_path
    
    async def read_file(self, path: str) -> str:
        """读取文件"""
        file_path = self._resolve_path(path)
        
        if not file_path.exists():
            raise FileNotFoundError(f"文件不存在: {path}")
        
        if not file_path.is_file():
            raise ValueError(f"不是文件: {path}")
        
        with open(file_path, 'r', encoding='utf-8') as f:
            return f.read()
    
    async def write_file(self, path: str, content: str) -> str:
        """写入文件"""
        file_path = self._resolve_path(path)
        
        file_path.parent.mkdir(parents=True, exist_ok=True)
        
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(content)
        
        return f"文件已写入: {path}"
    
    async def list_directory(self, path: str) -> list:
        """列出目录"""
        dir_path = self._resolve_path(path)
        
        if not dir_path.exists():
            raise FileNotFoundError(f"目录不存在: {path}")
        
        if not dir_path.is_dir():
            raise ValueError(f"不是目录: {path}")
        
        items = []
        for item in dir_path.iterdir():
            items.append({
                "name": item.name,
                "type": "directory" if item.is_dir() else "file",
                "size": item.stat().st_size if item.is_file() else None
            })
        
        return items
