"""File Tools for Agent Skills

Provides file reading capabilities for agents to access skill instructions.
"""
import os
import logging
from typing import Dict, Any

logger = logging.getLogger(__name__)


def read_file(file_path: str) -> Dict[str, Any]:
    """读取文件内容
    
    Args:
        file_path: 文件路径（相对或绝对路径）
    
    Returns:
        包含文件内容的字典
    """
    try:
        # 安全检查：只允许读取 skills 目录下的文件
        abs_path = os.path.abspath(file_path)
        skills_dir = os.path.abspath(
            os.path.join(os.path.dirname(__file__), "..", "skills")
        )
        
        if not abs_path.startswith(skills_dir):
            return {
                "error": f"Access denied: Can only read files in skills directory"
            }
        
        if not os.path.exists(abs_path):
            return {"error": f"File not found: {file_path}"}
        
        if not os.path.isfile(abs_path):
            return {"error": f"Not a file: {file_path}"}
        
        with open(abs_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        return {
            "file_path": file_path,
            "content": content,
            "size": len(content)
        }
    
    except Exception as e:
        logger.error(f"Error reading file {file_path}: {e}")
        return {"error": f"Error reading file: {str(e)}"}


def list_directory(dir_path: str) -> Dict[str, Any]:
    """列出目录内容
    
    Args:
        dir_path: 目录路径
    
    Returns:
        包含目录内容的字典
    """
    try:
        # 安全检查：只允许列出 skills 目录
        abs_path = os.path.abspath(dir_path)
        skills_dir = os.path.abspath(
            os.path.join(os.path.dirname(__file__), "..", "skills")
        )
        
        if not abs_path.startswith(skills_dir):
            return {
                "error": f"Access denied: Can only list skills directory"
            }
        
        if not os.path.exists(abs_path):
            return {"error": f"Directory not found: {dir_path}"}
        
        if not os.path.isdir(abs_path):
            return {"error": f"Not a directory: {dir_path}"}
        
        items = []
        for item in os.listdir(abs_path):
            item_path = os.path.join(abs_path, item)
            items.append({
                "name": item,
                "type": "directory" if os.path.isdir(item_path) else "file",
                "path": os.path.join(dir_path, item)
            })
        
        return {
            "directory": dir_path,
            "items": items,
            "count": len(items)
        }
    
    except Exception as e:
        logger.error(f"Error listing directory {dir_path}: {e}")
        return {"error": f"Error listing directory: {str(e)}"}
