"""Dominion profile client — payroll-scoped Tower Agent operations.

Extends BaseProfileClient with Dominion-specific context ingestion:
- Payroll batch summaries
- FloatGuard health
- GEC frontier data
- Tax registry health
- 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 DominionProfileClient(BaseProfileClient):
    """Client for Dominion (payroll) agent profiles.

    Usage::

        client.dominion.ingest_batch(agent_id, batch_summary={
            "batch_id": "batch-42",
            "total_payouts": 150,
            "successful": 148,
            "held": 2,
            "failed": 0,
            "tax_holds": 0,
            "float_status": "healthy",
        })
        brief = client.dominion.operator_brief(agent_id)
    """

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

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

    def ingest_batch(
        self,
        agent_id: str,
        batch_summary: Dict[str, Any],
    ) -> Dict[str, Any]:
        """Ingest a payroll batch summary.

        Call after every payout batch completes. The agent uses this
        to detect patterns and generate proactive suggestions.

        Expected summary shape::

            {
                "batch_id": str,
                "total_payouts": int,
                "successful": int,
                "held": int,
                "failed": int,
                "tax_holds": int,
                "gec_metrics": {...},
                "float_status": str,
                "milestones_due": [...],
            }
        """
        resp = self._t.post(
            f"/api/agents/{agent_id}/context/batch",
            json={"type": "payroll_batch", "data": batch_summary},
        )
        return resp.json().get("data", resp.json())

    def ingest_float(
        self,
        agent_id: str,
        float_health: Dict[str, Any],
    ) -> Dict[str, Any]:
        """Ingest FloatGuard health data.

        Expected shape::

            {
                "status": "healthy" | "throttled" | "blocked",
                "utilization_ratio": float,
                "available": float,
                "committed": float,
            }
        """
        resp = self._t.post(
            f"/api/agents/{agent_id}/context/float",
            json={"type": "float_health", "data": float_health},
        )
        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 the payroll frontier.

        Expected shape (from NUMA ``/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_tax_health(
        self,
        agent_id: str,
        health: Dict[str, Any],
    ) -> Dict[str, Any]:
        """Ingest tax code registry health for hard-stop monitoring.

        Expected shape::

            {
                "active_tax_codes": int,
                "expiring_tax_codes": int,
                "regions_missing_codes": [...],
            }
        """
        resp = self._t.post(
            f"/api/agents/{agent_id}/context/tax_health",
            json={"type": "tax_health", "data": health},
        )
        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.

        Expected shape::

            [{"dimension": "E", "label": "Efficiency", "value": 0.42,
              "severity": "warning", "advice": "..."}]
        """
        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())

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

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

        Returns regime status, frontier health, float status,
        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.

        Returns the audit trail of which rules fired and why.
        """
        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

    def payout_summary(self, agent_id: str, worker_id: str) -> Dict[str, Any]:
        """Get an agent-generated worker payout summary."""
        resp = self._t.get(
            f"/api/agents/{agent_id}/payout-summary",
            params={"worker_id": worker_id},
        )
        return resp.json().get("data", resp.json())
