"""Example-only helpers for the documented flat collection signing protocol.

No HTTP calls or credentials are included. Configure secrets on your server.
The supported example input values are strings, integers and null. Confirm
additional value types, response signatures and channel limits during setup.
"""
from __future__ import annotations
import hashlib
import hmac
import re
from collections.abc import Mapping

def sign_collect(parameters: Mapping[str, object], secret: str) -> str:
    """Sort nonempty flat scalar fields, append the secret, return MD5 hex."""
    if not isinstance(secret, str) or not secret:
        raise ValueError("A server-side secret is required")
    values: dict[str, str] = {}
    for name, value in parameters.items():
        if not isinstance(name, str) or not re.fullmatch(r"[A-Za-z0-9_]+", name):
            raise ValueError("Use the exact documented ASCII field names")
        if name == "sign" or value is None or value == "":
            continue
        if isinstance(value, bool) or not isinstance(value, (str, int)):
            raise TypeError("This example accepts only strings and integers")
        values[name] = str(value)
    canonical = "&".join(name + "=" + values[name] for name in sorted(values))
    signed_text = canonical + "&key=" + secret
    return hashlib.md5(signed_text.encode("utf-8")).hexdigest()

def verify_collect_notification(
    parameters: Mapping[str, object],
    api_secret: str,
    callback_secret: str | None = None,
) -> bool:
    """Verify the JSON field signature, preserving all received string values."""
    if not isinstance(parameters, Mapping):
        return False
    supplied = parameters.get("sign")
    if not isinstance(supplied, str) or not re.fullmatch(r"[0-9a-f]{32}", supplied):
        return False
    secret = callback_secret or api_secret
    try:
        expected = sign_collect(parameters, secret)
    except (ValueError, TypeError):
        return False
    return hmac.compare_digest(expected, supplied)
