"""PSK authentication for mesh peer communication."""

from __future__ import annotations

import hashlib
import hmac
import time


def mesh_key_hash(mesh_key: str) -> str:
    """SHA-256 hash of mesh key."""
    return hashlib.sha256(mesh_key.encode("utf-8")).hexdigest()


def mesh_key_prefix(mesh_key: str) -> str:
    """First 8 chars of hash -- for mDNS TXT record filtering."""
    return mesh_key_hash(mesh_key)[:8]


def sign_request(mesh_key: str, body: bytes, timestamp: str) -> str:
    """HMAC-SHA256(key, body + timestamp)."""
    message = body + timestamp.encode("utf-8")
    return hmac.new(
        mesh_key.encode("utf-8"),
        message,
        hashlib.sha256,
    ).hexdigest()


def verify_request(
    mesh_key: str,
    body: bytes,
    timestamp: str,
    signature: str,
    max_age: float = 30.0,
) -> bool:
    """Verify HMAC and timestamp freshness.

    Returns True if the signature is valid and the timestamp is within
    ``max_age`` seconds of the current time.
    """
    # Check timestamp freshness
    try:
        ts = float(timestamp)
    except (ValueError, TypeError):
        return False

    if abs(time.time() - ts) > max_age:
        return False

    # Constant-time comparison
    expected = sign_request(mesh_key, body, timestamp)
    return hmac.compare_digest(expected, signature)
