"""Security tests — repr redaction and error message sanitization."""

import pytest

from sense_memory.store import MemoryStore


class FakeIdentity:
    """Minimal identity stub with secret fields for testing redaction."""
    public_key_hex = "ab" * 32
    private_key_hex = "cd" * 32
    nsec = "nsec1fakesecretkeythatmustnotappearinrepr000000000000000000"


# ---------------------------------------------------------------------------
# __repr__ redaction — MemoryStore must never expose identity secrets
# ---------------------------------------------------------------------------

def test_memorystore_repr_does_not_contain_nsec():
    """MemoryStore repr must not leak the nsec."""
    identity = FakeIdentity()
    store = MemoryStore(identity, "wss://relay.example.com")
    r = repr(store)
    assert "nsec1" not in r
    assert identity.nsec not in r


def test_memorystore_repr_does_not_contain_private_key():
    """MemoryStore repr must not leak the private key hex."""
    identity = FakeIdentity()
    store = MemoryStore(identity, "wss://relay.example.com")
    r = repr(store)
    assert identity.private_key_hex not in r


def test_memorystore_repr_shows_truncated_pubkey():
    """MemoryStore repr should show a truncated pubkey for identification."""
    identity = FakeIdentity()
    store = MemoryStore(identity, "wss://relay.example.com")
    r = repr(store)
    assert "MemoryStore(" in r
    assert identity.public_key_hex[:8] in r
    assert "..." in r


def test_memorystore_repr_shows_relay_url():
    """MemoryStore repr should include the relay URL (not secret)."""
    identity = FakeIdentity()
    store = MemoryStore(identity, "wss://relay.example.com")
    r = repr(store)
    assert "wss://relay.example.com" in r


def test_memorystore_str_does_not_contain_nsec():
    """str(store) must also be safe — falls through to __repr__."""
    identity = FakeIdentity()
    store = MemoryStore(identity, "wss://relay.example.com")
    s = str(store)
    assert "nsec1" not in s
    assert identity.private_key_hex not in s


def test_memorystore_repr_in_format_string():
    """Embedding in f-strings or format() must not leak secrets."""
    identity = FakeIdentity()
    store = MemoryStore(identity, "wss://relay.example.com")
    msg = f"Store is {store!r}"
    assert identity.private_key_hex not in msg
    assert identity.nsec not in msg


# ---------------------------------------------------------------------------
# Error message sanitization — errors must not leak secret values
# ---------------------------------------------------------------------------

def test_empty_relay_error_does_not_leak_identity():
    """ValueError for empty relay should not include identity details."""
    identity = FakeIdentity()
    with pytest.raises(ValueError, match="non-empty") as exc_info:
        MemoryStore(identity, "")
    assert identity.private_key_hex not in str(exc_info.value)
    assert identity.nsec not in str(exc_info.value)
