"""PeptideTech request signing for Python 3.8+. One file, standard library only.

    from peptidetech_signing import verify_request, sign_request

Incoming (PeptideTech -> your backend): pass the RAW body bytes, before any
JSON parsing, to verify_request(). Outgoing (your backend -> PeptideTech
/api/partners/v2/events): sign_request() returns the three x-peptidetech-*
headers. The secret is the signing secret from the merchant portal (or the
sandbox). Never log it.

Self-test against the published vectors:
    python3 peptidetech_signing.py --test peptidetech-signing-vectors.json
"""
import hashlib
import hmac
import json
import re
import sys
import time
import uuid

TOLERANCE_SECONDS = 300
_NONCE = re.compile(r"^[A-Za-z0-9_-]{16,100}$")
_TIMESTAMP = re.compile(r"^\d{10}$")


def _bytes(value):
    if value is None:
        return b""
    return value if isinstance(value, (bytes, bytearray)) else str(value).encode("utf-8")


def _header(headers, name):
    if not headers:
        return ""
    for key, value in headers.items():
        if key.lower() == name:
            return value[0] if isinstance(value, (list, tuple)) else (value or "")
    return ""


def string_to_sign(timestamp, nonce, method, path, body=b""):
    """timestamp.nonce.METHOD.path.sha256hex(raw body). GET signs an empty body."""
    return "%s.%s.%s.%s.%s" % (timestamp, nonce, str(method).upper(), path, hashlib.sha256(_bytes(body)).hexdigest())


def _hmac(secret, message):
    return hmac.new(_bytes(secret), message.encode("utf-8"), hashlib.sha256).hexdigest()


def challenge_proof(secret, challenge):
    """The proof /verify and integration.test must return: hex HMAC-SHA256(secret, challenge)."""
    return _hmac(secret, str(challenge))


def sign_request(secret, method, path, body=b"", nonce=None, timestamp=None):
    """Headers for a request to PeptideTech. For POST /events, nonce must equal the event id."""
    nonce = nonce or uuid.uuid4().hex
    timestamp = str(int(timestamp if timestamp is not None else time.time()))
    return {
        "x-peptidetech-timestamp": timestamp,
        "x-peptidetech-nonce": nonce,
        "x-peptidetech-signature": _hmac(secret, string_to_sign(timestamp, nonce, method, path, body)),
    }


def verify_request(secret, method, path, body, headers, now=None, tolerance_seconds=TOLERANCE_SECONDS):
    """Check a request PeptideTech sent you.

    path is the request path exactly as received, including your base path
    (for example /peptidetech/webhooks), without the query string. Returns
    {"ok": True} or {"ok": False, "reason": ..., "message": ..., "string_to_sign": ...}.
    Also reject a reused event id with a different body in your own database.
    """
    timestamp = _header(headers, "x-peptidetech-timestamp")
    nonce = _header(headers, "x-peptidetech-nonce")
    signature = _header(headers, "x-peptidetech-signature")
    now = int(now if now is not None else time.time())

    def fail(reason, message):
        out = {"ok": False, "reason": reason, "message": message}
        if timestamp and nonce:
            out["string_to_sign"] = string_to_sign(timestamp, nonce, method, path, body)
        return out

    if not (timestamp and nonce and signature):
        return fail("missing_headers", "x-peptidetech-timestamp, x-peptidetech-nonce and x-peptidetech-signature are required.")
    if not _TIMESTAMP.match(timestamp):
        return fail("bad_timestamp", "The timestamp must be Unix seconds.")
    if abs(now - int(timestamp)) > tolerance_seconds:
        return fail("expired_timestamp", "The timestamp is more than %d seconds from this server's clock." % tolerance_seconds)
    if not _NONCE.match(nonce):
        return fail("bad_nonce", "The nonce must be 16 to 100 letters, digits, underscores or hyphens.")
    expected = _hmac(secret, string_to_sign(timestamp, nonce, method, path, body))
    if not hmac.compare_digest(expected, str(signature)):
        return fail("bad_signature", "The signature does not match. Check the secret, the exact path and the raw body bytes.")
    return {"ok": True, "timestamp": int(timestamp), "nonce": nonce}


def verify_webhook(secret, method, path, body, headers, now=None, tolerance_seconds=TOLERANCE_SECONDS):
    """verify_request plus the webhook rule that the event id equals the nonce. Adds the parsed event when ok."""
    result = verify_request(secret, method, path, body, headers, now, tolerance_seconds)
    if not result["ok"]:
        return result
    try:
        event = json.loads(_bytes(body).decode("utf-8"))
    except ValueError:
        return {"ok": False, "reason": "bad_json", "message": "The body is not JSON."}
    if not isinstance(event, dict) or event.get("id") != result["nonce"]:
        return {"ok": False, "reason": "event_id_mismatch", "message": "The event id must equal x-peptidetech-nonce."}
    result["event"] = event
    return result


def self_test(vectors, proofs=()):
    """Run the published test vectors. Returns the number checked; raises on the first mismatch."""
    for v in vectors:
        s = string_to_sign(v["timestamp"], v["nonce"], v["method"], v["path"], v["body"])
        if s != v["string_to_sign"]:
            raise AssertionError("%s: string to sign differs" % v["name"])
        headers = sign_request(v["secret"], v["method"], v["path"], v["body"], v["nonce"], v["timestamp"])
        if headers["x-peptidetech-signature"] != v["signature"]:
            raise AssertionError("%s: signature differs" % v["name"])
        check = verify_request(v["secret"], v["method"], v["path"], v["body"], headers, now=v["timestamp"])
        if not check["ok"]:
            raise AssertionError("%s: %s" % (v["name"], check["reason"]))
    for p in proofs:
        if challenge_proof(p["secret"], p["challenge"]) != p["proof"]:
            raise AssertionError("challenge proof differs")
    return len(vectors) + len(proofs)


if __name__ == "__main__":
    if len(sys.argv) != 3 or sys.argv[1] != "--test":
        sys.stderr.write("Usage: python3 peptidetech_signing.py --test peptidetech-signing-vectors.json\n")
        sys.exit(2)
    with open(sys.argv[2], encoding="utf-8") as f:
        data = json.load(f)
        print("ok %d vectors" % self_test(data["vectors"], data.get("proofs", [])))
