"""Shared FastAPI dependencies for routers.

Centralizes DB session management and API-key authentication so routers no
longer re-declare these helpers themselves.
"""

from typing import Optional

from fastapi import Depends, Header, HTTPException, status

from agenteval.config import get_settings
from agenteval.storage.db import get_session


def get_db():
    """Yield a SQLModel Session and guarantee close() on request completion."""
    session = get_session()
    try:
        yield session
    finally:
        session.close()


def require_auth(
    x_api_key: Optional[str] = Header(default=None),
    x_auth_token: Optional[str] = Header(default=None),
) -> None:
    """Enforce authentication when any credential is configured.

    Accepted credentials (either one passes):
      - X-API-Key matching AGENTEVAL_API_KEY (machine callers, OpenClaw skill)
      - X-Auth-Token matching the web session token (browser after login)

    When neither AGENTEVAL_API_KEY nor AGENTEVAL_ADMIN_PASSWORD is set, the
    check is a no-op so local dev keeps working without extra configuration.
    """
    settings = get_settings()
    if not settings.api_key and not settings.admin_password:
        return
    if settings.api_key and x_api_key == settings.api_key:
        return
    if settings.admin_password:
        from agenteval.web.routers.auth import verify_session_token

        if x_auth_token and verify_session_token(x_auth_token):
            return
    raise HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Invalid or missing credentials",
    )


# Backwards-compatible alias: existing routers depend on require_api_key.
require_api_key = require_auth

# Convenience alias used by routers via ``dependencies=[Depends(auth_required)]``.
auth_required = Depends(require_auth)
