"""Python 3. Check or make a MARZI signature (standard library only)."""
import hashlib
import hmac
import time


def sign(secret: str, timestamp: str, method: str, uri: str, body: bytes) -> str:
    """hex( HMAC-SHA256( secret, timestamp \\n METHOD \\n path?query \\n sha256hex(body) ) ); body is the raw bytes (b"" for GET)."""
    body_hash = hashlib.sha256(body).hexdigest()
    payload = f"{timestamp}\n{method}\n{uri}\n{body_hash}".encode()
    return hmac.new(secret.encode(), payload, hashlib.sha256).hexdigest()


def is_from_marzi(secret: str, headers: dict, method: str, uri: str, body: bytes, max_skew_seconds: int = 300) -> bool:
    """True when the request really comes from MARZI. `uri` is the path + query WITHOUT the folder your connector lives in."""
    timestamp = str(headers.get("X-Marzi-Timestamp", ""))
    given = str(headers.get("X-Marzi-Signature", "")).lower()
    if not timestamp.isdigit() or not given:
        return False
    if abs(time.time() - int(timestamp)) > max_skew_seconds:
        return False  # too old: someone may be replaying it
    return hmac.compare_digest(sign(secret, timestamp, method, uri, body), given)  # never compare with ==


if __name__ == "__main__":
    # Test vector from the documentation: must print 6555990f154cc9a91c0fb5182bfb991bebcca1fed0a1f137a11f0be74d5913d7
    print(sign("test-secret-key-0123456789abcdef", "1700000000", "POST", "/v1/auth/verify?x=1", '{"username":"khach","password":"mat khau"}'.encode()))
