"""
Graph read router — query SIF nodes for a tenant.

GET /tenants/{tenant_id}/assets
GET /tenants/{tenant_id}/vulnerabilities
GET /tenants/{tenant_id}/risks
GET /tenants/{tenant_id}/vendors
"""

from __future__ import annotations

from fastapi import APIRouter, HTTPException, Query, status

from zia.api.auth import AuthDep
from zia.api.models import NodeListResponse
from zia.tenants.context import TenantRegistry

router = APIRouter(tags=["Graph"])

NODE_TYPES = ["asset", "vulnerability", "risk", "vendor", "identity", "control", "ai_model"]


def _require_tenant(tenant_id: str) -> None:
    if not TenantRegistry().exists(tenant_id):
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Tenant '{tenant_id}' not found",
        )


def _read_nodes(tenant_id: str, node_type: str) -> list[dict]:
    try:
        from zia.sif.graph.adapter import KuzuAdapter
        adapter = KuzuAdapter()
        return adapter.get_nodes(tenant_id=tenant_id, node_type=node_type)
    except ImportError:
        return []
    except Exception as exc:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Graph read failed: {exc}",
        )


@router.get(
    "/tenants/{tenant_id}/assets",
    response_model=NodeListResponse,
    summary="List asset nodes",
)
async def list_assets(tenant_id: str, _key: AuthDep) -> NodeListResponse:
    _require_tenant(tenant_id)
    nodes = _read_nodes(tenant_id, "asset")
    return NodeListResponse(tenant_id=tenant_id, node_type="asset", nodes=nodes, total=len(nodes))


@router.get(
    "/tenants/{tenant_id}/vulnerabilities",
    response_model=NodeListResponse,
    summary="List vulnerability nodes",
)
async def list_vulnerabilities(tenant_id: str, _key: AuthDep) -> NodeListResponse:
    _require_tenant(tenant_id)
    nodes = _read_nodes(tenant_id, "vulnerability")
    return NodeListResponse(tenant_id=tenant_id, node_type="vulnerability", nodes=nodes, total=len(nodes))


@router.get(
    "/tenants/{tenant_id}/risks",
    response_model=NodeListResponse,
    summary="List risk nodes",
)
async def list_risks(tenant_id: str, _key: AuthDep) -> NodeListResponse:
    _require_tenant(tenant_id)
    nodes = _read_nodes(tenant_id, "risk")
    return NodeListResponse(tenant_id=tenant_id, node_type="risk", nodes=nodes, total=len(nodes))


@router.get(
    "/tenants/{tenant_id}/vendors",
    response_model=NodeListResponse,
    summary="List vendor nodes",
)
async def list_vendors(tenant_id: str, _key: AuthDep) -> NodeListResponse:
    _require_tenant(tenant_id)
    nodes = _read_nodes(tenant_id, "vendor")
    return NodeListResponse(tenant_id=tenant_id, node_type="vendor", nodes=nodes, total=len(nodes))


@router.get(
    "/tenants/{tenant_id}/identities",
    response_model=NodeListResponse,
    summary="List identity nodes",
)
async def list_identities(tenant_id: str, _key: AuthDep) -> NodeListResponse:
    _require_tenant(tenant_id)
    nodes = _read_nodes(tenant_id, "identity")
    return NodeListResponse(tenant_id=tenant_id, node_type="identity", nodes=nodes, total=len(nodes))
