"""HMAC request signing between the ATS and the self-hosted platform.

Scheme (mirrored in platform/shared/auth.py — keep the two in sync):

    signature = HMAC_SHA256(secret, f"{timestamp}.".encode() + raw_body)
    header    = X-ATS-Signature: t=<unix ts>,v1=<hex digest>

The timestamp is bound into the digest to prevent replay (default tolerance
five minutes)."""

import hashlib
import hmac
import time

HEADER = "X-ATS-Signature"
TOLERANCE_S = 300


def _digest(secret, timestamp, body):
    if isinstance(body, str):
        body = body.encode()
    msg = f"{timestamp}.".encode() + body
    return hmac.new(secret.encode(), msg, hashlib.sha256).hexdigest()


def sign_headers(secret, body, timestamp=None):
    """Headers to attach to an outgoing signed request."""
    ts = int(timestamp or time.time())
    return {HEADER: f"t={ts},v1={_digest(secret, ts, body)}"}


def verify_signature(secret, body, header_value, tolerance=TOLERANCE_S, now=None):
    """Constant-time verification of an incoming X-ATS-Signature header."""
    if not (secret and header_value):
        return False
    parts = dict(
        p.split("=", 1) for p in header_value.split(",") if "=" in p
    )
    try:
        ts = int(parts.get("t", ""))
    except ValueError:
        return False
    if abs(int(now or time.time()) - ts) > tolerance:
        return False
    expected = _digest(secret, ts, body)
    return hmac.compare_digest(expected, parts.get("v1", ""))
