from __future__ import annotations

from fastapi import APIRouter, Header, HTTPException, status

from app.core.config import settings
from app.services import qdrant_index_service

router = APIRouter(tags=["Internal Maintenance"])

INTERNAL_SECRET_HEADER = "x-internal-secret"


def _require_internal_secret(x_internal_secret: str | None) -> None:
    configured = settings.GATEWAY_INTERNAL_SERVICE_SECRET.strip()
    if not configured:
        if settings.is_local():
            return
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail="internal maintenance API is not configured",
        )
    if not x_internal_secret or x_internal_secret.strip() != configured:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="invalid internal secret",
        )


@router.delete(
    "/internal/v1/repos/{repo_id:path}/vectors",
    status_code=status.HTTP_200_OK,
)
async def delete_repo_vectors(
    repo_id: str,
    x_internal_secret: str | None = Header(default=None, alias="X-Internal-Secret"),
) -> dict[str, str]:
    _require_internal_secret(x_internal_secret)
    repo_id = repo_id.strip()
    if not repo_id:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="repo_id is required")
    return await qdrant_index_service.delete_repo_vectors(repo_id)
