"""
Tests for insaits/structured_logging.py - JSON structured logger
"""

import json
import logging
import pytest
from insa_its.structured_logging import StructuredLogger


class TestStructuredLogger:
    def test_log_returns_payload(self):
        slog = StructuredLogger()
        payload = slog._log(logging.INFO, "test.event", key="value")
        assert payload["event"] == "test.event"
        assert payload["key"] == "value"
        assert "ts" in payload

    def test_log_with_correlation_id(self):
        slog = StructuredLogger()
        payload = slog._log(
            logging.INFO, "test.event", correlation_id="corr-123"
        )
        assert payload["correlation_id"] == "corr-123"

    def test_log_without_correlation_id(self):
        slog = StructuredLogger()
        payload = slog._log(logging.INFO, "test.event")
        assert "correlation_id" not in payload

    def test_payload_is_valid_json(self):
        slog = StructuredLogger()
        payload = slog._log(
            logging.INFO, "test.event",
            correlation_id="c1", data={"nested": True},
        )
        # Should be JSON-serializable
        serialized = json.dumps(payload)
        parsed = json.loads(serialized)
        assert parsed["event"] == "test.event"


class TestAnomalyDetected:
    def test_basic_anomaly_log(self):
        slog = StructuredLogger()
        payload = slog.anomaly_detected(
            "SEMANTIC_DRIFT", "high", "agent1", "agent2"
        )
        assert payload["event"] == "anomaly.detected"
        assert payload["anomaly_type"] == "SEMANTIC_DRIFT"
        assert payload["severity"] == "high"
        assert payload["sender"] == "agent1"
        assert payload["receiver"] == "agent2"

    def test_anomaly_with_correlation(self):
        slog = StructuredLogger()
        payload = slog.anomaly_detected(
            "TEST", "low", "a1", "a2", correlation_id="corr-456"
        )
        assert payload["correlation_id"] == "corr-456"

    def test_anomaly_with_extra_kwargs(self):
        slog = StructuredLogger()
        payload = slog.anomaly_detected(
            "TEST", "medium", "a1", "a2",
            score=0.85, threshold=0.7,
        )
        assert payload["score"] == 0.85
        assert payload["threshold"] == 0.7


class TestMessageClean:
    def test_clean_message_log(self):
        slog = StructuredLogger()
        payload = slog.message_clean("agent1", "agent2")
        assert payload["event"] == "message.clean"
        assert payload["sender"] == "agent1"

    def test_clean_with_correlation(self):
        slog = StructuredLogger()
        payload = slog.message_clean("a1", "a2", "corr-789")
        assert payload["correlation_id"] == "corr-789"


class TestReadinessCheck:
    def test_readiness_log(self):
        slog = StructuredLogger()
        checks = {
            "license": {"status": "ok"},
            "embeddings": {"status": "warn"},
        }
        payload = slog.readiness_check(True, checks)
        assert payload["event"] == "readiness.check"
        assert payload["ready"] is True
        assert payload["summary"]["license"] == "ok"

    def test_readiness_failed(self):
        slog = StructuredLogger()
        checks = {"engine": {"status": "fail"}}
        payload = slog.readiness_check(False, checks)
        assert payload["ready"] is False


class TestCircuitBreakerLog:
    def test_circuit_breaker_tripped(self):
        slog = StructuredLogger()
        payload = slog.circuit_breaker_tripped("agent1", 0.65)
        assert payload["event"] == "circuit_breaker.open"
        assert payload["agent_id"] == "agent1"
        assert payload["anomaly_rate"] == 0.65


class TestInterventionLog:
    def test_intervention_triggered(self):
        slog = StructuredLogger()
        payload = slog.intervention_triggered(
            "quarantined", "agent1", "critical"
        )
        assert payload["event"] == "intervention.triggered"
        assert payload["action"] == "quarantined"
        assert payload["severity"] == "critical"
