"""Grid Operator profile client — multi-product Tower Agent operations.

Extends BaseProfileClient with Grid-specific context ingestion:
- NUMA signal ingestion (GEC health, priority shifts, escalations)
- Grid overview stats (slots, utilization, trust distribution)
- CSK dimension hints
- Operator brief and translation log
"""

from __future__ import annotations

from typing import Any, Dict, List

from tower.profiles._base import BaseProfileClient


class GridProfileClient(BaseProfileClient):
    """Client for Grid Operator agent profiles.

    Usage::

        client.grid.ingest_numa_signals(agent_id, signals=[
            {"signal_id": "sig-1", "type": "GEC_HEALTH", "priority": 0.7,
             "frontier_id": "grid.digital_tasks", "payload": {...}},
        ])
        client.grid.ingest_stats(agent_id, stats={
            "total_slots": 500, "active_slots": 420, "completed_today": 85,
        })
        brief = client.grid.operator_brief(agent_id)
    """

    def __init__(self, transport: Any) -> None:
        super().__init__(transport, profile="grid_operator")

    # ── Context Ingestion ─────────────────────────────────────────────

    def ingest_numa_signals(
        self,
        agent_id: str,
        signals: List[Dict[str, Any]],
    ) -> Dict[str, Any]:
        """Ingest raw NUMA signals from the signal protocol.

        Expected signal shape::

            {
                "signal_id": str,
                "type": "GEC_HEALTH" | "PRIORITY_SHIFT" | "GOVERNANCE_ALERT" | "ESCALATION",
                "priority": float,
                "frontier_id": str,
                "payload": {...},
                "expires_at": float,
                "created_at": float,
            }
        """
        resp = self._t.post(
            f"/api/agents/{agent_id}/context/numa_signals",
            json={"type": "numa_signals", "signals": signals},
        )
        return resp.json().get("data", resp.json())

    def ingest_gec(
        self,
        agent_id: str,
        frontier_id: str,
        gec_data: Dict[str, Any],
    ) -> Dict[str, Any]:
        """Ingest GEC health data for a specific Grid frontier.

        Expected shape (from NUMA ``GET /gec/{frontier_id}``)::

            {
                "frontier_id": str,
                "gec0": float,
                "metallic_label": str,
                "attractor_stability": float,
                "delta_gec": float,
                "trend": str,
                "csk": {"S": float, "H": float, "D": float, "R": float, "E": float},
            }
        """
        resp = self._t.post(
            f"/api/agents/{agent_id}/context/gec",
            json={"type": "gec_health", "frontier_id": frontier_id, "data": gec_data},
        )
        return resp.json().get("data", resp.json())

    def ingest_csk_hints(
        self,
        agent_id: str,
        frontier_id: str,
        hints: List[Dict[str, Any]],
    ) -> Dict[str, Any]:
        """Ingest CSK dimension hints from NUMA for a Grid frontier."""
        resp = self._t.post(
            f"/api/agents/{agent_id}/context/csk_hints",
            json={"type": "csk_hints", "frontier_id": frontier_id, "hints": hints},
        )
        return resp.json().get("data", resp.json())

    def ingest_stats(
        self,
        agent_id: str,
        stats: Dict[str, Any],
    ) -> Dict[str, Any]:
        """Ingest Grid overview stats for operational intelligence.

        Expected shape (from Grid's ``/api/overview``)::

            {
                "total_slots": int,
                "active_slots": int,
                "completed_today": int,
                "total_participants": int,
                "slots_by_class": {...},
                "slots_by_status": {...},
                "trust_distribution": {...},
            }
        """
        resp = self._t.post(
            f"/api/agents/{agent_id}/context/grid_stats",
            json={"type": "grid_stats", "data": stats},
        )
        return resp.json().get("data", resp.json())

    # ── Intelligence Queries ──────────────────────────────────────────

    def operator_brief(self, agent_id: str) -> Dict[str, Any]:
        """Get an operator-facing Grid brief.

        Returns dominant regime across all grid.* frontiers,
        utilization snapshot, trust distribution, active suggestions,
        escalations, and top suggestion.
        """
        resp = self._t.get(f"/api/agents/{agent_id}/brief")
        return resp.json().get("data", resp.json())

    def translation_log(self, agent_id: str, *, limit: int = 50) -> List[Dict[str, Any]]:
        """Get recent NUMA signal translation log entries."""
        resp = self._t.get(
            f"/api/agents/{agent_id}/translation-log",
            params={"limit": limit},
        )
        data = resp.json()
        return data.get("data", data) if isinstance(data, dict) else data
