"""
Database Explorer MCP Server
A FastMCP server for exploring multiple databases with SELECT queries,
table sampling, and structure inspection.
"""

import sys
import os
from fastmcp import FastMCP
from fastmcp.tools.tool import ToolResult
from mcp.types import TextContent
from meeseeql.database_manager import load_config, DatabaseManager
from meeseeql import tools

mcp = FastMCP("Database Explorer")

db_manager = None


@mcp.tool()
def list_databases() -> ToolResult:
    """List all configured databases"""
    result = tools.list_databases(db_manager)
    return ToolResult(
        content=[TextContent(type="text", text=str(result))],
        structured_content=result.model_dump(),
    )


@mcp.tool()
async def execute_query(
    database: str,
    query: str,
    limit: int = 100,
    page: int = 1,
    accurate_count: bool = False,
) -> ToolResult:
    """Execute a SELECT query on the specified database with pagination.

    Args:
        database: Database name to query
        query: SELECT query to execute
        limit: Maximum rows per page (default: 100)
        page: Page number (default: 1)
        accurate_count: Run COUNT query for exact pagination (default: False, slower but accurate)
    """
    result = await tools.execute_query(
        db_manager, database, query, limit, page, accurate_count
    )
    return ToolResult(
        content=[TextContent(type="text", text=str(result))],
        structured_content=result.model_dump(),
    )


@mcp.tool()
async def sample_table(
    database: str,
    table_name: str,
    db_schema: str | None = None,
) -> ToolResult:
    """Sample rows from a table"""
    result = await tools.sample_table(db_manager, database, table_name, db_schema)
    return ToolResult(
        content=[TextContent(type="text", text=str(result))],
        structured_content=result.model_dump(),
    )


@mcp.tool()
async def describe_table(
    database: str,
    table_name: str,
    db_schema: str | None = None,
    limit: int = 250,
    page: int = 1,
) -> ToolResult:
    """Get table structure including columns and foreign keys with pagination"""
    result = await tools.describe_table(
        db_manager, database, table_name, db_schema, limit, page
    )
    return ToolResult(
        content=[TextContent(type="text", text=str(result))],
        structured_content=result.model_dump(),
    )


@mcp.tool()
async def search_tables(
    database: str,
    search_term: str | None = None,
    schema: str | None = None,
    limit: int = 500,
    page: int = 1,
) -> ToolResult:
    """Search for tables in the specified database with optional filtering and relevance-based ordering

    Args:
        database: Database name to search in
        search_term: Term to search for in table names. Leave empty to list all tables.
        limit: Maximum rows per page (default: 500)
        page: Page number (default: 1)
    """
    result = await tools.search_tables(
        db_manager, database, search_term, limit, page, schema
    )
    return ToolResult(
        content=[TextContent(type="text", text=str(result))],
        structured_content=result.model_dump(),
    )


@mcp.tool()
async def test_connection(database: str) -> ToolResult:
    """Test database connection, useful for debugging issues"""
    result = await tools.test_connection(db_manager, database)
    return ToolResult(
        content=[TextContent(type="text", text=str(result))],
        structured_content=result.model_dump(),
    )


# Looks for the config file in the following places:
# 1. --config flag (if provided)
# 2. MEESEEQL_CONFIG environment variable
# 3. ./config.yaml (current working directory)
# 4. ~/.config/meeseeql/config.yaml
# 5. ~/meeseeql.yaml (simple home directory)
def find_config_file():
    if len(sys.argv) > 2 and sys.argv[1] == "--config":
        return sys.argv[2]

    env_config = os.environ.get("MEESEEQL_CONFIG")
    if env_config and os.path.exists(env_config):
        return env_config

    cwd_config = os.path.join(os.getcwd(), "config.yaml")
    if os.path.exists(cwd_config):
        return cwd_config

    home_dir = os.path.expanduser("~")
    xdg_config = os.path.join(home_dir, ".config", "meeseeql", "config.yaml")
    if os.path.exists(xdg_config):
        return xdg_config

    home_config = os.path.join(home_dir, "meeseeql.yaml")
    if os.path.exists(home_config):
        return home_config

    raise ValueError("Config file not found")


def main():
    global db_manager
    config_path = find_config_file()
    config = load_config(config_path)
    db_manager = DatabaseManager(config)
    mcp.run()


if __name__ == "__main__":
    main()
