"""Tests for sre_beacon.calculators.incident_calculator."""

from datetime import datetime, timedelta

import pytest

from sre_beacon.calculators.incident_calculator import (
    calculate_incident_metrics,
    load_incidents,
)
from sre_beacon.models import Incident, IncidentSeverity


class TestLoadIncidents:
    def test_load_from_yaml(self, demo_dir):
        incidents = load_incidents(demo_dir["incidents"])
        assert len(incidents) == 8
        assert incidents[0].severity == IncidentSeverity.P1


class TestCalculateIncidentMetrics:
    def test_basic_metrics(self, sample_incidents):
        metrics = calculate_incident_metrics(sample_incidents)
        assert metrics.total_incidents == 3
        assert metrics.p1_p2_count == 2
        assert metrics.mttr is not None
        assert metrics.mtta is not None

    def test_mttr_calculation(self, sample_incidents):
        metrics = calculate_incident_metrics(sample_incidents)
        # INC-001: 45m, INC-002: 60m, INC-003: 30m → avg 45m
        assert abs(metrics.mttr.total_seconds() - 45 * 60) < 1

    def test_mtta_calculation(self, sample_incidents):
        metrics = calculate_incident_metrics(sample_incidents)
        # INC-001: 5m, INC-002: 10m, INC-003: 20m → avg ~11.67m
        expected_seconds = (5 + 10 + 20) * 60 / 3
        assert abs(metrics.mtta.total_seconds() - expected_seconds) < 1

    def test_by_severity(self, sample_incidents):
        metrics = calculate_incident_metrics(sample_incidents)
        assert "P1" in metrics.by_severity
        assert "P2" in metrics.by_severity
        assert metrics.by_severity["P1"]["count"] == 1

    def test_by_service(self, sample_incidents):
        metrics = calculate_incident_metrics(sample_incidents)
        assert "api" in metrics.by_service
        assert metrics.by_service["api"]["count"] == 2

    def test_action_items_percentage(self, sample_incidents):
        metrics = calculate_incident_metrics(sample_incidents)
        # 2 out of 3 have action items → 66.7%
        assert abs(metrics.incidents_with_action_items_pct - 66.7) < 0.1

    def test_empty_incidents(self):
        metrics = calculate_incident_metrics([])
        assert metrics.total_incidents == 0
        assert metrics.mttr is None
        assert metrics.mtbf is None

    def test_mtbf_calculation(self, sample_incidents):
        metrics = calculate_incident_metrics(sample_incidents)
        assert metrics.mtbf is not None
        # Gap between INC-001 resolved (45m after) and INC-002 detected (5 days)
        # and between INC-002 resolved and INC-003 detected (5 more days)
        assert metrics.mtbf.total_seconds() > 0
