# app/core/auth.py
from fastapi import Header, HTTPException, status, Request
from app.db.database import get_key
from app.core.config import settings


class ClientInfo:
    def __init__(self, key: str, name: str):
        self.key  = key
        self.name = name


async def require_api_key(
    request: Request,
    x_api_key: str | None = Header(default=None, alias="X-API-Key"),
) -> ClientInfo:
    """
    - If X-API-Key header is present → validate it (for external clients).
    - If request comes from localhost with no key → allow as 'local UI'.
    - Otherwise → 401.
    """
    # Allow local browser UI without a key
    client_host = request.client.host if request.client else ""
    is_local = client_host in ("127.0.0.1", "::1", "localhost")

    if not x_api_key:
        if is_local:
            return ClientInfo(key="local", name="Local UI")
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Missing X-API-Key header.",
            headers={"WWW-Authenticate": "ApiKey"},
        )

    key_data = get_key(x_api_key)
    if not key_data:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid or inactive API key.",
            headers={"WWW-Authenticate": "ApiKey"},
        )
    return ClientInfo(key=x_api_key, name=key_data["client_name"])

async def require_admin_key(
    x_admin_user: str = Header(..., alias="X-Admin-User"),
    x_admin_password: str = Header(..., alias="X-Admin-Password"),
) -> bool:
    if (x_admin_user != settings.ADMIN_USERNAME or
        x_admin_password != settings.ADMIN_PASSWORD):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Invalid admin credentials.",
        )
    return True
