"""文件管理工具"""

import json
from typing import Any

from mcp.types import Tool, TextContent

from trailbase_mcp.client.client import TrailBaseClient


def get_files_tools() -> list[Tool]:
    """获取文件相关工具"""
    return [
        Tool(
            name="files.list",
            description="列出文件",
            inputSchema={
                "type": "object",
                "properties": {
                    "prefix": {"type": "string", "description": "路径前缀"},
                    "limit": {"type": "integer", "description": "返回数量限制"},
                    "page_token": {"type": "string", "description": "分页令牌"},
                },
            },
        ),
        Tool(
            name="files.delete",
            description="删除文件",
            inputSchema={
                "type": "object",
                "properties": {
                    "path": {"type": "string", "description": "文件路径"},
                },
                "required": ["path"],
            },
        ),
        Tool(
            name="files.meta",
            description="获取文件元数据",
            inputSchema={
                "type": "object",
                "properties": {
                    "path": {"type": "string", "description": "文件路径"},
                },
                "required": ["path"],
            },
        ),
    ]


async def handle_files_list(
    client: TrailBaseClient,
    prefix: str | None = None,
    limit: int | None = None,
    page_token: str | None = None,
) -> list[TextContent]:
    """处理 files.list 工具调用"""
    try:
        # TrailBase 没有通用的文件列表 API
        # 文件是通过表的 file 列管理的
        # 可以通过查询所有表，然后查找包含 file 列的表
        tables_result = client.http.get("api/_admin/tables")
        tables = tables_result.get("tables", [])
        
        files_info = []
        for table in tables:
            table_name = table.get("name", "")
            if not table_name:
                continue
            
            # 获取表结构
            try:
                table_info = client.http.post("api/_admin/query", json={
                    "query": f'PRAGMA table_info("{table_name}")'
                })
                columns = table_info.get("rows", [])
                
                # 查找包含 file 类型的列
                file_columns = []
                for col in columns:
                    col_name = col[1] if isinstance(col, list) and len(col) > 1 else None
                    col_type = col[2] if isinstance(col, list) and len(col) > 2 else None
                    if col_name and col_type and "json" in str(col_type).lower():
                        file_columns.append(col_name)
                
                if file_columns:
                    # 尝试列出该表的行以获取文件信息
                    try:
                        rows_result = client.http.get(f"api/_admin/table/{table_name}/rows", params={"limit": limit or 10})
                        rows = rows_result.get("rows", [])
                        columns_info = rows_result.get("columns", [])
                        
                        for row in rows:
                            for file_col in file_columns:
                                col_idx = next((i for i, c in enumerate(columns_info) if c.get("name") == file_col), None)
                                if col_idx is not None and col_idx < len(row):
                                    file_data = row[col_idx]
                                    if file_data:
                                        files_info.append({
                                            "table": table_name,
                                            "column": file_col,
                                            "file_data": str(file_data)[:100]  # 截断长数据
                                        })
                    except Exception:
                        pass  # 忽略无法访问的表
            except Exception:
                pass  # 忽略无法查询的表
        
        return [TextContent(type="text", text=json.dumps({
            "files": files_info[:limit] if limit else files_info,
            "note": "Files are managed through table file columns. Use /api/_admin/table/{table_name}/files with pk_column, pk_value, and file_column_name to access specific files."
        }, ensure_ascii=False))]
    except Exception as e:
        return [TextContent(type="text", text=json.dumps({"error": str(e)}, ensure_ascii=False))]


async def handle_files_delete(
    client: TrailBaseClient,
    path: str,
) -> list[TextContent]:
    """处理 files.delete 工具调用"""
    try:
        client.http.delete(f"/api/_admin/files/{path}")
        return [TextContent(type="text", text=json.dumps({"ok": True}, ensure_ascii=False))]
    except Exception as e:
        return [TextContent(type="text", text=json.dumps({"error": str(e)}, ensure_ascii=False))]


async def handle_files_meta(
    client: TrailBaseClient,
    path: str,
) -> list[TextContent]:
    """处理 files.meta 工具调用"""
    try:
        # TrailBase 文件路径格式可能是: table_name/pk_value/file_column_name
        # 或者: table_name/pk_value/file_column_name/file_name
        parts = path.split("/")
        if len(parts) < 3:
            return [TextContent(type="text", text='{"error": "Invalid path format. Expected: table_name/pk_value/file_column_name or table_name/pk_value/file_column_name/file_name"}')]
        
        table_name = parts[0]
        pk_value = parts[1]
        file_column_name = parts[2]
        file_name = parts[3] if len(parts) > 3 else None
        
        # 获取表结构以确定主键列
        table_info = client.http.post("api/_admin/query", json={
            "query": f'PRAGMA table_info("{table_name}")'
        })
        columns = table_info.get("rows", [])
        
        # 查找主键列
        pk_column = None
        for col in columns:
            col_name = col[1] if isinstance(col, list) and len(col) > 1 else None
            is_pk = col[5] if isinstance(col, list) and len(col) > 5 else 0
            if col_name and is_pk:
                pk_column = col_name
                break
        
        if not pk_column:
            return [TextContent(type="text", text=f'{{"error": "Primary key column not found for table {table_name}"}}')]
        
        # 使用 files API 获取文件信息
        params = {
            "pk_column": pk_column,
            "pk_value": pk_value,
            "file_column_name": file_column_name,
        }
        if file_name:
            params["file_name"] = file_name
        
        # 注意：read_files API 返回文件内容，不是元数据
        # 我们需要通过查询表来获取文件元数据
        try:
            result = client.http.get(f"api/_admin/table/{table_name}/files", params=params)
            return [TextContent(type="text", text=json.dumps({
                "table": table_name,
                "pk_column": pk_column,
                "pk_value": pk_value,
                "file_column_name": file_column_name,
                "file_name": file_name,
                "note": "File metadata is stored in the table file column. Use /api/_admin/table/{table_name}/rows to query file column data."
            }, ensure_ascii=False))]
        except Exception as e:
            return [TextContent(type="text", text=json.dumps({"error": f"Failed to access file: {str(e)}"}, ensure_ascii=False))]
    except Exception as e:
        return [TextContent(type="text", text=json.dumps({"error": str(e)}, ensure_ascii=False))]

