"""
Unit tests for Observability Layer

Tests metrics, structured logging, and tracing.
"""

import pytest
import json
import os
from altrus.core.observability.structured_logging import get_logger, configure_logging
from altrus.core.observability.tracing import get_tracer, trace_span

def test_structured_logging(tmp_path):
    log_file = tmp_path / "test.log"
    configure_logging(log_file=str(log_file), level="INFO")
    logger = get_logger()

    logger.info("Test message", extra_key="extra_value")

    # Verify file content
    with open(log_file, "r") as f:
        line = f.readline()
        data = json.loads(line)
        assert data["message"] == "Test message"
        assert data["extra_key"] == "extra_value"
        assert "timestamp" in data
        assert data["level"] == "INFO"

def test_tracing():
    tracer = get_tracer("test_service")

    with trace_span("test_operation", op_type="unit_test") as span:
        span.add_event("event_1")
        assert span.name == "test_operation"
        assert span.attributes["op_type"] == "unit_test"

    spans = tracer.get_spans()
    assert len(spans) > 0
    last_span = spans[-1]
    assert last_span.name == "test_operation"
    assert last_span.status == "OK"
    assert len(last_span.events) == 1

def test_tracing_exception():
    tracer = get_tracer("test_service")

    try:
        with trace_span("failing_op"):
            raise ValueError("intentional error")
    except ValueError:
        pass

    spans = tracer.get_spans()
    fail_span = [s for s in spans if s.name == "failing_op"][-1]
    assert fail_span.status == "ERROR"
    assert "exception" in [e["name"] for e in fail_span.events]
