"""
Healer Agent Tools

Tools for self-healing operations:
- Circuit breaker management
- Anomaly detection
- Healing action execution
- Chaos engineering
"""

from __future__ import annotations

import asyncio
import logging
import uuid
from datetime import datetime, timezone
from typing import Any

import redis.asyncio as redis

from ..self_healing_types import (
    AnomalyDetectionConfig,
    AnomalySeverity,
    CircuitBreakerConfig,
    CircuitState,
    ChaosExperiment,
    ChaosExperimentResult,
    ChaosExperimentType,
    ComponentHealth,
    DetectionMethod,
    HealingAction,
    HealingActionType,
    HealingResult,
    HealingStatus,
    HealingTrigger,
    HealthCheckType,
    HealthStatus,
    MetricPoint,
    SystemHealth,
    TripReason,
)
from ..services.circuit_breaker import CircuitBreaker, CircuitBreakerRegistry
from ..services.anomaly_detector import AnomalyDetector, MultiMetricAnomalyDetector

logger = logging.getLogger(__name__)


# =============================================================================
# Healer Tools - Circuit Breaker Management
# =============================================================================

class CircuitBreakerTools:
    """Tools for circuit breaker management"""

    def __init__(self, redis_url: str | None = None):
        """Initialize circuit breaker tools"""
        self.redis_url = redis_url or "redis://localhost:6379"
        self._redis: redis.Redis | None = None
        self._registry: CircuitBreakerRegistry | None = None

    async def initialize(self) -> None:
        """Initialize Redis and circuit breaker registry"""
        try:
            self._redis = redis.from_url(self.redis_url)
            self._registry = CircuitBreakerRegistry(self._redis)
            await self._registry.initialize()
            logger.info("CircuitBreakerTools initialized")
        except Exception as e:
            logger.warning(f"Failed to initialize Redis: {e}")
            self._registry = CircuitBreakerRegistry()

    async def close(self) -> None:
        """Clean up resources"""
        if self._redis:
            await self._redis.close()

    async def list_circuits(self) -> list[dict[str, Any]]:
        """List all circuit breakers and their states"""
        if not self._registry:
            await self.initialize()

        states = self._registry.list_all()
        return [
            {
                "name": s.name,
                "state": s.state.value,
                "trip_reason": s.trip_reason.value if s.trip_reason else None,
                "tripped_at": s.tripped_at.isoformat() if s.tripped_at else None,
                "stats": {
                    "total_requests": s.stats.total_requests,
                    "successful_requests": s.stats.successful_requests,
                    "failed_requests": s.stats.failed_requests,
                    "error_rate": (
                        s.stats.failed_requests / max(s.stats.total_requests, 1)
                    ),
                    "avg_latency_ms": s.stats.avg_latency_ms,
                },
            }
            for s in states
        ]

    async def list_open_circuits(self) -> list[dict[str, Any]]:
        """List all open (tripped) circuit breakers"""
        if not self._registry:
            await self.initialize()

        states = self._registry.list_open()
        return [
            {
                "name": s.name,
                "trip_reason": s.trip_reason.value if s.trip_reason else None,
                "tripped_at": s.tripped_at.isoformat() if s.tripped_at else None,
                "next_retry_at": s.next_retry_at.isoformat() if s.next_retry_at else None,
            }
            for s in states
        ]

    async def get_circuit_state(self, name: str) -> dict[str, Any]:
        """Get state of a specific circuit breaker"""
        if not self._registry:
            await self.initialize()

        breaker = self._registry.get(name)
        if not breaker:
            return {"error": f"Circuit breaker '{name}' not found"}

        state = breaker.get_state()
        return {
            "name": state.name,
            "state": state.state.value,
            "trip_reason": state.trip_reason.value if state.trip_reason else None,
            "tripped_at": state.tripped_at.isoformat() if state.tripped_at else None,
            "next_retry_at": state.next_retry_at.isoformat() if state.next_retry_at else None,
            "stats": {
                "total_requests": state.stats.total_requests,
                "successful_requests": state.stats.successful_requests,
                "failed_requests": state.stats.failed_requests,
                "timeout_requests": state.stats.timeout_requests,
                "avg_latency_ms": state.stats.avg_latency_ms,
                "p99_latency_ms": state.stats.p99_latency_ms,
                "consecutive_failures": state.stats.consecutive_failures,
                "consecutive_successes": state.stats.consecutive_successes,
            },
            "config": {
                "error_threshold": state.config.error_threshold,
                "timeout_threshold": state.config.timeout_threshold,
                "latency_threshold_ms": state.config.latency_threshold_ms,
                "recovery_timeout_seconds": state.config.recovery_timeout_seconds,
            },
        }

    async def trip_circuit(self, name: str, reason: str = "manual") -> dict[str, Any]:
        """Manually trip a circuit breaker"""
        if not self._registry:
            await self.initialize()

        breaker = self._registry.get(name)
        if not breaker:
            # Create a new circuit breaker
            breaker = await self._registry.get_or_create(name)

        trip_reason = TripReason(reason) if reason in [r.value for r in TripReason] else TripReason.MANUAL
        await breaker.trip(trip_reason)

        logger.info(f"[HEALER] Circuit '{name}' tripped manually: {reason}")

        return {
            "success": True,
            "circuit": name,
            "action": "trip",
            "reason": trip_reason.value,
            "new_state": CircuitState.OPEN.value,
        }

    async def reset_circuit(self, name: str) -> dict[str, Any]:
        """Reset a circuit breaker to closed state"""
        if not self._registry:
            await self.initialize()

        breaker = self._registry.get(name)
        if not breaker:
            return {"error": f"Circuit breaker '{name}' not found"}

        await breaker.reset()

        logger.info(f"[HEALER] Circuit '{name}' reset to CLOSED")

        return {
            "success": True,
            "circuit": name,
            "action": "reset",
            "new_state": CircuitState.CLOSED.value,
        }

    async def reset_all_circuits(self) -> dict[str, Any]:
        """Reset all circuit breakers"""
        if not self._registry:
            await self.initialize()

        await self._registry.reset_all()

        logger.info("[HEALER] All circuits reset to CLOSED")

        return {
            "success": True,
            "action": "reset_all",
            "message": "All circuit breakers reset to CLOSED state",
        }


# =============================================================================
# Healer Tools - Anomaly Detection
# =============================================================================

class AnomalyDetectorTools:
    """Tools for anomaly detection"""

    def __init__(self, redis_url: str | None = None):
        """Initialize anomaly detector tools"""
        self.redis_url = redis_url or "redis://localhost:6379"
        self._redis: redis.Redis | None = None
        self._detector: MultiMetricAnomalyDetector | None = None

    async def initialize(self) -> None:
        """Initialize Redis and anomaly detector"""
        try:
            self._redis = redis.from_url(self.redis_url)
            self._detector = MultiMetricAnomalyDetector(self._redis)
            logger.info("AnomalyDetectorTools initialized")
        except Exception as e:
            logger.warning(f"Failed to initialize Redis: {e}")
            self._detector = MultiMetricAnomalyDetector()

    async def close(self) -> None:
        """Clean up resources"""
        if self._redis:
            await self._redis.close()

    async def add_metric(
        self,
        metric_name: str,
        detection_method: str = "zscore",
        sensitivity: float = 3.0,
    ) -> dict[str, Any]:
        """Add a metric to monitor for anomalies"""
        if not self._detector:
            await self.initialize()

        method = DetectionMethod(detection_method) if detection_method in [m.value for m in DetectionMethod] else DetectionMethod.ZSCORE

        config = AnomalyDetectionConfig(
            metric_name=metric_name,
            detection_method=method,
            sensitivity=sensitivity,
        )

        await self._detector.add_detector(metric_name, config)

        return {
            "success": True,
            "metric": metric_name,
            "detection_method": method.value,
            "sensitivity": sensitivity,
        }

    async def add_data_point(
        self,
        metric_name: str,
        value: float,
        labels: dict[str, str] | None = None,
    ) -> dict[str, Any]:
        """Add a data point and check for anomalies"""
        if not self._detector:
            await self.initialize()

        point = MetricPoint(
            timestamp=datetime.now(timezone.utc),
            value=value,
            metric_name=metric_name,
            labels=labels or {},
        )

        anomaly = await self._detector.add_point(metric_name, point)

        if anomaly:
            return {
                "is_anomaly": True,
                "anomaly": {
                    "id": anomaly.anomaly_id,
                    "type": anomaly.anomaly_type.value,
                    "severity": anomaly.severity.value,
                    "expected_value": anomaly.expected_value,
                    "actual_value": anomaly.actual_value,
                    "deviation": anomaly.deviation,
                    "confidence": anomaly.confidence,
                },
            }

        return {"is_anomaly": False, "value": value}

    async def detect_anomalies(self) -> dict[str, Any]:
        """Run anomaly detection on all monitored metrics"""
        if not self._detector:
            await self.initialize()

        results = await self._detector.detect_all()

        return {
            "metrics_analyzed": len(results),
            "results": {
                name: {
                    "is_healthy": result.is_healthy,
                    "anomalies_count": len(result.anomalies),
                    "baseline_mean": result.baseline_mean,
                    "baseline_std": result.baseline_std,
                    "anomalies": [
                        {
                            "id": a.anomaly_id,
                            "type": a.anomaly_type.value,
                            "severity": a.severity.value,
                            "deviation": a.deviation,
                        }
                        for a in result.anomalies
                    ],
                }
                for name, result in results.items()
            },
        }

    async def get_statistics(self) -> dict[str, Any]:
        """Get statistics for all monitored metrics"""
        if not self._detector:
            await self.initialize()

        return self._detector.get_all_statistics()


# =============================================================================
# Healer Tools - Healing Actions
# =============================================================================

class HealingActionTools:
    """Tools for executing healing actions"""

    def __init__(self, redis_url: str | None = None):
        """Initialize healing action tools"""
        self.redis_url = redis_url or "redis://localhost:6379"
        self._redis: redis.Redis | None = None
        self._action_history: list[HealingResult] = []

    async def initialize(self) -> None:
        """Initialize Redis connection"""
        try:
            self._redis = redis.from_url(self.redis_url)
            logger.info("HealingActionTools initialized")
        except Exception as e:
            logger.warning(f"Failed to initialize Redis: {e}")

    async def close(self) -> None:
        """Clean up resources"""
        if self._redis:
            await self._redis.close()

    async def execute_healing(
        self,
        action_type: str,
        target: str,
        parameters: dict[str, Any] | None = None,
    ) -> dict[str, Any]:
        """Execute a healing action"""
        action_id = str(uuid.uuid4())[:8]
        start_time = datetime.now(timezone.utc)
        parameters = parameters or {}

        try:
            healing_type = HealingActionType(action_type)
        except ValueError:
            return {"error": f"Unknown action type: {action_type}"}

        logger.info(f"[HEALER] Executing {action_type} on {target}")

        try:
            # Execute based on action type
            if healing_type == HealingActionType.CACHE_CLEAR:
                result = await self._clear_cache(target, parameters)
            elif healing_type == HealingActionType.RATE_LIMIT:
                result = await self._apply_rate_limit(target, parameters)
            elif healing_type == HealingActionType.CIRCUIT_OPEN:
                result = await self._open_circuit(target)
            elif healing_type == HealingActionType.CIRCUIT_CLOSE:
                result = await self._close_circuit(target)
            elif healing_type == HealingActionType.RESTART_SERVICE:
                result = await self._restart_service(target)
            elif healing_type == HealingActionType.FAILOVER:
                result = await self._trigger_failover(target, parameters)
            elif healing_type == HealingActionType.RETRY_BACKLOG:
                result = await self._retry_backlog(target, parameters)
            elif healing_type == HealingActionType.ALERT_ONCALL:
                result = await self._alert_oncall(target, parameters)
            else:
                result = {"success": False, "error": f"Action {action_type} not implemented"}

            end_time = datetime.now(timezone.utc)
            duration_ms = (end_time - start_time).total_seconds() * 1000

            healing_result = HealingResult(
                action_id=action_id,
                action_type=healing_type,
                status=HealingStatus.COMPLETED if result.get("success") else HealingStatus.FAILED,
                target=target,
                started_at=start_time,
                completed_at=end_time,
                duration_ms=duration_ms,
                error_message=result.get("error"),
            )

            self._action_history.append(healing_result)

            return {
                "action_id": action_id,
                "action_type": action_type,
                "target": target,
                "status": healing_result.status.value,
                "duration_ms": duration_ms,
                **result,
            }

        except Exception as e:
            logger.error(f"[HEALER] Action failed: {e}")
            return {
                "action_id": action_id,
                "action_type": action_type,
                "target": target,
                "status": HealingStatus.FAILED.value,
                "error": str(e),
            }

    async def _clear_cache(self, target: str, parameters: dict[str, Any]) -> dict[str, Any]:
        """Clear cache for a target"""
        if not self._redis:
            return {"success": False, "error": "Redis not available"}

        pattern = parameters.get("pattern", f"snbg:{target}:*")
        keys = await self._redis.keys(pattern)

        if keys:
            await self._redis.delete(*keys)
            logger.info(f"[HEALER] Cleared {len(keys)} cache keys matching {pattern}")
            return {"success": True, "keys_cleared": len(keys), "pattern": pattern}

        return {"success": True, "keys_cleared": 0, "pattern": pattern}

    async def _apply_rate_limit(self, target: str, parameters: dict[str, Any]) -> dict[str, Any]:
        """Apply rate limiting to a target"""
        if not self._redis:
            return {"success": False, "error": "Redis not available"}

        limit = parameters.get("limit", 100)
        window_seconds = parameters.get("window_seconds", 60)

        key = f"snbg:ratelimit:{target}"
        await self._redis.set(key, limit, ex=window_seconds)

        logger.info(f"[HEALER] Applied rate limit {limit}/min to {target}")
        return {"success": True, "limit": limit, "window_seconds": window_seconds}

    async def _open_circuit(self, target: str) -> dict[str, Any]:
        """Open a circuit breaker"""
        # This would integrate with CircuitBreakerTools
        logger.info(f"[HEALER] Opening circuit for {target}")
        return {"success": True, "message": f"Circuit {target} opened"}

    async def _close_circuit(self, target: str) -> dict[str, Any]:
        """Close a circuit breaker"""
        logger.info(f"[HEALER] Closing circuit for {target}")
        return {"success": True, "message": f"Circuit {target} closed"}

    async def _restart_service(self, target: str) -> dict[str, Any]:
        """Restart a service (simulated - would integrate with container orchestration)"""
        logger.warning(f"[HEALER] Service restart requested for {target} - requires manual intervention")
        return {
            "success": False,
            "requires_approval": True,
            "message": f"Service restart for {target} requires human approval",
        }

    async def _trigger_failover(self, target: str, parameters: dict[str, Any]) -> dict[str, Any]:
        """Trigger failover to backup"""
        backup = parameters.get("backup_target")
        logger.warning(f"[HEALER] Failover requested: {target} -> {backup}")
        return {
            "success": False,
            "requires_approval": True,
            "message": f"Failover from {target} to {backup} requires human approval",
        }

    async def _retry_backlog(self, target: str, parameters: dict[str, Any]) -> dict[str, Any]:
        """Retry failed items from backlog/DLQ"""
        max_items = parameters.get("max_items", 100)
        logger.info(f"[HEALER] Retrying backlog for {target}, max {max_items} items")
        return {"success": True, "items_retried": 0, "message": "Backlog retry initiated"}

    async def _alert_oncall(self, target: str, parameters: dict[str, Any]) -> dict[str, Any]:
        """Alert on-call engineer"""
        severity = parameters.get("severity", "warning")
        message = parameters.get("message", f"Issue detected with {target}")
        logger.warning(f"[HEALER] [ONCALL ALERT] [{severity.upper()}] {message}")
        return {"success": True, "severity": severity, "message": message}

    def get_action_history(self, limit: int = 100) -> list[dict[str, Any]]:
        """Get history of healing actions"""
        return [
            {
                "action_id": r.action_id,
                "action_type": r.action_type.value,
                "target": r.target,
                "status": r.status.value,
                "duration_ms": r.duration_ms,
                "started_at": r.started_at.isoformat() if r.started_at else None,
                "error": r.error_message,
            }
            for r in self._action_history[-limit:]
        ]


# =============================================================================
# Healer Tools - Chaos Engineering
# =============================================================================

class ChaosTools:
    """Tools for chaos engineering experiments"""

    def __init__(self):
        """Initialize chaos tools"""
        self._experiments: list[ChaosExperimentResult] = []
        self._active_experiment: ChaosExperiment | None = None

    async def run_chaos_experiment(
        self,
        experiment_type: str,
        target: str,
        duration_seconds: int = 60,
        parameters: dict[str, Any] | None = None,
    ) -> dict[str, Any]:
        """Run a chaos engineering experiment"""
        try:
            exp_type = ChaosExperimentType(experiment_type)
        except ValueError:
            return {"error": f"Unknown experiment type: {experiment_type}"}

        experiment_id = str(uuid.uuid4())[:8]
        parameters = parameters or {}

        experiment = ChaosExperiment(
            experiment_id=experiment_id,
            experiment_type=exp_type,
            target=target,
            parameters=parameters,
            duration_seconds=duration_seconds,
        )

        self._active_experiment = experiment

        logger.warning(f"[CHAOS] Starting experiment {experiment_id}: {experiment_type} on {target}")

        start_time = datetime.now(timezone.utc)

        try:
            # Execute experiment based on type
            if exp_type == ChaosExperimentType.LATENCY_INJECTION:
                await self._inject_latency(target, parameters, duration_seconds)
            elif exp_type == ChaosExperimentType.ERROR_INJECTION:
                await self._inject_errors(target, parameters, duration_seconds)
            elif exp_type == ChaosExperimentType.RESOURCE_STRESS:
                await self._stress_resources(target, parameters, duration_seconds)
            else:
                logger.info(f"[CHAOS] Experiment type {experiment_type} simulated")

            end_time = datetime.now(timezone.utc)

            result = ChaosExperimentResult(
                experiment_id=experiment_id,
                experiment_type=exp_type,
                target=target,
                success=True,
                healing_triggered=False,
                started_at=start_time,
                ended_at=end_time,
                observations=[f"Experiment completed in {(end_time - start_time).total_seconds():.1f}s"],
            )

            self._experiments.append(result)
            self._active_experiment = None

            return {
                "experiment_id": experiment_id,
                "experiment_type": experiment_type,
                "target": target,
                "success": True,
                "duration_seconds": (end_time - start_time).total_seconds(),
                "observations": result.observations,
            }

        except Exception as e:
            logger.error(f"[CHAOS] Experiment failed: {e}")
            self._active_experiment = None
            return {
                "experiment_id": experiment_id,
                "experiment_type": experiment_type,
                "target": target,
                "success": False,
                "error": str(e),
            }

    async def _inject_latency(self, target: str, parameters: dict[str, Any], duration: int) -> None:
        """Inject latency into a target"""
        latency_ms = parameters.get("latency_ms", 1000)
        logger.info(f"[CHAOS] Injecting {latency_ms}ms latency into {target} for {duration}s")
        # In a real implementation, this would configure a proxy or middleware
        await asyncio.sleep(min(duration, 5))  # Simulate for max 5 seconds

    async def _inject_errors(self, target: str, parameters: dict[str, Any], duration: int) -> None:
        """Inject errors into a target"""
        error_rate = parameters.get("error_rate", 0.5)
        logger.info(f"[CHAOS] Injecting {error_rate*100}% error rate into {target} for {duration}s")
        await asyncio.sleep(min(duration, 5))

    async def _stress_resources(self, target: str, parameters: dict[str, Any], duration: int) -> None:
        """Stress test resources"""
        cpu_percent = parameters.get("cpu_percent", 80)
        memory_mb = parameters.get("memory_mb", 512)
        logger.info(f"[CHAOS] Stressing {target}: {cpu_percent}% CPU, {memory_mb}MB memory for {duration}s")
        await asyncio.sleep(min(duration, 5))

    def stop_experiment(self) -> dict[str, Any]:
        """Stop active chaos experiment"""
        if not self._active_experiment:
            return {"success": False, "message": "No active experiment"}

        experiment_id = self._active_experiment.experiment_id
        self._active_experiment = None

        logger.info(f"[CHAOS] Experiment {experiment_id} stopped")
        return {"success": True, "experiment_id": experiment_id, "message": "Experiment stopped"}

    def get_experiment_history(self, limit: int = 20) -> list[dict[str, Any]]:
        """Get history of chaos experiments"""
        return [
            {
                "experiment_id": r.experiment_id,
                "experiment_type": r.experiment_type.value,
                "target": r.target,
                "success": r.success,
                "healing_triggered": r.healing_triggered,
                "started_at": r.started_at.isoformat() if r.started_at else None,
                "ended_at": r.ended_at.isoformat() if r.ended_at else None,
            }
            for r in self._experiments[-limit:]
        ]


# =============================================================================
# Tool Definitions for Agent SDK
# =============================================================================

HEALER_TOOLS = [
    # Circuit Breaker Tools
    {
        "name": "list_circuits",
        "description": "List all circuit breakers and their states (CLOSED, OPEN, HALF_OPEN)",
        "input_schema": {
            "type": "object",
            "properties": {},
            "required": [],
        },
    },
    {
        "name": "list_open_circuits",
        "description": "List all open (tripped) circuit breakers that are blocking requests",
        "input_schema": {
            "type": "object",
            "properties": {},
            "required": [],
        },
    },
    {
        "name": "get_circuit_state",
        "description": "Get detailed state of a specific circuit breaker",
        "input_schema": {
            "type": "object",
            "properties": {
                "name": {
                    "type": "string",
                    "description": "Name of the circuit breaker",
                },
            },
            "required": ["name"],
        },
    },
    {
        "name": "trip_circuit",
        "description": "Manually trip a circuit breaker to block requests",
        "input_schema": {
            "type": "object",
            "properties": {
                "name": {
                    "type": "string",
                    "description": "Name of the circuit breaker",
                },
                "reason": {
                    "type": "string",
                    "enum": ["error_rate", "timeout_rate", "latency_spike", "manual", "dependency_failure"],
                    "description": "Reason for tripping the circuit",
                },
            },
            "required": ["name"],
        },
    },
    {
        "name": "reset_circuit",
        "description": "Reset a circuit breaker to CLOSED state",
        "input_schema": {
            "type": "object",
            "properties": {
                "name": {
                    "type": "string",
                    "description": "Name of the circuit breaker",
                },
            },
            "required": ["name"],
        },
    },
    # Anomaly Detection Tools
    {
        "name": "detect_anomalies",
        "description": "Run anomaly detection on all monitored metrics",
        "input_schema": {
            "type": "object",
            "properties": {},
            "required": [],
        },
    },
    {
        "name": "add_metric",
        "description": "Add a metric to monitor for anomalies",
        "input_schema": {
            "type": "object",
            "properties": {
                "metric_name": {
                    "type": "string",
                    "description": "Name of the metric to monitor",
                },
                "detection_method": {
                    "type": "string",
                    "enum": ["zscore", "iqr", "mad", "ewma", "threshold"],
                    "description": "Detection method to use",
                },
                "sensitivity": {
                    "type": "number",
                    "description": "Sensitivity threshold (default 3.0)",
                },
            },
            "required": ["metric_name"],
        },
    },
    # Healing Action Tools
    {
        "name": "execute_healing",
        "description": "Execute a self-healing action. Actions: cache_clear, rate_limit, circuit_open, circuit_close, retry_backlog, alert_oncall. Critical actions (restart_service, failover) require approval.",
        "input_schema": {
            "type": "object",
            "properties": {
                "action_type": {
                    "type": "string",
                    "enum": ["cache_clear", "rate_limit", "circuit_open", "circuit_close", "restart_service", "failover", "retry_backlog", "alert_oncall"],
                    "description": "Type of healing action",
                },
                "target": {
                    "type": "string",
                    "description": "Target service or component",
                },
                "parameters": {
                    "type": "object",
                    "description": "Action-specific parameters",
                },
            },
            "required": ["action_type", "target"],
        },
    },
    {
        "name": "get_healing_history",
        "description": "Get history of executed healing actions",
        "input_schema": {
            "type": "object",
            "properties": {
                "limit": {
                    "type": "integer",
                    "description": "Maximum number of actions to return (default 100)",
                },
            },
            "required": [],
        },
    },
    # Chaos Engineering Tools
    {
        "name": "run_chaos_experiment",
        "description": "Run a chaos engineering experiment to test system resilience. Use with caution!",
        "input_schema": {
            "type": "object",
            "properties": {
                "experiment_type": {
                    "type": "string",
                    "enum": ["latency_injection", "error_injection", "resource_stress"],
                    "description": "Type of chaos experiment",
                },
                "target": {
                    "type": "string",
                    "description": "Target service or component",
                },
                "duration_seconds": {
                    "type": "integer",
                    "description": "Duration of the experiment (default 60)",
                },
                "parameters": {
                    "type": "object",
                    "description": "Experiment-specific parameters",
                },
            },
            "required": ["experiment_type", "target"],
        },
    },
    {
        "name": "stop_chaos_experiment",
        "description": "Stop the currently running chaos experiment",
        "input_schema": {
            "type": "object",
            "properties": {},
            "required": [],
        },
    },
]
