"""Bearer token authentication for the edge agent API."""
from __future__ import annotations

import logging
from typing import Optional

from fastapi import Depends, HTTPException, Request, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer

from radix_edge.config import get_config

logger = logging.getLogger("radix_edge.auth")

_bearer_scheme = HTTPBearer(auto_error=False)


async def require_auth(
    request: Request,
    credentials: Optional[HTTPAuthorizationCredentials] = Depends(_bearer_scheme),
) -> str:
    """Validate Bearer token. Returns the token string on success.

    Raises 401 if:
    - No auth token is configured (agent misconfigured)
    - No Authorization header provided
    - Token doesn't match configured value
    """
    config = get_config()

    if not config.auth_token:
        # No token configured — allow unauthenticated local access
        logger.debug("No auth token configured; allowing local access")
        return "local"

    if credentials is None:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Missing authorization header",
            headers={"WWW-Authenticate": "Bearer"},
        )

    if credentials.credentials != config.auth_token:
        logger.warning("Invalid auth token from %s", request.client.host if request.client else "unknown")
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid authentication token",
            headers={"WWW-Authenticate": "Bearer"},
        )

    return credentials.credentials
