import hashlib
import re
from typing import Tuple

try:
    import phonenumbers
except ImportError:
    phonenumbers = None


def clean_phone_number(raw: str) -> str:
    """Normalize a phone number to E.164-like format (+digits)."""
    digits = re.sub(r"[^0-9]", "", raw.strip())
    if len(digits) < 7 or len(digits) > 15:
        return ""
    return f"+{digits}"


def normalize_prefix(raw: str) -> str:
    """Clean a user-entered prefix for searching (keeps digits only)."""
    return re.sub(r"[^0-9]", "", raw.strip())


def iso_to_flag(iso_code: str) -> str:
    """Convert 2-letter ISO country code (e.g. BD) to flag emoji."""
    code = (iso_code or "").upper()
    if len(code) != 2 or not code.isalpha():
        return "🌐"
    return "".join(chr(127397 + ord(ch)) for ch in code)


def detect_country_info(phone: str) -> Tuple[str, str]:
    """Return (ISO_CODE, FLAG_EMOJI) for a phone number."""
    if phonenumbers is None:
        return "XX", "🌐"
    try:
        parsed = phonenumbers.parse(phone, None)
        iso = phonenumbers.region_code_for_number(parsed) or "XX"
        return iso.upper(), iso_to_flag(iso)
    except Exception:
        return "XX", "🌐"


def mask_phone_middle_3(phone: str, replacement: str = "***") -> str:
    """
    Hide exactly 3 digits in the middle of the phone number and replace them
    with '***' or custom admin text (e.g. +88017***45678 or +88017VIP45678).
    """
    cleaned = phone.strip()
    rep = replacement if replacement else "***"
    digits_only = cleaned.lstrip("+")
    has_plus = cleaned.startswith("+")

    if len(digits_only) <= 4:
        return ("+" if has_plus else "") + rep

    mid_start = max(1, (len(digits_only) - 3) // 2)
    masked_digits = digits_only[:mid_start] + rep + digits_only[mid_start + 3 :]
    return ("+" if has_plus else "") + masked_digits


def extract_otp_code(text: str) -> str:
    """Extract a 4-8 digit OTP code (supports formats like 123-456 or 482910)."""
    if not text:
        return "N/A"
    hyphen_match = re.search(r"\b(\d{3}-\d{3})\b", text)
    if hyphen_match:
        return hyphen_match.group(1).replace("-", "")
    digit_match = re.search(r"\b(\d{4,8})\b", text)
    if digit_match:
        return digit_match.group(1)
    return "N/A"


def detect_sms_language(text: str) -> str:
    """Detect the language name of an incoming OTP SMS message."""
    if not text or not text.strip():
        return "Unknown"

    script_checks = [
        (r"[\u0980-\u09FF]", "Bengali (বাংলা)"),
        (r"[\u0600-\u06FF]", "Arabic (العربية)"),
        (r"[\u0900-\u097F]", "Hindi (हिन्दी)"),
        (r"[\u0400-\u04FF]", "Russian (Русский)"),
        (r"[\u4E00-\u9FFF]", "Chinese (中文)"),
        (r"[\u3040-\u30FF]", "Japanese (日本語)"),
        (r"[\uAC00-\uD7AF]", "Korean (한국어)"),
        (r"[\u0E00-\u0E7F]", "Thai (ไทย)"),
        (r"[\u0590-\u05FF]", "Hebrew (עברית)"),
    ]
    for pattern, lang_name in script_checks:
        if re.search(pattern, text):
            return lang_name

    lower = f" {text.lower()} "
    latin_hints = [
        (["kode", "jangan", "bagikan", "verifikasi", "anda"], "Indonesian"),
        (["código", "codigo", "compartas", "verificación", "tu "], "Spanish"),
        (["código", "não", "compartilhe", "verificação", "seu "], "Portuguese"),
        (["votre", "code de", "ne partagez", "vérification"], "French"),
        (["ihr ", "dein ", "nicht teilen", "bestätigungscode"], "German"),
        (["doğrulama", "kodunuz", "paylaşmayın"], "Turkish"),
        (["mã ", "xác minh", "không chia sẻ"], "Vietnamese"),
        (["codice", "non condividere", "verifica"], "Italian"),
    ]
    for words, lang_name in latin_hints:
        if any(w in lower for w in words):
            return lang_name

    if re.search(r"[A-Za-z]", text):
        return "English"
    return "Unknown"


def build_sms_hash(phone: str, sender: str, text: str) -> str:
    """Create a deterministic hash to prevent duplicate OTP credits across panels."""
    raw = f"{phone}|{sender.strip().lower()}|{text.strip()}"
    return hashlib.sha256(raw.encode("utf-8")).hexdigest()


def format_group_otp_message(
    service_icon: str,
    service_name: str,
    iso_code: str,
    flag: str,
    phone_number: str,
    mask_replacement: str = "***",
) -> str:
    """
    Format the privacy-first OTP group post:
    - NO full SMS text
    - Shows only Country ISO + flag, Service logo/name, and 3-digit masked number
    - Full number and OTP remain hidden and are copied via inline CopyTextButton
    """
    masked = mask_phone_middle_3(phone_number, replacement=mask_replacement)
    return (
        f"{flag} <b>{iso_code}</b>  |  {service_icon} <b>{service_name}</b>\n"
        f"📱 <code>{masked}</code>\n"
        f"👇 <i>নম্বর বা OTP কপি করতে নিচের বাটনে ক্লিক করুন</i>"
    )
