import json
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
DASHBOARD_PATH = ROOT / "docker/grafana/provisioning/dashboards/json/ai-automation-overview.json"


def _panel_targets(dashboard: dict):
    for panel in dashboard.get("panels", []):
        yield from panel.get("targets", [])


def test_ai_automation_grafana_dashboard_is_valid_json():
    dashboard = json.loads(DASHBOARD_PATH.read_text(encoding="utf-8"))

    assert dashboard["uid"] == "momo-ai-automation-overview"
    assert dashboard["title"] == "MOMO AI Automation Overview"
    assert "ai-automation" in dashboard["tags"]
    assert dashboard["timezone"] == "Asia/Taipei"


def test_ai_automation_grafana_dashboard_tracks_required_metrics():
    dashboard = json.loads(DASHBOARD_PATH.read_text(encoding="utf-8"))
    expressions = "\n".join(
        target["expr"]
        for target in _panel_targets(dashboard)
        if target.get("expr")
    )

    for metric in [
        "momo_ai_event_router_dispatch_total",
        "momo_ai_event_router_latency_ms_count",
        "momo_ai_event_router_latency_ms_sum",
        "momo_ai_event_router_latency_ms_max",
        "momo_ai_event_router_safe_action_total",
        "momo_ai_event_router_replay_total",
        "momo_ai_autoheal_action_total",
        "momo_ai_autoheal_duration_ms_count",
        "momo_ai_autoheal_duration_ms_sum",
        "momo_ai_autoheal_duration_ms_max",
    ]:
        assert metric in expressions


def test_ai_automation_grafana_dashboard_uses_prometheus_datasource():
    dashboard = json.loads(DASHBOARD_PATH.read_text(encoding="utf-8"))

    metric_panels = [
        panel
        for panel in dashboard["panels"]
        if panel.get("targets")
    ]

    assert metric_panels
    assert all(
        panel.get("datasource", {}).get("uid") == "prometheus"
        for panel in metric_panels
    )
