from __future__ import annotations

import time

from pillar._signature import _generate_signature, verify_webhook_signature


SECRET = "whsec_test_secret_key"
BODY = b'{"action":"tool_call","tool_name":"lookup_customer"}'


class TestVerifyWebhookSignature:
    def test_valid_signature(self) -> None:
        sig = _generate_signature(BODY, SECRET)
        assert verify_webhook_signature(sig, BODY, SECRET)

    def test_invalid_secret_rejected(self) -> None:
        sig = _generate_signature(BODY, SECRET)
        assert not verify_webhook_signature(sig, BODY, "wrong_secret")

    def test_tampered_body_rejected(self) -> None:
        sig = _generate_signature(BODY, SECRET)
        assert not verify_webhook_signature(sig, b"tampered", SECRET)

    def test_expired_timestamp_rejected(self) -> None:
        old_ts = int(time.time()) - 600
        sig = _generate_signature(BODY, SECRET, timestamp=old_ts)
        assert not verify_webhook_signature(sig, BODY, SECRET, tolerance_seconds=300)

    def test_custom_tolerance(self) -> None:
        old_ts = int(time.time()) - 400
        sig = _generate_signature(BODY, SECRET, timestamp=old_ts)
        assert not verify_webhook_signature(sig, BODY, SECRET, tolerance_seconds=300)
        assert verify_webhook_signature(sig, BODY, SECRET, tolerance_seconds=500)

    def test_missing_timestamp_rejected(self) -> None:
        assert not verify_webhook_signature("v1=abc123", BODY, SECRET)

    def test_missing_signature_rejected(self) -> None:
        assert not verify_webhook_signature("t=1234567890", BODY, SECRET)

    def test_empty_header_rejected(self) -> None:
        assert not verify_webhook_signature("", BODY, SECRET)

    def test_non_integer_timestamp_rejected(self) -> None:
        assert not verify_webhook_signature("t=notanumber,v1=abc", BODY, SECRET)

    def test_string_body_accepted(self) -> None:
        body_str = BODY.decode()
        sig = _generate_signature(BODY, SECRET)
        assert verify_webhook_signature(sig, body_str, SECRET)

    def test_generate_and_verify_roundtrip(self) -> None:
        """Ensure _generate_signature and verify_webhook_signature are compatible."""
        bodies = [b"", b"hello", b'{"key": "value"}', b"\x00\x01\x02"]
        for body in bodies:
            sig = _generate_signature(body, SECRET)
            assert verify_webhook_signature(sig, body, SECRET), f"Failed for body={body!r}"
