"""Example demonstrating the authenticated HTTP client.

This example shows how to use the AuthenticatedHttpClient to make
authenticated requests to an HTTP MCP server with automatic token
management and 401 handling.
"""

import asyncio
import logging

from mcp_proxy.http.client import HttpClientImpl
from mcp_proxy.http.authenticated_client import AuthenticatedHttpClient
from mcp_proxy.auth.manager import AuthenticationManagerImpl
from mcp_proxy.models import ProxyConfig

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)


async def main():
    """Demonstrate authenticated HTTP client usage."""
    
    # Create configuration
    config = ProxyConfig(
        mcp_server_url="https://d3phcl5fqkzz01.cloudfront.net/mcp/",
        oauth_provider_url="https://your-oauth-provider.com",
        client_name="example-client",
        scopes=["mcp:read", "mcp:write"],
        connection_timeout=30,
        retry_attempts=3,
    )
    
    # Create HTTP client and authentication manager
    http_client = HttpClientImpl(
        base_url=str(config.mcp_server_url),
        timeout=config.connection_timeout,
    )
    
    auth_manager = AuthenticationManagerImpl(config)
    
    # Create authenticated client
    authenticated_client = AuthenticatedHttpClient(http_client, auth_manager)
    
    try:
        # Initialize (performs DCR and obtains token)
        print("Initializing authenticated client...")
        await authenticated_client.initialize()
        print("✓ Authenticated client initialized")
        
        # Make authenticated requests
        print("\nMaking authenticated POST request...")
        response = await authenticated_client.post(
            "/",
            body='{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}',
        )
        print(f"✓ Response status: {response.status}")
        print(f"  Response body: {response.body[:100]}...")
        
        # The client automatically handles 401 responses by:
        # 1. Refreshing the token
        # 2. Retrying the request
        # 3. Falling back to DCR if refresh fails
        
        print("\nMaking another authenticated request...")
        response = await authenticated_client.get("/")
        print(f"✓ Response status: {response.status}")
        
        # Session ID is automatically managed
        if authenticated_client.session_id:
            print(f"  Session ID: {authenticated_client.session_id}")
        
    except Exception as e:
        print(f"✗ Error: {e}")
    finally:
        # Clean up resources
        print("\nClosing authenticated client...")
        await authenticated_client.close()
        print("✓ Authenticated client closed")


async def demonstrate_context_manager():
    """Demonstrate using authenticated client as context manager."""
    
    config = ProxyConfig(
        mcp_server_url="https://d3phcl5fqkzz01.cloudfront.net/mcp/",
        oauth_provider_url="https://your-oauth-provider.com",
        client_name="example-client",
        scopes=["mcp:read", "mcp:write"],
    )
    
    http_client = HttpClientImpl(base_url=str(config.mcp_server_url))
    auth_manager = AuthenticationManagerImpl(config)
    
    # Use as context manager for automatic cleanup
    async with AuthenticatedHttpClient(http_client, auth_manager) as client:
        print("Making authenticated request...")
        response = await client.post(
            "/",
            body='{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}',
        )
        print(f"Response status: {response.status}")
    
    # Client is automatically closed when exiting context


async def demonstrate_401_handling():
    """Demonstrate automatic 401 handling."""
    
    print("\n" + "="*60)
    print("Demonstrating automatic 401 handling")
    print("="*60)
    
    config = ProxyConfig(
        mcp_server_url="https://d3phcl5fqkzz01.cloudfront.net/mcp/",
        oauth_provider_url="https://your-oauth-provider.com",
        client_name="example-client",
        scopes=["mcp:read", "mcp:write"],
    )
    
    http_client = HttpClientImpl(base_url=str(config.mcp_server_url))
    auth_manager = AuthenticationManagerImpl(config)
    authenticated_client = AuthenticatedHttpClient(http_client, auth_manager)
    
    try:
        await authenticated_client.initialize()
        
        # If the server returns 401, the client will:
        # 1. Automatically refresh the token
        # 2. Retry the request with the new token
        # 3. If refresh fails, fall back to DCR
        # 4. Retry again with new credentials
        
        print("\nMaking request (will handle 401 automatically)...")
        response = await authenticated_client.post(
            "/",
            body='{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}',
        )
        
        print(f"✓ Request succeeded with status: {response.status}")
        print("  (Any 401 responses were handled automatically)")
        
    except Exception as e:
        print(f"✗ Error after all retry attempts: {e}")
    finally:
        await authenticated_client.close()


if __name__ == "__main__":
    print("="*60)
    print("Authenticated HTTP Client Example")
    print("="*60)
    
    # Run the main example
    asyncio.run(main())
    
    # Uncomment to run other examples:
    # asyncio.run(demonstrate_context_manager())
    # asyncio.run(demonstrate_401_handling())
