"""AgentBill Signal Types Resource - CRUD operations via unified HTTP client"""

from typing import Any, Dict, Optional
from ..http_client import AgentBillHTTPClient
from ..raw_response import WithRawResponseMixin
from ..logger import get_logger

_log = get_logger("signal_types")


class SignalTypesResource(WithRawResponseMixin):
    """Signal Types resource for CRUD operations via unified HTTP client."""

    _resource_path = "/functions/v1/api-signal-types"

    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 list(self, category: Optional[str] = None, include_global: bool = True) -> Dict[str, Any]:
        """List signal types with optional filters."""
        params = {}
        if category:
            params["category"] = category
        if not include_global:
            params["include_global"] = "false"

        resp = self._http.get(self._resource_path, params=params)
        return resp.data

    def create(
        self,
        name: str,
        category: str = "activity",
        description: Optional[str] = None,
        unit: Optional[str] = None,
        default_value: Optional[float] = None,
        external_id: Optional[str] = None,
        expected_metrics: Optional[Dict[str, Any]] = None,
        revenue_formula: Optional[str] = None,
        validation_rules: Optional[Dict[str, Any]] = None,
    ) -> Dict[str, Any]:
        """Create a new signal type."""
        payload: Dict[str, Any] = {"name": name, "category": category}
        for key, val in {
            "description": description, "unit": unit, "default_value": default_value,
            "external_id": external_id, "expected_metrics": expected_metrics,
            "revenue_formula": revenue_formula, "validation_rules": validation_rules,
        }.items():
            if val is not None:
                payload[key] = val

        _log.debug("Creating signal type: %s", name)
        resp = self._http.post(self._resource_path, json=payload)
        return resp.data

    def get(self, signal_type_id: str, by_external_id: bool = False) -> Dict[str, Any]:
        """Get a signal type by ID or external_id."""
        params = {}
        if by_external_id:
            params["external_id"] = signal_type_id
        else:
            params["id"] = signal_type_id

        resp = self._http.get(self._resource_path, params=params)
        return resp.data

    def update(
        self,
        signal_type_id: str,
        name: Optional[str] = None,
        description: Optional[str] = None,
        category: Optional[str] = None,
        unit: Optional[str] = None,
        default_value: Optional[float] = None,
        external_id: Optional[str] = None,
        expected_metrics: Optional[Dict[str, Any]] = None,
        revenue_formula: Optional[str] = None,
        validation_rules: Optional[Dict[str, Any]] = None,
        is_active: Optional[bool] = None,
    ) -> Dict[str, Any]:
        """Update a signal type."""
        payload: Dict[str, Any] = {"id": signal_type_id}
        for key, val in {
            "name": name, "description": description, "category": category,
            "unit": unit, "default_value": default_value, "external_id": external_id,
            "expected_metrics": expected_metrics, "revenue_formula": revenue_formula,
            "validation_rules": validation_rules, "is_active": is_active,
        }.items():
            if val is not None:
                payload[key] = val

        resp = self._http.patch(self._resource_path, json=payload)
        return resp.data

    def delete(self, signal_type_id: str) -> None:
        """Delete a signal type."""
        self._http.request("DELETE", self._resource_path, json={"id": signal_type_id})
