"""
Klausur-Service Authentication Service

Functions for JWT authentication and user extraction.
"""

from typing import Dict
import jwt

from fastapi import HTTPException, Request

from config import JWT_SECRET, ENVIRONMENT


def get_current_user(request: Request) -> Dict:
    """
    Extract user from JWT token.

    Args:
        request: FastAPI Request object

    Returns:
        User payload dict containing user_id, role, email, etc.

    Raises:
        HTTPException: If token is missing, expired, or invalid
    """
    auth_header = request.headers.get("Authorization", "")

    if not auth_header.startswith("Bearer "):
        if ENVIRONMENT == "development":
            return {
                "user_id": "demo-teacher",
                "role": "admin",
                "email": "demo@breakpilot.app"
            }
        raise HTTPException(status_code=401, detail="Missing authorization header")

    token = auth_header.replace("Bearer ", "")
    try:
        payload = jwt.decode(token, JWT_SECRET, algorithms=["HS256"])
        return payload
    except jwt.ExpiredSignatureError:
        raise HTTPException(status_code=401, detail="Token expired")
    except jwt.InvalidTokenError:
        raise HTTPException(status_code=401, detail="Invalid token")
