import unittest

from fgai.logs import parse_log_line
from fgai.replay import replay_comparison, replay_events
from fgai.stream_profiles import parse_profiles


class ReplayTests(unittest.TestCase):
    def test_replay_uses_temporary_profile_baseline(self):
        profiles = parse_profiles([{"stream_id": "windows", "entity_field": "username", "categorical_fields": ["action"]}])
        events = [
            parse_log_line(f"timestamp={1_700_000_000 + index * 300} username=alice action=failed event={index}")
            for index in range(12)
        ]
        events.extend(
            parse_log_line(f"timestamp={1_700_003_600} username=alice action=failed burst={index}")
            for index in range(5)
        )
        result = replay_events(events, profiles, stream_id="windows")
        self.assertEqual(result["events"], 17)
        self.assertGreaterEqual(result["field_detector_counts"].get("auth_failure_burst", 0), 1)

    def test_replay_comparison_reports_detector_deltas(self):
        result = replay_comparison(
            {"events": 10, "field_findings": [{"a": 1}], "source_anomalies": [], "field_detector_counts": {"auth_failure_burst": 2}},
            {"events": 10, "field_findings": [{"a": 1}, {"a": 2}], "source_anomalies": [{"a": 1}], "field_detector_counts": {"auth_failure_burst": 1, "rare_value": 3}},
        )
        self.assertEqual(result["field_findings_delta"], 1)
        self.assertEqual(result["source_anomalies_delta"], 1)
        self.assertEqual(result["detector_count_delta"]["auth_failure_burst"], -1)
        self.assertEqual(result["detector_count_delta"]["rare_value"], 3)
