from typing import List
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2AuthorizationCodeBearer
from jose import jwt, JWTError

OAUTH2_SCHEME = OAuth2AuthorizationCodeBearer(
    authorizationUrl="https://auth.example/authorize",
    tokenUrl="https://auth.example/token",
    scopes={
        "citizen:write": "Citizen can create documents and threads",
        "official:read": "Official can read documents and threads",
        "official:write": "Official can answer and export",
    },
)

JWT_ISSUER = "https://auth.example"
JWT_AUDIENCE = "dvd-api"
JWT_PUBLIC_KEY = "FAKE_PUBLIC_KEY_FOR_DEMO"

class UserContext:
    def __init__(self, sub: str, scopes: List[str]):
        self.sub = sub
        self.scopes = scopes

    def has_scope(self, scope: str) -> bool:
        return scope in self.scopes

async def get_current_user(token: str = Depends(OAUTH2_SCHEME)) -> UserContext:
    try:
        payload = jwt.get_unverified_claims(token)
    except JWTError:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid token",
        )
    sub = payload.get("sub")
    scopes = payload.get("scope", "").split()
    if not sub:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid token: no subject",
        )
    return UserContext(sub=sub, scopes=scopes)
