"""
Demo FastAPI application showcasing MCP Guardian security middleware.

This application demonstrates how to use the Guardian class to protect
FastAPI endpoints with JWT authentication, scope-based authorization,
and rate limiting.
"""

from fastapi import FastAPI, Request
from mcp_guardian import Guardian

# Initialize FastAPI app
app = FastAPI(
    title="MCP Guardian Demo",
    description="A demonstration of MCP Guardian security middleware",
    version="1.0.0"
)

# Initialize Guardian with configuration
# Note: Copy config.example.yaml to config.yaml and update with your settings
guardian = Guardian(config_path="config.yaml")


@app.get("/")
async def root():
    """
    Public endpoint that doesn't require authentication.
    
    Returns:
        Welcome message
    """
    return {
        "message": "Welcome to MCP Guardian Demo!",
        "description": "This is a public endpoint that doesn't require authentication.",
        "protected_endpoints": {
            "/tools/calculate": "Requires 'tools:calculator:execute' scope"
        }
    }


@app.post("/tools/calculate")
@guardian.protect(scope="tools:calculator:execute")
async def calculate(request: Request, expression: str = "2 + 2"):
    """
    Protected endpoint that requires JWT authentication and specific scope.
    
    This endpoint demonstrates:
    - JWT token validation
    - Scope-based authorization
    - Rate limiting
    - Access to validated token payload
    
    Args:
        request: FastAPI request object (contains validated token in request.state.token)
        expression: Mathematical expression to evaluate (default: "2 + 2")
        
    Returns:
        Calculation result and user information from the validated token
    """
    # Access the validated JWT payload
    token_payload = request.state.token
    
    # Simple and safe expression evaluation (for demo purposes)
    # In production, you'd want more robust expression parsing
    try:
        # Only allow basic arithmetic operations for safety
        allowed_chars = set('0123456789+-*/(). ')
        if not all(c in allowed_chars for c in expression):
            raise ValueError("Invalid characters in expression")
        
        result = eval(expression)
    except Exception as e:
        result = f"Error evaluating expression: {str(e)}"
    
    return {
        "message": "Calculation completed successfully!",
        "expression": expression,
        "result": result,
        "user_info": {
            "user_id": token_payload.get('sub'),
            "scopes": token_payload.get('scopes', []),
            "audience": token_payload.get('aud'),
            "expires_at": token_payload.get('exp')
        },
        "security_notes": [
            "This endpoint is protected by MCP Guardian",
            "JWT token was validated successfully",
            "Scope 'tools:calculator:execute' was verified",
            "Rate limiting was applied based on user ID"
        ]
    }


@app.get("/health")
async def health_check():
    """
    Health check endpoint for monitoring.
    
    Returns:
        Service health status
    """
    return {
        "status": "healthy",
        "service": "MCP Guardian Demo",
        "version": "1.0.0"
    }


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)
