"""Tests for `_prepare_tags` / `_p_target` — the NIP-01 tag flattener.

`_prepare_tags` is deliberately dumb: it produces one uniform dict per tag
(`idx`, `name`, `elements`) with NO reference typing, NO `a`-coordinate
parsing, and NO `r`-relay normalization. Those concerns moved to the point
of use (the NIP-65 handler, the `addressables` view, callers reading
`elements[1]`). These tests pin that uniformity down.
"""

from ingest import _p_target, _prepare_tags


def test_basic_e_p_tags_are_uniform():
    tags = [["e", "ev" + "0" * 62], ["p", "pk" + "0" * 62]]
    out = _prepare_tags(tags)
    assert len(out) == 2
    assert out[0] == {"idx": 0, "name": "e", "elements": ["e", "ev" + "0" * 62]}
    assert out[1]["name"] == "p"
    assert out[1]["elements"] == ["p", "pk" + "0" * 62]


def test_non_reference_tag_is_kept_unchanged():
    out = _prepare_tags([["t", "bitcoin"]])
    assert out == [{"idx": 0, "name": "t", "elements": ["t", "bitcoin"]}]


def test_a_tag_is_not_parsed_here():
    # The coordinate stays a single verbatim element — splitting happens in
    # the `addressables` view, not at prepare time.
    out = _prepare_tags([["a", "30023:abcd:slug"]])
    assert out[0]["name"] == "a"
    assert out[0]["elements"] == ["a", "30023:abcd:slug"]


def test_r_tag_is_not_normalized_here():
    # No kind-dependent special-casing: `r` is just a tag like any other,
    # whatever the event kind. Relay normalization lives in the NIP-65 path.
    out = _prepare_tags([["r", "wss://relay.example/"]])
    assert out[0]["name"] == "r"
    assert out[0]["elements"] == ["r", "wss://relay.example/"]


def test_multi_element_tag_keeps_all_elements():
    out = _prepare_tags([["p", "pk" + "0" * 62, "wss://hint", "host"]])
    assert out[0]["elements"] == ["p", "pk" + "0" * 62, "wss://hint", "host"]


def test_skips_non_list_and_empty_tags():
    out = _prepare_tags(["not-a-list", [], ["p", "pk" + "0" * 62]])
    assert len(out) == 1
    assert out[0]["name"] == "p"
    # `idx` reflects original position, not output position — important for
    # event_tags row-key stability across re-ingest.
    assert out[0]["idx"] == 2


def test_non_string_elements_are_stringified():
    out = _prepare_tags([["t", 42]])
    assert out[0]["elements"] == ["t", "42"]


def test_p_target_returns_primary_value():
    out = _prepare_tags([["p", "deadbeef", "wss://hint"]])
    assert _p_target(out[0]) == "deadbeef"


def test_p_target_is_none_for_valueless_tag():
    out = _prepare_tags([["p"]])
    assert _p_target(out[0]) is None
