"""Helpers to verify Telegram Gateway callback signatures."""

from __future__ import annotations

import hashlib
import hmac
import time


def compute_signature(api_token: str, timestamp: str, raw_body: bytes) -> str:
    """Compute signature according to Telegram Gateway docs.

    Formula:
    secret_key = SHA256(api_token)
    data_check_string = timestamp + '\n' + raw_body
    signature = HEX(HMAC_SHA256(data_check_string, secret_key))
    """
    secret_key = hashlib.sha256(api_token.encode("utf-8")).digest()
    data_check = timestamp.encode("utf-8") + b"\n" + raw_body
    return hmac.new(secret_key, data_check, hashlib.sha256).hexdigest()


def verify_callback_signature(
    *,
    api_token: str,
    timestamp_header: str,
    signature_header: str,
    raw_body: bytes,
    max_age_seconds: int = 300,
    now: int | None = None,
) -> bool:
    """Verify Telegram callback signature and freshness by timestamp."""
    if not timestamp_header or not signature_header:
        return False

    try:
        timestamp = int(timestamp_header)
    except ValueError:
        return False

    now_value = int(time.time()) if now is None else now
    if abs(now_value - timestamp) > max_age_seconds:
        return False

    expected = compute_signature(api_token, timestamp_header, raw_body)
    return hmac.compare_digest(expected, signature_header)
