"""Validate CheckThisFile raw webhook bytes before JSON parsing.

Use in FastAPI: body = await request.body(); validate_raw(body, header, secret)
Then transact: INSERT event.id with UNIQUE constraint + schedule company reconciliation.
Do not mark a document current from arrival order. Fetch changes/record from the API.
Return 2xx only AFTER persisting; on duplicate id return 2xx without repeating effects.
"""
import hashlib
import hmac
import json
import re
import time


def validate_raw(body: bytes, signature_header: str, secret: str, *, now: int | None = None) -> dict:
    if len(body) > 16384 or len(secret) < 32:
        raise ValueError("Invalid webhook")
    match = re.fullmatch(r"t=(\d{1,12}),v1=([a-f0-9]{64})", signature_header)
    if match is None or abs((int(time.time()) if now is None else now) - int(match[1])) > 300:
        raise ValueError("Invalid or stale webhook signature")
    expected = hmac.new(secret.encode(), match[1].encode() + b"." + body, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(match[2], expected):
        raise ValueError("Invalid webhook signature")
    event = json.loads(body)
    if event.get("type") not in ("integrity.registered", "integrity.superseded", "integrity.revoked"):
        raise ValueError("Unsupported integrity event")
    for field in ("id", "occurredAt", "publicId", "companyReference", "source", "documentReference", "documentVersion"):
        if field not in event:
            raise ValueError("Incomplete integrity event")
    return event
