import os
import logging

from fastapi import Header, HTTPException
from starlette.requests import Request

logger = logging.getLogger("stock")

_WEBAI_AUTH_WARNED = False


def verify_webai_key(
    request: Request,
    x_webai_key: str | None = Header(default=None, alias="X-WebAI-Key"),
) -> None:
    """
    /api/webai/* 보호용 FastAPI dependency.

    - WEBAI_API_KEY env 미설정 → 503 (다른 endpoint 무영향). 1회만 ERROR 로그.
    - 헤더 누락 또는 키 불일치 → 401 + logger.warning(ip)
    """
    global _WEBAI_AUTH_WARNED
    configured = os.getenv("WEBAI_API_KEY", "").strip()
    if not configured:
        if not _WEBAI_AUTH_WARNED:
            logger.error("WEBAI_API_KEY not configured — refusing /api/webai/* requests")
            _WEBAI_AUTH_WARNED = True
        raise HTTPException(status_code=503, detail="webai auth not configured")

    # env 가 다시 설정되면 flag 해제 → 미래 regression 시 다시 알림
    if _WEBAI_AUTH_WARNED:
        _WEBAI_AUTH_WARNED = False

    if not x_webai_key or x_webai_key != configured:
        remote = request.client.host if request.client else "?"
        logger.warning("auth_fail path=%s remote=%s", request.url.path, remote)
        raise HTTPException(status_code=401, detail="invalid or missing X-WebAI-Key")
