"""
Shared HMAC signing used by the fleet check-in channel.

Both sides use this module:
  - the tenant install signs its payload before sending
  - Final Target verifies the signature before trusting the payload

The signature covers the raw JSON body plus a unix timestamp, so a captured
request cannot be replayed outside the freshness window.
"""
import hashlib
import hmac
import time

# Requests older than this are rejected
MAX_SKEW_SECONDS = 300


def sign(secret, body_bytes, timestamp):
    """Return the hex HMAC-SHA256 of '<timestamp>.<body>' using secret."""
    if isinstance(secret, str):
        secret = secret.encode('utf-8')
    if isinstance(body_bytes, str):
        body_bytes = body_bytes.encode('utf-8')
    message = str(timestamp).encode('utf-8') + b'.' + body_bytes
    return hmac.new(secret, message, hashlib.sha256).hexdigest()


def verify(secret, body_bytes, timestamp, signature):
    """
    Constant-time check of a received signature.
    Returns (ok, reason). reason is '' when ok is True.
    """
    if not secret:
        return False, 'no shared secret configured for this tenant'
    try:
        ts = int(timestamp)
    except (TypeError, ValueError):
        return False, 'missing or invalid timestamp'

    skew = abs(time.time() - ts)
    if skew > MAX_SKEW_SECONDS:
        return False, 'timestamp outside the allowed window'

    expected = sign(secret, body_bytes, ts)
    if not hmac.compare_digest(expected, signature or ''):
        return False, 'signature mismatch'

    return True, ''
