from __future__ import annotations

"""Anomalies resource — anomaly detection and management via the Nexure API."""

from datetime import datetime
from typing import Any

from nexure.models import AnomalyDetail, AnomalyList, BaselineResult, DetectionResult
from nexure.resources._base import BaseResource


class AnomaliesResource(BaseResource):
    """nx.anomalies — anomaly detection and management."""

    def list(
        self,
        *,
        status: str | None = None,
        severity: str | None = None,
        metric_type: str | None = None,
        since: datetime | None = None,
        limit: int = 50,
        offset: int = 0,
    ) -> AnomalyList:
        """List anomalies with optional filters.

        Args:
            status: Filter by status (open, acknowledged, resolved, dismissed).
            severity: Filter by severity (low, medium, high, critical).
            metric_type: Filter by metric type.
            since: Only show anomalies detected after this time.
            limit: Maximum results per page.
            offset: Pagination offset.
        """
        params: dict[str, Any] = {"limit": limit, "offset": offset}
        if status is not None:
            params["status"] = status
        if severity is not None:
            params["severity"] = severity
        if metric_type is not None:
            params["metric_type"] = metric_type
        if since is not None:
            params["since"] = since.isoformat()
        data = self._get("/anomalies", params=params)
        return AnomalyList(**data)

    def get(self, anomaly_id: str) -> AnomalyDetail:
        """Get full anomaly detail including trend data.

        Args:
            anomaly_id: The anomaly ID (e.g. "anm_a1b2c3d4e5f6").
        """
        data = self._get(f"/anomalies/{anomaly_id}")
        return AnomalyDetail(**data)

    def acknowledge(self, anomaly_id: str) -> AnomalyDetail:
        """Mark an anomaly as acknowledged."""
        data = self._patch(f"/anomalies/{anomaly_id}", json={"status": "acknowledged"})
        return AnomalyDetail(**data)

    def resolve(self, anomaly_id: str) -> AnomalyDetail:
        """Mark an anomaly as resolved."""
        data = self._patch(f"/anomalies/{anomaly_id}", json={"status": "resolved"})
        return AnomalyDetail(**data)

    def dismiss(self, anomaly_id: str, *, reason: str) -> AnomalyDetail:
        """Dismiss an anomaly with a reason.

        Args:
            anomaly_id: The anomaly ID.
            reason: Required explanation for dismissing.
        """
        data = self._patch(
            f"/anomalies/{anomaly_id}",
            json={"status": "dismissed", "dismiss_reason": reason},
        )
        return AnomalyDetail(**data)

    def detect(self) -> DetectionResult:
        """Trigger anomaly detection (compares recent metrics against baselines)."""
        data = self._post("/anomalies/detect")
        return DetectionResult(**data)

    def calculate_baselines(self, *, window_days: int = 30) -> BaselineResult:
        """Recalculate metric baselines.

        Args:
            window_days: Rolling window size in days (7-90, default 30).
        """
        from nexure.exceptions import _handle_response

        resp = self._client.post(
            "/anomalies/calculate-baselines",
            params={"window_days": window_days},
        )
        body = resp.json()
        _handle_response(resp.status_code, body, dict(resp.headers))
        return BaselineResult(**body)
