"""
Minimal example service with JWT verification using JWKS.
Auto-generated by @vmenon25/mcp-server-webauthn-client

This service demonstrates zero-trust architecture integration:
- JWT verification using WebAuthn server's JWKS endpoint (RFC 7517)
- Protected endpoints requiring valid JWT tokens
- Example API response with authenticated user info
- PyJWKClient for automatic key fetching and caching
"""
from fastapi import FastAPI, Depends, HTTPException, Header
from typing import Optional
import jwt
import os
from jwt import PyJWKClient

app = FastAPI(
    title="WebAuthn Example Service",
    description="Protected API service demonstrating JWT verification with JWKS",
    version="1.0.0"
)

# Configuration
JWKS_URL = os.getenv("WEBAUTHN_JWKS_URL", "http://webauthn-server:8080/.well-known/jwks.json")

# PyJWKClient automatically fetches and caches JWKS (5 minute TTL default)
jwks_client = PyJWKClient(JWKS_URL)

def verify_jwt_token(authorization: Optional[str] = Header(None)) -> dict:
    """Verify JWT from Authorization header using JWKS"""
    if not authorization:
        raise HTTPException(
            status_code=401,
            detail="Missing Authorization header"
        )

    if not authorization.startswith("Bearer "):
        raise HTTPException(
            status_code=401,
            detail="Invalid Authorization header format. Expected 'Bearer <token>'"
        )

    token = authorization.split(" ")[1]

    try:
        # PyJWKClient fetches the signing key from JWKS endpoint
        signing_key = jwks_client.get_signing_key_from_jwt(token)
        payload = jwt.decode(
            token,
            signing_key.key,
            algorithms=["RS256"],
            issuer="mpo-webauthn",
            audience="webauthn-clients"
        )
        return payload
    except jwt.ExpiredSignatureError:
        raise HTTPException(status_code=401, detail="Token expired")
    except jwt.InvalidTokenError as e:
        raise HTTPException(status_code=401, detail=f"Invalid token: {str(e)}")

@app.get("/health")
def health():
    """Health check (no authentication required)"""
    return {
        "status": "healthy",
        "service": "webauthn-example-service",
        "version": "1.0.0"
    }

@app.get("/api/user/profile")
def get_profile(user: dict = Depends(verify_jwt_token)):
    """Protected endpoint - requires valid JWT"""
    return {
        "username": user["sub"],
        "message": "This is protected data from the example service",
        "authenticated_at": user.get("iat"),
        "expires_at": user.get("exp"),
        "issuer": user.get("iss")
    }

@app.get("/api/example/data")
def get_example_data(user: dict = Depends(verify_jwt_token)):
    """Another protected endpoint - demonstrates multiple API routes"""
    return {
        "data": [
            {"id": 1, "value": "Sample data 1"},
            {"id": 2, "value": "Sample data 2"},
            {"id": 3, "value": "Sample data 3"}
        ],
        "user": user["sub"],
        "note": "All /api/* routes are protected by Envoy Gateway JWT verification"
    }

if __name__ == "__main__":
    import uvicorn
    port = int(os.getenv("APP_PORT", "9000"))
    uvicorn.run(app, host="0.0.0.0", port=port)
