"""Tests for shared patch helpers."""

from unittest.mock import patch

from caliper._features import features
from caliper._patch_helpers import merge_metadata, pop_caliper_metadata, push_record

# ---------------------------------------------------------------------------
# pop_caliper_metadata
# ---------------------------------------------------------------------------


def test_pop_caliper_metadata_removes_key():
    kwargs = {"model": "test", "caliper_metadata": {"user": "123"}}
    meta = pop_caliper_metadata(kwargs)
    assert meta == {"user": "123"}
    assert "caliper_metadata" not in kwargs


def test_pop_caliper_metadata_absent():
    kwargs = {"model": "test"}
    meta = pop_caliper_metadata(kwargs)
    assert meta == {}


def test_pop_caliper_metadata_coerces_values():
    kwargs = {"caliper_metadata": {"count": 42, "active": True}}
    meta = pop_caliper_metadata(kwargs)
    assert meta == {"count": "42", "active": "True"}


# ---------------------------------------------------------------------------
# merge_metadata
# ---------------------------------------------------------------------------


def test_merge_metadata_per_request_wins():
    with features(user_id="ctx"):
        merged = merge_metadata({"user_id": "req"})
        assert merged["user_id"] == "req"


def test_merge_metadata_combines_both():
    with features(feature="chat"):
        merged = merge_metadata({"campaign": "q4"})
        assert merged == {"feature": "chat", "campaign": "q4"}


def test_merge_metadata_empty():
    merged = merge_metadata({})
    assert merged == {}


# ---------------------------------------------------------------------------
# push_record
# ---------------------------------------------------------------------------


def test_push_record_noop_when_no_buffer():
    """push_record silently does nothing when the buffer is None."""
    with patch("caliper._get_buffer", return_value=None):
        push_record(None)  # type: ignore[arg-type]
