import logging
from typing import Dict, List
import httpx

from config import config

logger = logging.getLogger(__name__)


class WhatsAppChecker:
    """Checks WhatsApp registration via a connected WAHA / Baileys HTTP bridge."""

    def __init__(self, api_url: str, api_key: str = ""):
        self.api_url = api_url
        self.api_key = api_key

    async def check_number(self, phone: str, session_name: str = "default") -> str:
        if not self.api_url:
            return "UNCHECKED"
        headers = {"X-Api-Key": self.api_key} if self.api_key else {}
        clean_digits = phone.lstrip("+")
        try:
            async with httpx.AsyncClient(timeout=10) as client:
                resp = await client.get(
                    self.api_url,
                    params={"phone": clean_digits, "session": session_name},
                    headers=headers,
                )
                if resp.status_code != 200:
                    return "UNCHECKED"
                data = resp.json()
                exists = bool(data.get("numberExists") or data.get("exists"))
                return "REGISTERED" if exists else "FRESH"
        except Exception as exc:
            logger.warning("WhatsApp check failed for %s: %s", phone, exc)
            return "UNCHECKED"


class TelegramChecker:
    """Checks Telegram registration using Telethon StringSession."""

    def __init__(self, api_id: int, api_hash: str):
        self.api_id = api_id
        self.api_hash = api_hash

    async def check_number(self, phone: str, session_string: str) -> str:
        if not (self.api_id and self.api_hash and session_string):
            return "UNCHECKED"
        try:
            from telethon import TelegramClient
            from telethon.sessions import StringSession
            from telethon.tl.functions.contacts import ImportContactsRequest, DeleteContactsRequest
            from telethon.tl.types import InputPhoneContact

            async with TelegramClient(StringSession(session_string), self.api_id, self.api_hash) as client:
                contact = InputPhoneContact(client_id=0, phone=phone, first_name="Check", last_name="User")
                result = await client(ImportContactsRequest([contact]))
                if result.users:
                    await client(DeleteContactsRequest(id=result.users))
                    return "REGISTERED"
                return "FRESH"
        except Exception as exc:
            logger.warning("Telegram check failed for %s: %s", phone, exc)
            return "UNCHECKED"


async def check_number_for_service(
    phone: str,
    checker_type: str,
    checker_accounts: List[Dict[str, str]],
) -> str:
    ctype = (checker_type or "NONE").upper()
    if ctype == "NONE" or not checker_accounts:
        return "UNCHECKED"

    account = checker_accounts[0]
    if ctype == "WA":
        checker = WhatsAppChecker(config.wa_checker_api_url, config.wa_checker_api_key)
        return await checker.check_number(phone, session_name=account["credential"])
    if ctype == "TG":
        checker = TelegramChecker(config.tg_api_id, config.tg_api_hash)
        return await checker.check_number(phone, session_string=account["credential"])
    return "UNCHECKED"
