"""Test authentication utilities for MCP client tests.

Supports two authentication methods (checked in priority order):

1. **MCP_API_KEY** (preferred) — Pre-shared static token that bypasses OAuth.
   Set `MCP_API_KEY` in `.env` (same value the server reads).
   The server's API key bypass in `server.py` accepts this token and returns
   a synthetic AccessToken without calling Google.

2. **JWT token file** (legacy) — Reads from `test_tokens.json` generated by
   the server when `ENABLE_JWT_AUTH=true`.  Kept for backward compatibility.

The returned token string is passed as `auth=` to the FastMCP `Client` /
`StreamableHttpTransport`, which sends it as `Authorization: Bearer <token>`.
"""

import json
import os
from typing import Optional

from dotenv import load_dotenv

# Ensure .env is loaded so MCP_API_KEY is available
load_dotenv()


def get_mcp_api_key() -> Optional[str]:
    """Get MCP_API_KEY from environment.

    This is the preferred authentication method for tests when GoogleProvider
    is active.  The same key must be set in the server's .env file.

    Returns:
        API key string if MCP_API_KEY is set and non-empty, None otherwise.
    """
    key = os.getenv("MCP_API_KEY", "").strip()
    return key if key else None


def get_test_token(user_email: str = "test@example.com") -> Optional[str]:
    """Get a test JWT token for the specified user.

    Legacy method — reads tokens from ``test_tokens.json`` generated by the
    server.  Only used when ``ENABLE_JWT_AUTH`` is ``true`` and the token file
    exists.

    Args:
        user_email: Email address to get token for

    Returns:
        JWT token string if available, None otherwise
    """
    try:
        # Only use tokens if JWT auth is enabled
        if os.getenv("ENABLE_JWT_AUTH", "true").lower() == "true":
            # Read tokens from file generated by server
            test_tokens_file = "test_tokens.json"
            if os.path.exists(test_tokens_file):
                with open(test_tokens_file, "r") as f:
                    test_tokens = json.load(f)
                return test_tokens.get(user_email)
            else:
                # Don't warn — this is expected when using MCP_API_KEY
                return None
        return None
    except Exception as e:
        print(f"Error getting test token: {e}")
        return None


def get_client_auth_config(user_email: str = "test@example.com") -> Optional[str]:
    """Get authentication configuration for FastMCP client.

    Priority order:
      1. MCP_API_KEY environment variable (works with GoogleProvider API key bypass)
      2. JWT token from test_tokens.json (legacy, requires ENABLE_JWT_AUTH=true)
      3. None (no auth — tests will get 401 if server requires auth)

    Args:
        user_email: Email address to get token for (used by legacy JWT lookup)

    Returns:
        Bearer token string if available, None otherwise
    """
    # 1. Prefer MCP_API_KEY — works with GoogleProvider's API key bypass
    api_key = get_mcp_api_key()
    if api_key:
        return api_key

    # 2. Fall back to legacy JWT token file
    return get_test_token(user_email)
