"""HMAC request signing between platform services and the ATS.

MIRROR of backend/apps/ai_calls/security.py — the Django side cannot import
this package (separate roots), so the ~30 lines are duplicated by design.
If you change the scheme, change BOTH files.

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

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):
    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):
    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
    return hmac.compare_digest(_digest(secret, ts, body), parts.get("v1", ""))
