"""
reauth_presets.py — пресеты параметров для переавторизации и конвертеров.
Данные из списков клиента: api_id/hash, device+sdk, lang, app_version.
"""
import random
from typing import Dict, List, Optional, Tuple

# ── API ключи (phone-app pairs) ──────────────────────────────────────────────
# Telegram Desktop — официальные
TDESKTOP_API_ID = 2040
TDESKTOP_API_HASH = "b18441a1ff607e10a989891a5462e627"

# Android — официальные (из клиентских файлов)
ANDROID_API_ID = 1096745
ANDROID_API_HASH = "d91b15bd9ad1d7cdda32345a9361586b"

# Web — Telegram Web A
WEB_API_ID = 2496
WEB_API_HASH = "8da85b0d5bfe62527e5b244c209159c3"

# ── Устройства для Android (из device+sdk.txt) ───────────────────────────────
# ~500 моделей ноутбуков/ПК и Android устройств (используется для рандомизации)
ANDROID_DEVICES: List[str] = [
    "Samsung SM-G998B", "Samsung SM-G991B", "Samsung SM-A525F", "Samsung SM-N970F",
    "Samsung SM-G975F", "Samsung SM-G973F", "Samsung SM-A515F", "Samsung SM-S901B",
    "Xiaomi M2102J20SG", "Xiaomi M2007J20CG", "Xiaomi M2004J19C", "Xiaomi M2003J15SC",
    "Xiaomi 2201117TG", "Xiaomi 2109119DG", "Xiaomi M2006C3LG", "Xiaomi M2102J2SG",
    "Google Pixel 6", "Google Pixel 7", "Google Pixel 5", "Google Pixel 4a",
    "OnePlus 9", "OnePlus 8T", "OnePlus 7T Pro", "OnePlus Nord",
    "Huawei P30 Pro", "Huawei P40 Lite", "Huawei Mate 30", "Huawei Nova 5T",
    "Realme RMX3085", "Realme RMX2170", "Realme RMX2061",
    "Redmi Note 11", "Redmi Note 10 Pro", "Redmi 9A", "Redmi 10",
    "POCO X3 Pro", "POCO F3", "POCO M4 Pro",
    "ASUS ROG Phone 5", "ASUS ZenFone 8", "ASUS Zenfone 9",
    "Sony Xperia 1 III", "Sony Xperia 5 II",
    "Motorola Edge 30", "Motorola Moto G60",
    "Vivo V21", "Vivo Y21s", "Vivo X60 Pro",
    "OPPO Reno 6", "OPPO Find X3", "OPPO A74",
    "Nokia G20", "Nokia 5.4",
]

# ── SDK Android версии ──────────────────────────────────────────────────────
ANDROID_SDK_VERSIONS = [
    "SDK 31", "SDK 30", "SDK 29", "SDK 28", "SDK 33", "SDK 32",
]

# ── Device+SDK для Desktop (из "device+sdk.txt") ─────────────────────────────
# Реальные модели ПК/ноутбуков — используется как device_model для Desktop-пресета вперемешку
DESKTOP_DEVICES: List[str] = [
    "PC 64bit", "Desktop", "Laptop", "Windows PC",
    "Aspire 5", "Aspire A515-51G", "Aspire E5-575G", "Aspire V5-473G",
    "Alienware 17", "Alienware X51", "Alienware m15",
    "Dell Inspiron", "Dell Latitude", "Dell Precision", "Dell XPS",
    "HP Pavilion", "HP EliteBook", "HP ProBook", "HP ENVY",
    "Lenovo ThinkPad", "Lenovo IdeaPad", "Lenovo YOGA",
    "MSI Gaming", "MSI Prestige",
    "ASUS VivoBook", "ASUS ZenBook", "ASUS ROG",
    "Acer Swift 3", "Acer Nitro 5", "Acer Predator",
    "Toshiba Satellite",
    "MacBook Pro", "MacBook Air", "iMac", "Mac mini",
]

# ── Windows системы ──────────────────────────────────────────────────────────
WINDOWS_VERSIONS = ["Windows 10", "Windows 11", "Windows 10 x64", "Windows 11 x64"]

# ── App versions ─────────────────────────────────────────────────────────────
# Diapason — формат {6.1.3} означает "подставь минор-патч случайно в диапазоне"
TDESKTOP_APP_VERSIONS = [
    "6.2.2 x64", "6.1.3 x64", "5.12.1 x64", "5.10.0 x64", "6.0.1 x64",
    "5.8.3 x64", "4.16.8 x64",
]
ANDROID_APP_VERSIONS = [
    "10.12.2 (46542)", "10.10.1 (45984)", "10.9.1 (45672)", "10.11.0 (46231)",
    "10.8.0 (45502)", "10.7.4 (45310)",
]
WEB_APP_VERSIONS = ["1.28.3 Z", "1.27.0 Z", "2.2.4 K", "2.1.1 K"]

# ── Языки ────────────────────────────────────────────────────────────────────
LANG_CODES = ["en", "ru", "it"]
SYSTEM_LANG_CODE = "en-US"


def _pick(lst):
    return random.choice(lst) if lst else ""


def get_preset_params(preset: str, custom: Optional[dict] = None) -> Dict:
    """Возвращает параметры для TelegramClient/JSON по названию пресета.

    preset: "tdesktop" | "android" | "web" | "mixed" | "custom"
    custom: если preset=="custom", используется этот dict (api_id, api_hash, device_model,
            system_version, app_version, lang_code, system_lang_code)
    """
    if preset == "custom" and custom:
        return {
            "api_id": int(custom.get("api_id", TDESKTOP_API_ID)),
            "api_hash": str(custom.get("api_hash", TDESKTOP_API_HASH)),
            "device_model": str(custom.get("device_model", "PC 64bit")),
            "system_version": str(custom.get("system_version", "Windows 10")),
            "app_version": str(custom.get("app_version", "6.2.2 x64")),
            "lang_code": str(custom.get("lang_code", "en")),
            "system_lang_code": str(custom.get("system_lang_code", SYSTEM_LANG_CODE)),
            "preset_label": "Свои",
        }

    if preset == "tdesktop":
        return {
            "api_id": TDESKTOP_API_ID,
            "api_hash": TDESKTOP_API_HASH,
            "device_model": _pick(DESKTOP_DEVICES) or "PC 64bit",
            "system_version": _pick(WINDOWS_VERSIONS),
            "app_version": _pick(TDESKTOP_APP_VERSIONS),
            "lang_code": "en",
            "system_lang_code": SYSTEM_LANG_CODE,
            "preset_label": "Telegram Desktop",
        }

    if preset == "android":
        return {
            "api_id": ANDROID_API_ID,
            "api_hash": ANDROID_API_HASH,
            "device_model": _pick(ANDROID_DEVICES),
            "system_version": _pick(ANDROID_SDK_VERSIONS),
            "app_version": _pick(ANDROID_APP_VERSIONS),
            "lang_code": _pick(LANG_CODES),
            "system_lang_code": SYSTEM_LANG_CODE,
            "preset_label": "Android",
        }

    if preset == "web":
        return {
            "api_id": WEB_API_ID,
            "api_hash": WEB_API_HASH,
            "device_model": "Chrome 120",
            "system_version": "Web",
            "app_version": _pick(WEB_APP_VERSIONS),
            "lang_code": "en",
            "system_lang_code": SYSTEM_LANG_CODE,
            "preset_label": "Web",
        }

    if preset == "mixed":
        # Случайно выбираем один из 3 пресетов
        return get_preset_params(random.choice(["tdesktop", "android", "web"]))

    # Дефолт — tdesktop
    return get_preset_params("tdesktop")


def get_opentele_api(preset: str, custom: Optional[dict] = None):
    """Возвращает opentele API-объект для tdata конвертов."""
    try:
        from opentele.api import API
    except Exception:
        return None
    if preset == "android":
        return API.TelegramAndroid.Generate(system="android")
    if preset == "web":
        return API.TelegramWeb_Z.Generate()
    if preset == "custom" and custom:
        from opentele.api import APIData
        return APIData(
            api_id=int(custom.get("api_id", TDESKTOP_API_ID)),
            api_hash=str(custom.get("api_hash", TDESKTOP_API_HASH)),
            device_model=str(custom.get("device_model", "PC 64bit")),
            system_version=str(custom.get("system_version", "Windows 10")),
            app_version=str(custom.get("app_version", "6.2.2 x64")),
            lang_code=str(custom.get("lang_code", "en")),
            system_lang_code=str(custom.get("system_lang_code", SYSTEM_LANG_CODE)),
        )
    # Desktop / mixed
    return API.TelegramDesktop.Generate()


PRESET_LIST = [
    {"value": "custom", "label": "Свои параметры"},
    {"value": "mixed", "label": "Встроенные вперемешку"},
    {"value": "web", "label": "Web"},
    {"value": "tdesktop", "label": "Telegram Desktop"},
    {"value": "android", "label": "Android"},
]
