"""
Telemetry router.

POST /tenants/{tenant_id}/telemetry — ingest an event into the SIF graph
"""

from __future__ import annotations

from datetime import datetime, timezone

from fastapi import APIRouter, HTTPException, status

from zia.api.auth import AuthDep
from zia.api.models import TelemetryEventRequest, TelemetryEventResponse
from zia.tenants.context import TenantRegistry

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

SUPPORTED_EVENT_TYPES = {
    "vulnerability_found",
    "asset_discovered",
    "control_updated",
    "vendor_assessed",
}


@router.post(
    "/tenants/{tenant_id}/telemetry",
    response_model=TelemetryEventResponse,
    status_code=status.HTTP_202_ACCEPTED,
    summary="Ingest a telemetry event into the SIF graph",
)
async def ingest_telemetry(
    tenant_id: str,
    body: TelemetryEventRequest,
    _key: AuthDep,
) -> TelemetryEventResponse:
    """
    Push a security event into the SIF graph for a tenant.

    Supported event_types:
    - `vulnerability_found`
    - `asset_discovered`
    - `control_updated`
    - `vendor_assessed`
    """
    if not TenantRegistry().exists(tenant_id):
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Tenant '{tenant_id}' not found",
        )

    if body.event_type not in SUPPORTED_EVENT_TYPES:
        raise HTTPException(
            status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
            detail=(
                f"Unsupported event_type '{body.event_type}'. "
                f"Supported: {sorted(SUPPORTED_EVENT_TYPES)}"
            ),
        )

    # Merge event_type into payload for the ingestor
    event = {"event_type": body.event_type, **body.payload}

    try:
        from zia.sif.graph.adapter import KuzuAdapter
        adapter = KuzuAdapter()
        if adapter is None:
            raise ImportError("KuzuAdapter unavailable")
        adapter.initialize_schema(tenant_id)
        from zia.sif.telemetry.ingestor import TelemetryIngestor
        ingestor = TelemetryIngestor(adapter)
        ingestor.ingest(event, tenant_id=tenant_id)
    except (ImportError, AttributeError, TypeError):
        # kuzu not installed or stub returned None — accept event, skip graph write
        pass
    except Exception as exc:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Ingestion failed: {exc}",
        )

    return TelemetryEventResponse(
        accepted=True,
        event_type=body.event_type,
        tenant_id=tenant_id,
        ingested_at=datetime.now(timezone.utc),
    )
