"""AgentBill Signals Resource — REST API for signal CRUD via unified HTTP client.

v8.1.0: Created as part of Signals Revamp Phase 2.
v10.4.1: Migrated to unified HTTP client.
"""
from typing import Any, Dict, List, Optional
from ..http_client import AgentBillHTTPClient
from ..raw_response import WithRawResponseMixin
from ..logger import get_logger
from ..types import Signal, BulkResult

_log = get_logger("signals_resource")


class SignalsResource(WithRawResponseMixin):
    """REST API resource for signal CRUD operations.

    All HTTP calls go through the shared ``AgentBillHTTPClient``.
    """

    _resource_path = "/functions/v1/list-signals"

    def __init__(self, config: Dict[str, Any], http_client: "AgentBillHTTPClient" = None):
        self.config = config
        self.debug = config.get("debug", False)
        self._http = http_client

    def create(self, signal: Signal) -> Dict[str, Any]:
        """Create a signal via REST API (standalone, no trace context needed)."""
        payload: Dict[str, Any] = dict(signal)

        # Inject customer/agent from config if not in signal
        if "customer_id" not in payload and self.config.get("customer_id"):
            payload["customer_id"] = self.config["customer_id"]
        if "customer_id" not in payload and self.config.get("customer_external_id"):
            payload["customer_external_id"] = self.config["customer_external_id"]
        if self.config.get("agent_id") and "agent_id" not in payload:
            payload["agent_id"] = self.config["agent_id"]
        if self.config.get("agent_external_id") and "agent_external_id" not in payload:
            payload["agent_external_id"] = self.config["agent_external_id"]

        try:
            resp = self._http.post("/functions/v1/api-ingest", json=payload)
            result = resp.data if isinstance(resp.data, dict) else {}
            is_success = resp.ok and result.get("success", True)

            _log.debug("Signal '%s' %s", payload.get("event_name", "unknown"),
                       "created" if is_success else "failed")

            return {"success": is_success, "status_code": resp.status, **result}
        except Exception as e:
            _log.warning("Signal creation error: %s", e)
            return {"success": False, "error": str(e)}

    def create_many(self, signals: List[Signal]) -> BulkResult:
        """Create multiple signals via REST API."""
        results: List[Dict[str, Any]] = []
        processed = 0

        for sig in signals:
            result = self.create(sig)
            results.append(result)
            if result.get("success"):
                processed += 1

        return {
            "success": processed == len(signals),
            "processed": processed,
            "results": results,
            "error": None if processed == len(signals) else f"{len(signals) - processed} signal(s) failed",
        }

    def list(
        self,
        *,
        limit: int = 50,
        offset: int = 0,
        customer_id: Optional[str] = None,
        agent_id: Optional[str] = None,
        event_name: Optional[str] = None,
        start_date: Optional[str] = None,
        end_date: Optional[str] = None,
    ) -> Dict[str, Any]:
        """List signals via REST API."""
        params: Dict[str, str] = {"limit": str(limit), "offset": str(offset)}
        if customer_id:
            params["customer_id"] = customer_id
        if agent_id:
            params["agent_id"] = agent_id
        if event_name:
            params["event_name"] = event_name
        if start_date:
            params["start_date"] = start_date
        if end_date:
            params["end_date"] = end_date

        try:
            resp = self._http.get(self._resource_path, params=params)
            result = resp.data if isinstance(resp.data, dict) else {}

            _log.debug("Listed %d signals", len(result.get("data", [])))

            return {"success": resp.ok, "status_code": resp.status, **result}
        except Exception as e:
            _log.warning("Signal list error: %s", e)
            return {"success": False, "error": str(e), "data": []}
