"""Tools de usuario."""

import time
from datetime import UTC, datetime
from typing import Any

from fastmcp import FastMCP
from fastmcp.server.dependencies import AccessToken, get_access_token

from services.usage_logger import get_usage_logger, ms_since


def register_user_tools(mcp: FastMCP) -> None:
    """Registra tools de usuario."""

    @mcp.tool(annotations={"readOnlyHint": True, "openWorldHint": False})
    async def whoami() -> dict[str, Any]:
        """
        Retorna informacoes do usuario autenticado.

        Exibe dados extraidos do token JWT do Supabase Auth:
        - user_id (sub)
        - email
        - role
        - scopes
        - quando o token foi emitido
        - quando o token expira
        """
        _start = time.perf_counter()
        token: AccessToken | None = get_access_token()

        if token is None:
            result: dict[str, Any] = {
                "autenticado": False,
                "erro": "Nenhum token de acesso encontrado. Usuario nao autenticado.",
            }
            try:
                get_usage_logger().log_tool_call(
                    tool_name="whoami",
                    duration_ms=ms_since(_start),
                    success=False,
                    error_message="no_token",
                )
            except Exception:
                pass
            return result

        claims = token.claims or {}

        # Extrair dados do token JWT
        user_id = claims.get("sub")
        email = claims.get("email")
        role = claims.get("role")
        exp = claims.get("exp")
        iat = claims.get("iat")

        # Formatar timestamps
        exp_formatted = None
        iat_formatted = None
        if exp:
            exp_formatted = datetime.fromtimestamp(exp, tz=UTC).isoformat()
        if iat:
            iat_formatted = datetime.fromtimestamp(iat, tz=UTC).isoformat()

        try:
            get_usage_logger().log_tool_call(
                tool_name="whoami",
                duration_ms=ms_since(_start),
                user_id=user_id,
                user_email=email,
            )
        except Exception:
            pass

        return {
            "autenticado": True,
            "user_id": user_id,
            "email": email,
            "role": role,
            "scopes": token.scopes,
            "client_id": token.client_id,
            "token_emitido_em": iat_formatted,
            "token_expira_em": exp_formatted,
        }
