# File: /Users/bpa/Desktop/ForesixaQuant/stripe_webhook_verification.py
# Description: Hardened Stripe SDK Webhook Cryptographic Verification Module
import os
import stripe

MAX_PAYLOAD_BYTES = 1_048_576
SIGNATURE_TOLERANCE_SECONDS = 300

def verify_webhook(raw_body: bytes, signature: str):
    """Return a verified event; raise on invalid input or configuration."""
    secret = os.environ.get("STRIPE_WEBHOOK_SECRET", "")
    mode = os.environ.get("STRIPE_MODE", "")

    if not secret or mode not in {"sandbox", "live"}:
        raise RuntimeError("Stripe webhook configuration is incomplete")

    if not isinstance(raw_body, bytes):
        raise ValueError("Unmodified request bytes are required")

    if not signature or len(raw_body) > MAX_PAYLOAD_BYTES:
        raise ValueError("Missing signature or oversized request")

    event = stripe.Webhook.construct_event(
        payload=raw_body,
        sig_header=signature,
        secret=secret,
        tolerance=SIGNATURE_TOLERANCE_SECONDS,
    )

    if event["livemode"] != (mode == "live"):
        raise ValueError("Stripe event environment mismatch")

    return event
