"""Tests for neonlink.record."""

from datetime import datetime, timezone

from neonlink.record import (
    HEADER_CORRELATION_ID,
    HEADER_MESSAGE_ID,
    HEADER_MESSAGE_TYPE,
    HEADER_RETRY_COUNT,
    HEADER_TRACEPARENT,
    HEADER_TRACESTATE,
    Record,
)


class TestRecord:
    def test_get_header_empty(self):
        rec = Record(topic="t")
        assert rec.get_header("missing") == ""

    def test_set_and_get_header(self):
        rec = Record(topic="t")
        rec.set_header(HEADER_MESSAGE_TYPE, "MESSAGE_TYPE_TEST")
        assert rec.message_type == "MESSAGE_TYPE_TEST"

    def test_properties(self):
        rec = Record(
            topic="test-topic",
            key=b"key-1",
            value=b"value-1",
            headers={
                HEADER_MESSAGE_TYPE: "MESSAGE_TYPE_ETL_COMPLETION",
                HEADER_CORRELATION_ID: "corr-123",
                HEADER_MESSAGE_ID: "msg-456",
            },
        )
        assert rec.message_type == "MESSAGE_TYPE_ETL_COMPLETION"
        assert rec.correlation_id == "corr-123"
        assert rec.message_id == "msg-456"

    def test_timestamp_default_none(self):
        rec = Record(topic="t")
        assert rec.timestamp is None

    def test_timestamp_set(self):
        ts = datetime(2026, 3, 1, 12, 0, 0, tzinfo=timezone.utc)
        rec = Record(topic="t", timestamp=ts)
        assert rec.timestamp == ts
        assert rec.timestamp.tzinfo == timezone.utc


class TestPoisonAndRetry:
    def test_poison_pill(self):
        from neonlink.poison import is_poison_pill, get_retry_count, increment_retry_count

        rec = Record(topic="t")
        assert not is_poison_pill(rec, 5)
        assert get_retry_count(rec) == 0

        rec.set_header(HEADER_RETRY_COUNT, "3")
        assert not is_poison_pill(rec, 5)
        assert get_retry_count(rec) == 3

        rec.set_header(HEADER_RETRY_COUNT, "4")
        count = increment_retry_count(rec)
        assert count == 5
        assert is_poison_pill(rec, 5)
        assert get_retry_count(rec) == 5

    def test_invalid_retry_count(self):
        from neonlink.poison import get_retry_count

        rec = Record(topic="t", headers={HEADER_RETRY_COUNT: "invalid"})
        assert get_retry_count(rec) == 0


class TestTracing:
    def test_inject_extract_noop_without_otel(self):
        from neonlink.tracing import inject_trace_context, extract_trace_context

        rec = Record(topic="t")
        inject_trace_context(rec)  # Should not raise
        ctx = extract_trace_context(rec)
        # May return None if OTel not installed, or a context if it is.

    def test_manual_headers(self):
        rec = Record(topic="t")
        rec.set_header(HEADER_TRACEPARENT, "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01")
        rec.set_header(HEADER_TRACESTATE, "rojo=00f067aa0ba902b7")
        assert rec.get_header(HEADER_TRACEPARENT) != ""
        assert rec.get_header(HEADER_TRACESTATE) != ""
