import json
from pathlib import Path
from typing import Any, Dict, List


def _compare(value: float, operator: str, threshold: float) -> bool:
    if operator == ">":
        return value > threshold
    if operator == ">=":
        return value >= threshold
    if operator == "<":
        return value < threshold
    if operator == "<=":
        return value <= threshold
    if operator == "==":
        return value == threshold
    return False


def evaluate_incidents(runbook_path: Path, metrics: Dict[str, Any]) -> List[Dict[str, Any]]:
    runbook = json.loads(runbook_path.read_text(encoding="utf-8"))
    hits: List[Dict[str, Any]] = []
    for detector in runbook.get("detectors", []):
        metric_name = detector.get("metric")
        operator = detector.get("operator")
        threshold = float(detector.get("threshold", 0))
        value = float(metrics.get(metric_name, 0))
        if _compare(value, operator, threshold):
            hits.append(
                {
                    "detector_id": detector.get("id"),
                    "severity": detector.get("severity"),
                    "metric": metric_name,
                    "value": value,
                    "threshold": threshold,
                }
            )
    return hits


def resolve_auto_actions(runbook_path: Path, detector_id: str) -> List[str]:
    runbook = json.loads(runbook_path.read_text(encoding="utf-8"))
    for action in runbook.get("auto_actions", []):
        if action.get("on") == detector_id:
            return list(action.get("steps", []))
    return []
