"""Tests for mesh PSK authentication."""

from __future__ import annotations

import time

from radix_edge.mesh.security import (
    mesh_key_hash,
    mesh_key_prefix,
    sign_request,
    verify_request,
)


class TestMeshKeyHash:
    def test_deterministic(self):
        h1 = mesh_key_hash("my-secret-key")
        h2 = mesh_key_hash("my-secret-key")
        assert h1 == h2

    def test_different_keys_different_hashes(self):
        h1 = mesh_key_hash("key-a")
        h2 = mesh_key_hash("key-b")
        assert h1 != h2

    def test_hash_is_hex_string(self):
        h = mesh_key_hash("test")
        assert len(h) == 64  # SHA-256 hex
        assert all(c in "0123456789abcdef" for c in h)


class TestMeshKeyPrefix:
    def test_prefix_is_8_chars(self):
        prefix = mesh_key_prefix("my-key")
        assert len(prefix) == 8

    def test_prefix_matches_hash_start(self):
        key = "test-mesh-key"
        assert mesh_key_prefix(key) == mesh_key_hash(key)[:8]


class TestSignVerify:
    def test_sign_verify_roundtrip(self):
        key = "shared-secret"
        body = b'{"node_id": "node-abc"}'
        ts = str(time.time())

        sig = sign_request(key, body, ts)
        assert verify_request(key, body, ts, sig)

    def test_wrong_key_rejected(self):
        body = b'{"data": "test"}'
        ts = str(time.time())

        sig = sign_request("correct-key", body, ts)
        assert not verify_request("wrong-key", body, ts, sig)

    def test_tampered_body_rejected(self):
        key = "secret"
        ts = str(time.time())

        sig = sign_request(key, b"original body", ts)
        assert not verify_request(key, b"tampered body", ts, sig)

    def test_expired_timestamp_rejected(self):
        key = "secret"
        body = b"test"
        old_ts = str(time.time() - 60.0)  # 60 seconds ago

        sig = sign_request(key, body, old_ts)
        assert not verify_request(key, body, old_ts, sig, max_age=30.0)

    def test_invalid_timestamp_rejected(self):
        key = "secret"
        body = b"test"

        sig = sign_request(key, body, "not-a-number")
        assert not verify_request(key, body, "not-a-number", sig)

    def test_fresh_timestamp_accepted(self):
        key = "secret"
        body = b"test"
        ts = str(time.time() - 5.0)  # 5 seconds ago

        sig = sign_request(key, body, ts)
        assert verify_request(key, body, ts, sig, max_age=30.0)
