"""
Supply Chain Risk Agent — ZIA reference implementation.

Reads vendor nodes from the SIF graph, assesses risk exposure,
and updates vendor risk scores. Adapter point for vpulse-ai integration.
"""

from __future__ import annotations

from zia.core.runtime.agent import AgentContext, AgentResult, BaseAgent
from zia.core.runtime.registry import register_agent
from zia.sif.graph.adapter import KuzuAdapter


@register_agent(
    domain="supply_chain",
    description="Assesses third-party vendor risk from the SIF graph",
    version="1.0.0",
)
class SupplyChainAgent(BaseAgent):
    """
    Assesses third-party vendor risk for all vendors in the tenant SIF graph.

    Phase 3 integration: replace _assess_vendor_stub() with vpulse-ai
    vendor analysis logic (cyber incident lookups + AI scoring).
    """

    def __init__(self, adapter: KuzuAdapter) -> None:
        self._adapter = adapter

    def execute(self, context: AgentContext) -> AgentResult:
        tenant_id = context.tenant_id
        assessed: list[dict] = []
        errors: list[str] = []

        vendors = self._adapter.get_nodes(tenant_id=tenant_id, node_type="vendor")

        for vendor in vendors:
            try:
                score = self._assess_vendor_stub(vendor)
                assessed.append({
                    "vendor_id": vendor["node_id"],
                    "risk_score": score,
                    "tier": vendor.get("tier", 1),
                })
            except Exception as e:
                errors.append(f"Failed to assess vendor {vendor.get('node_id')}: {e}")

        return AgentResult.ok(
            context,
            output={
                "vendors_assessed": len(assessed),
                "results": assessed,
                "errors": errors,
            },
        )

    def _assess_vendor_stub(self, vendor: dict) -> float:
        """
        Stub for vendor risk assessment.
        TODO: Replace with vpulse-ai incident lookup + AI scoring in Phase 3.
        """
        # Tier 1 vendors are higher risk (direct access); tier 3 are lower
        tier = int(vendor.get("tier", 2))
        base = {1: 6.0, 2: 4.0, 3: 2.0}.get(tier, 4.0)
        return base
