"""Admin endpoints for FoundryGraph BigQuery explorer."""

from typing import Any, Dict

from fastapi import APIRouter, Depends, HTTPException, Query

from ...auth_security import AdminContext, require_admin
from ...services.foundrygraph_bq import (
    check_bq_health,
    lookup_company_by_domain,
    lookup_company_by_fg_id,
    search_companies_by_name_term,
)

router = APIRouter(tags=["Admin FoundryGraph"])


@router.get("/health")
def get_health(
    admin_ctx: AdminContext = Depends(require_admin),
) -> Dict[str, Any]:
    """Return BigQuery connectivity status and sample counts."""
    return check_bq_health()


@router.get("/stats")
def get_stats(
    admin_ctx: AdminContext = Depends(require_admin),
) -> Dict[str, Any]:
    """Return lightweight stats from the FoundryGraph gold dataset."""
    return check_bq_health()


@router.get("/search")
def search_companies(
    q: str = Query("", description="Search term"),
    limit: int = Query(50, ge=1, le=200),
    admin_ctx: AdminContext = Depends(require_admin),
) -> Dict[str, Any]:
    """Search companies by label term."""
    query = (q or "").strip()
    if not query:
        return {"companies": [], "count": 0, "query": ""}
    companies = search_companies_by_name_term(query, limit=limit)
    return {"companies": companies, "count": len(companies), "query": query}


@router.get("/company/{fg_id}")
def get_company_detail(
    fg_id: str,
    admin_ctx: AdminContext = Depends(require_admin),
) -> Dict[str, Any]:
    """Lookup a single company by FoundryGraph ID."""
    company = lookup_company_by_fg_id(fg_id)
    if not company:
        raise HTTPException(status_code=404, detail="Company not found")
    return company


@router.get("/domain/{domain}")
def get_company_by_domain(
    domain: str,
    admin_ctx: AdminContext = Depends(require_admin),
) -> Dict[str, Any]:
    """Lookup a single company by domain."""
    company = lookup_company_by_domain(domain)
    if not company:
        raise HTTPException(status_code=404, detail="Company not found")
    return company
