import hashlib
import hmac
import secrets
from uuid import UUID
from core.config import get_settings


def generate_webhook_secret() -> str:
    """Generates a high-entropy secret token for X-Telegram-Bot-Api-Secret-Token."""
    return secrets.token_urlsafe(32)


def hash_webhook_secret(secret_token: str) -> str:
    """Computes SHA-256 hash of webhook secret token for secure database storage."""
    return hashlib.sha256(secret_token.strip().encode("utf-8")).hexdigest()


def verify_webhook_secret(received_token: str, stored_hash: str) -> bool:
    """Verifies received secret token against stored hash using constant-time comparison."""
    if not received_token or not stored_hash:
        return False
    computed_hash = hash_webhook_secret(received_token)
    return hmac.compare_digest(computed_hash, stored_hash)


def get_bot_webhook_url(bot_id: UUID) -> str:
    """Builds the webhook URL for a specific bot."""
    base_url = get_settings().TELEGRAM_WEBHOOK_BASE_URL.rstrip("/")
    return f"{base_url}/{bot_id}"
