import hashlib
import hmac
import time
from typing import Any, Tuple


def verify_telegram_authorization(
    auth_data: dict[str, Any],
    bot_token: str,
    max_age_seconds: int = 86400,
) -> Tuple[bool, str]:
    """
    Verify authentication data received from Telegram Login Widget.
    
    Telegram verification algorithm:
    1. Check `auth_date` is fresh (< max_age_seconds) and not in the future.
    2. Build data_check_string by sorting all key=value pairs alphabetically, excluding 'hash'.
    3. Generate secret_key = SHA256(bot_token.encode()).digest()
    4. Calculate HMAC-SHA256(data_check_string, secret_key).hexdigest()
    5. Compare with received `hash` using constant-time comparison.
    """
    if not bot_token:
        return False, "Telegram bot token is not configured on the server."

    received_hash = auth_data.get("hash")
    if not received_hash or not isinstance(received_hash, str):
        return False, "Missing or invalid 'hash' in Telegram authorization data."

    # 1. Verify auth_date freshness
    auth_date_raw = auth_data.get("auth_date")
    if auth_date_raw is None:
        return False, "Missing 'auth_date' in Telegram authorization data."

    try:
        auth_date = int(auth_date_raw)
    except (ValueError, TypeError):
        return False, "Invalid 'auth_date' format."

    now = int(time.time())
    # Clock skew tolerance: allow up to 120 seconds in future
    if auth_date > now + 120:
        return False, "Authentication timestamp is in the future."

    # Replay protection: check expiration
    if (now - auth_date) > max_age_seconds:
        return False, f"Telegram authorization data has expired (age: {now - auth_date}s > {max_age_seconds}s)."

    # 2. Build data_check_string
    # Exclude 'hash', exclude None values, sort keys alphabetically
    check_pairs = []
    for key, val in sorted(auth_data.items()):
        if key == "hash" or val is None:
            continue
        check_pairs.append(f"{key}={val}")

    data_check_string = "\n".join(check_pairs)

    # 3. Derive secret key
    secret_key = hashlib.sha256(bot_token.encode("utf-8")).digest()

    # 4. Compute expected HMAC
    expected_hash = hmac.new(
        secret_key,
        data_check_string.encode("utf-8"),
        hashlib.sha256,
    ).hexdigest()

    # 5. Constant-time comparison
    if not hmac.compare_digest(expected_hash.lower(), received_hash.lower()):
        return False, "Cryptographic signature verification failed: invalid hash."

    return True, "Telegram authorization verified successfully."
