from typing import Optional

from fastapi import APIRouter, Depends

from dependencies import verify_admin_api_key
import services.cache_service as cache_service

router = APIRouter(
    prefix="/admin/cache",
    tags=["admin-cache"],
    dependencies=[Depends(verify_admin_api_key)],
)


@router.post("/clear")
async def clear_query_cache(company_id: Optional[int] = None):
    """Clears cached HR-assist query answers (services/cache_service.py's
    v4:hr_query:<company_id>:<query> keys). Needed after any change to
    classify_node.py's intent taxonomy/prompt or to a node's response
    text — an answer cached under the OLD (now-wrong) logic keeps being
    replayed verbatim to every caller phrasing the same query, for up to
    REDIS_EXPIRATION seconds, regardless of how correct the fix in the
    code is. Confirmed live: the large_team_review classification fix
    (HA-214) had no effect on a query already cached under the prior
    misclassification until this was called.

    company_id scopes the clear to one company; omitted clears every
    company's cached query answers.
    """
    pattern = f"hr_query:{company_id}:*" if company_id is not None else "hr_query:*"
    cleared = cache_service.clear_cache(pattern)
    return {"success": cleared, "pattern": pattern}