"""Tests for sre_beacon.analyzers.alert_analyzer."""

import pytest

from sre_beacon.analyzers.alert_analyzer import (
    analyze_alert_rules,
    load_alert_rules,
)
from sre_beacon.models import AlertIssueSeverity, AlertRule


class TestLoadAlertRules:
    def test_load_from_yaml(self, demo_dir):
        rules = load_alert_rules(demo_dir["alerts"])
        assert len(rules) == 9
        assert rules[0].name == "HighErrorRate"

    def test_skips_recording_rules(self, tmp_yaml):
        data = {
            "groups": [{
                "name": "test",
                "rules": [
                    {"record": "job:requests:rate5m", "expr": "rate(requests[5m])"},
                    {"alert": "TestAlert", "expr": "up == 0"},
                ],
            }]
        }
        path = tmp_yaml(data, "rules.yaml")
        rules = load_alert_rules(path)
        assert len(rules) == 1
        assert rules[0].name == "TestAlert"


class TestAnalyzeAlertRules:
    def test_good_rules_fewer_issues(self, good_alert_rules):
        report = analyze_alert_rules(good_alert_rules)
        assert report.total_rules == 1
        assert report.critical_count == 0
        assert report.high_count == 0

    def test_bad_rules_many_issues(self, bad_alert_rules):
        report = analyze_alert_rules(bad_alert_rules)
        assert report.total_rules == 6
        assert report.critical_count >= 1  # BrokenAlert empty expr
        assert report.high_count >= 1      # Missing severity, runbook, etc.
        assert len(report.issues) > 10

    def test_empty_expression_critical(self):
        rules = [AlertRule(name="Bad", expr="", labels={"severity": "critical"},
                          annotations={}, group="g")]
        report = analyze_alert_rules(rules)
        critical_issues = [i for i in report.issues if i.severity == AlertIssueSeverity.CRITICAL]
        assert len(critical_issues) >= 1

    def test_no_severity_label(self):
        rules = [AlertRule(name="NoSev", expr="up == 0", labels={}, annotations={}, group="g")]
        report = analyze_alert_rules(rules)
        assert report.rules_without_severity == 1

    def test_no_for_duration(self):
        rules = [AlertRule(name="NoFor", expr="up == 0", for_duration="",
                          labels={"severity": "warning"}, annotations={}, group="g")]
        report = analyze_alert_rules(rules)
        assert report.rules_without_for == 1

    def test_no_runbook(self):
        rules = [AlertRule(name="NoRunbook", expr="up == 0", for_duration="5m",
                          labels={"severity": "warning"}, annotations={"summary": "down"}, group="g")]
        report = analyze_alert_rules(rules)
        assert report.rules_without_runbook == 1

    def test_duplicate_names(self):
        rules = [
            AlertRule(name="Dup", expr="a > 1", for_duration="5m",
                     labels={"severity": "warning"}, annotations={}, group="g"),
            AlertRule(name="Dup", expr="b > 1", for_duration="5m",
                     labels={"severity": "warning"}, annotations={}, group="g"),
        ]
        report = analyze_alert_rules(rules)
        assert "Dup" in report.duplicate_names

    def test_critical_excessive_for(self):
        rules = [AlertRule(name="SlowCrit", expr="x > 1", for_duration="30m",
                          severity="critical",
                          labels={"severity": "critical", "team": "sre"},
                          annotations={"summary": "s", "description": "d",
                                      "runbook_url": "https://r.co",
                                      "dashboard_url": "https://d.co"},
                          group="g")]
        report = analyze_alert_rules(rules)
        rule_ids = [i.rule_id for i in report.issues]
        assert "SRE-ALT-005" in rule_ids

    def test_warning_page_action(self):
        rules = [AlertRule(name="WarnPage", expr="x > 1", for_duration="5m",
                          severity="warning",
                          labels={"severity": "warning", "action": "page", "team": "t"},
                          annotations={"summary": "s", "description": "d",
                                      "runbook_url": "u", "dashboard_url": "d"},
                          group="g")]
        report = analyze_alert_rules(rules)
        rule_ids = [i.rule_id for i in report.issues]
        assert "SRE-ALT-011" in rule_ids

    def test_score_and_grade(self, good_alert_rules):
        report = analyze_alert_rules(good_alert_rules)
        assert report.score >= 0
        assert report.grade in ("A+", "A", "B", "C", "D", "F")
