"""Server information and capability tools."""

import os
from importlib.metadata import version
from typing import Optional
from mcp.server.fastmcp import Context
from mcp.server.session import ServerSession
from point_topic_mcp.core.utils import dynamic_docstring, get_mcp_status_info
from point_topic_mcp.auth.decorators import public


def _get_version() -> str:
    """Get package version from installed metadata."""
    try:
        return version("point-topic-mcp")
    except Exception:
        return "0.0.0-dev"


@public
def get_server_info() -> dict:
    """
    Get server information. Available to all users.

    Welcome message and authentication status for the Point Topic MCP server.
    Shows whether you have full access or are on the free/public version.

    Returns:
        Server information including name, version, and auth status
    """
    admin_key_set = bool(os.getenv("ADMIN_API_KEY"))

    return {
        "name": "Point Topic MCP",
        "description": "UK broadband data analysis server",
        "version": _get_version(),
        "authenticated": admin_key_set,
        "message": (
            "Welcome to Point Topic MCP! "
            "You are on the free version with limited access. "
            "Contact Point Topic for full API access."
            if not admin_key_set
            else "Welcome to Point Topic MCP! You have full access."
        ),
    }


@public
@dynamic_docstring([("{STATUS}", get_mcp_status_info)])
def get_mcp_server_capabilities(
    ctx: Optional[Context[ServerSession, None]] = None,
) -> str:
    """MCP Server Configuration Status and Available Tools

    Shows which tools are available and which need environment variables.
    Use this to debug missing tools or check your MCP server configuration.

    Current Status: {STATUS}

    Environment Variables Guide:
    • SNOWFLAKE_USER + SNOWFLAKE_PASSWORD → Database tools (execute_query, assemble_dataset_context, etc.)
    • GITHUB_TOKEN → GitHub organization tools (search_issues_across_org, create_issue, etc.)
    • CHART_API_KEY → Authenticated chart generation (generate_authenticated_chart_url)
    • Public chart tools available without credentials (get_point_topic_public_chart_catalog)

    Configure missing environment variables in your MCP client to unlock additional tools.
    """
    return get_mcp_status_info()
