"""
Example: Using AuthManager with FastAPI.

Before running, set the environment variable:
    export NEURONOS_AUTH_JWKS_URL="https://your-app.clerk.accounts.dev/.well-known/jwks.json"

Three levels of protection:
    1. auth.require_auth()                              → just verify the token
    2. auth.require_roles(["coordinador"])               → verify token + check role
    3. auth.require_org_role("org_2x", ["coordinador"])  → verify token + org + role
"""

from fastapi import FastAPI, Depends
from fastapi.middleware.cors import CORSMiddleware

from neuronos_capabilities import AuthManager

app = FastAPI()
app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:3000"],
    allow_methods=["*"],
    allow_headers=["*"],
)

auth = AuthManager()


# --- Level 1: Auth only ---
@app.get("/api/test-auth")
async def test_auth(user: dict = Depends(auth.require_auth())):
    """Any authenticated user."""
    return {"status": "Token is valid", "user_id": user.get("sub")}


# --- Level 2: Auth + Role ---
@app.get("/api/coordinator-action")
async def coordinator_action(
    user: dict = Depends(auth.require_roles(["coordinador"])),
):
    """Requires 'coordinador' role from public_metadata.rol."""
    return {"message": "Coordinator access granted", "user_id": user.get("sub")}


# --- Level 3: Auth + Org + Role ---
@app.get("/api/org-coordinator")
async def org_coordinator(
    user: dict = Depends(
        auth.require_org_role("org_2abc123", ["coordinador"])
    ),
):
    """Requires org membership AND 'coordinador' role."""
    return {
        "message": "Org Coordinator access granted",
        "user_id": user.get("sub"),
    }
