"""心跳响应防伪：MD5(时间桶 + verify_code)。"""

import hashlib
from datetime import datetime, timezone


def heartbeat_time_bucket(dt: datetime | None = None) -> str:
    """UTC 时间桶，格式如 ``2026-05-20 15``（精确到小时）。"""
    if dt is None:
        dt = datetime.now(timezone.utc)
    elif dt.tzinfo is None:
        dt = dt.replace(tzinfo=timezone.utc)
    else:
        dt = dt.astimezone(timezone.utc)
    return dt.strftime("%Y-%m-%d %H")


def compute_server_verify_code(verify_code: str, dt: datetime | None = None) -> str:
    raw = f"{heartbeat_time_bucket(dt)}{verify_code}"
    return hashlib.md5(raw.encode("utf-8")).hexdigest()
