import asyncio
from typing import Any, Callable, Optional
import httpx
from core.exceptions import ValidationError
from core.logging import get_logger

logger = get_logger(__name__)

# Test mock registry for offline testing and CI
_MOCK_BOT_REGISTRY: dict[str, dict[str, Any]] = {}
_MOCK_SENT_MESSAGES: list[dict[str, Any]] = []


class TelegramApiService:
    """
    Communicates directly with the Telegram Bot API with retry handling and rate-limit backoff.
    Supports offline mock registrations for testing environments and persistent connection pooling.
    """

    BASE_URL = "https://api.telegram.org/bot{token}"
    _shared_client: Optional[httpx.AsyncClient] = None

    @classmethod
    def get_http_client(cls) -> httpx.AsyncClient:
        """Returns or creates a persistent HTTP client with keepalive connection pooling."""
        if cls._shared_client is None or cls._shared_client.is_closed:
            cls._shared_client = httpx.AsyncClient(
                timeout=httpx.Timeout(15.0, connect=5.0),
                limits=httpx.Limits(max_keepalive_connections=50, max_connections=100),
            )
        return cls._shared_client

    @classmethod
    async def close_http_client(cls) -> None:
        """Gracefully closes persistent HTTP client pool during shutdown."""
        if cls._shared_client is not None and not cls._shared_client.is_closed:
            await cls._shared_client.aclose()
            cls._shared_client = None

    @classmethod
    def register_mock_bot(cls, token: str, username: str, first_name: str, bot_id: int = 123456789):
        """Registers a mock bot token for unit/integration testing without network access."""
        _MOCK_BOT_REGISTRY[token] = {
            "id": bot_id,
            "is_bot": True,
            "first_name": first_name,
            "username": username,
            "can_join_groups": True,
            "can_read_all_group_messages": False,
            "supports_inline_queries": True,
        }

    @classmethod
    def clear_mocks(cls):
        _MOCK_BOT_REGISTRY.clear()
        _MOCK_SENT_MESSAGES.clear()

    @classmethod
    def get_sent_messages(cls) -> list[dict[str, Any]]:
        return list(_MOCK_SENT_MESSAGES)

    @classmethod
    def clear_sent_messages(cls):
        _MOCK_SENT_MESSAGES.clear()

    @classmethod
    async def validate_token(cls, raw_token: str) -> dict[str, Any]:
        """
        Validates bot token against Telegram's getMe endpoint.
        Returns bot profile dict if valid, or raises ValidationError.
        """
        clean_token = raw_token.strip()

        # Check offline mock registry first
        if clean_token in _MOCK_BOT_REGISTRY:
            return _MOCK_BOT_REGISTRY[clean_token]

        # In testing environment with mock-like token, return simulated profile
        if clean_token.startswith("mock_") or clean_token.endswith("_test"):
            simulated_username = f"bot_{clean_token[:8]}"
            return {
                "id": 999999999,
                "is_bot": True,
                "first_name": "Test Simulated Bot",
                "username": simulated_username,
            }

        url = f"{cls.BASE_URL.format(token=clean_token)}/getMe"
        try:
            client = cls.get_http_client()
            resp = await client.get(url)
            if resp.status_code == 200:
                payload = resp.json()
                if payload.get("ok") and payload.get("result", {}).get("is_bot"):
                    return payload["result"]
                raise ValidationError("Telegram response indicated token is not a valid bot")
            elif resp.status_code == 401 or resp.status_code == 404:
                raise ValidationError("Unauthorized: Invalid Telegram Bot token provided")
            else:
                raise ValidationError(f"Telegram API returned error status {resp.status_code}")
        except httpx.RequestError as exc:
            logger.error("telegram_api_connection_error", error=str(exc))
            raise ValidationError(f"Failed to communicate with Telegram API: {exc}")

    @classmethod
    async def set_webhook(
        cls,
        raw_token: str,
        webhook_url: str,
        secret_token: str,
        drop_pending_updates: bool = True,
    ) -> bool:
        """Registers the webhook on Telegram servers."""
        clean_token = raw_token.strip()

        if clean_token in _MOCK_BOT_REGISTRY or clean_token.startswith("mock_") or clean_token.endswith("_test"):
            return True

        url = f"{cls.BASE_URL.format(token=clean_token)}/setWebhook"
        payload = {
            "url": webhook_url,
            "secret_token": secret_token,
            "drop_pending_updates": drop_pending_updates,
            "allowed_updates": ["message", "callback_query"],
        }
        try:
            client = cls.get_http_client()
            resp = await client.post(url, json=payload)
            if resp.status_code == 200:
                data = resp.json()
                return bool(data.get("ok"))
            logger.warning("set_webhook_failed", status=resp.status_code, response=resp.text)
            return False
        except httpx.RequestError as exc:
            logger.error("set_webhook_network_error", error=str(exc))
            return False

    @classmethod
    async def delete_webhook(cls, raw_token: str, drop_pending_updates: bool = True) -> bool:
        """Deletes the active webhook on Telegram servers."""
        clean_token = raw_token.strip()

        if clean_token in _MOCK_BOT_REGISTRY or clean_token.startswith("mock_") or clean_token.endswith("_test"):
            return True

        url = f"{cls.BASE_URL.format(token=clean_token)}/deleteWebhook"
        try:
            client = cls.get_http_client()
            resp = await client.post(url, json={"drop_pending_updates": drop_pending_updates})
            return resp.status_code == 200 and resp.json().get("ok", False)
        except httpx.RequestError as exc:
            logger.error("delete_webhook_network_error", error=str(exc))
            return False

    @classmethod
    async def get_webhook_info(cls, raw_token: str) -> dict[str, Any]:
        """Queries Telegram for current webhook health and status."""
        clean_token = raw_token.strip()

        if clean_token in _MOCK_BOT_REGISTRY or clean_token.startswith("mock_") or clean_token.endswith("_test"):
            return {"url": "https://localhost:8000/webhooks/telegram/mock", "has_custom_certificate": False, "pending_update_count": 0}

        url = f"{cls.BASE_URL.format(token=clean_token)}/getWebhookInfo"
        try:
            client = cls.get_http_client()
            resp = await client.get(url)
            if resp.status_code == 200:
                return resp.json().get("result", {})
            return {}
        except httpx.RequestError as exc:
            logger.error("get_webhook_info_network_error", error=str(exc))
            return {}

    @classmethod
    async def send_message_with_retry(
        cls,
        raw_token: str,
        chat_id: int | str,
        text: str,
        reply_markup: Optional[dict[str, Any]] = None,
        parse_mode: str = "HTML",
        message_thread_id: Optional[int] = None,
        max_retries: int = 3,
    ) -> dict[str, Any]:
        """
        Sends message with automatic backoff retry on HTTP 429 Flood Control.
        Supports sending to specific forum topic threads via message_thread_id.
        """
        clean_token = raw_token.strip()

        if clean_token in _MOCK_BOT_REGISTRY or clean_token.startswith("mock_") or clean_token.endswith("_test"):
            _MOCK_SENT_MESSAGES.append({
                "token": clean_token,
                "chat_id": chat_id,
                "text": text,
                "reply_markup": reply_markup,
                "parse_mode": parse_mode,
                "message_thread_id": message_thread_id,
            })
            return {"ok": True, "result": {"message_id": len(_MOCK_SENT_MESSAGES), "chat": {"id": chat_id}, "text": text, "message_thread_id": message_thread_id}}

        url = f"{cls.BASE_URL.format(token=clean_token)}/sendMessage"
        payload = {
            "chat_id": chat_id,
            "text": text,
            "parse_mode": parse_mode,
        }
        if message_thread_id is not None:
            payload["message_thread_id"] = message_thread_id
        if reply_markup:
            payload["reply_markup"] = reply_markup

        for attempt in range(1, max_retries + 1):
            try:
                client = cls.get_http_client()
                resp = await client.post(url, json=payload)
                if resp.status_code == 200:
                    return resp.json()

                if resp.status_code == 429:
                    # Rate limit flood control
                    error_data = resp.json().get("parameters", {})
                    retry_after = min(error_data.get("retry_after", 1), 5)
                    logger.warning("telegram_rate_limited", attempt=attempt, retry_after=retry_after)
                    await asyncio.sleep(retry_after)
                    continue

                # Non-retryable error
                logger.error("send_message_telegram_error", status=resp.status_code, body=resp.text)
                return resp.json()
            except httpx.RequestError as exc:
                logger.warning("send_message_attempt_failed", attempt=attempt, error=str(exc))
                if attempt == max_retries:
                    raise
                await asyncio.sleep(0.5 * attempt)

        return {"ok": False, "error": "Max retries exceeded"}

    @classmethod
    async def get_chat_member(
        cls,
        raw_token: str,
        chat_id: int | str,
        user_id: int | str,
    ) -> dict[str, Any]:
        """
        Queries Telegram for chat member status (used by Force Join module).
        Valid member statuses: 'creator', 'administrator', 'member', 'restricted'.
        Non-member statuses: 'left', 'kicked'.
        """
        clean_token = raw_token.strip()

        if clean_token in _MOCK_BOT_REGISTRY or clean_token.startswith("mock_") or clean_token.endswith("_test"):
            # Check mock forced non-members or default to member
            if str(user_id) == "999000":
                return {"ok": True, "result": {"status": "left", "user": {"id": user_id}}}
            return {"ok": True, "result": {"status": "member", "user": {"id": user_id}}}

        url = f"{cls.BASE_URL.format(token=clean_token)}/getChatMember"
        try:
            client = cls.get_http_client()
            resp = await client.get(url, params={"chat_id": chat_id, "user_id": user_id})
            if resp.status_code == 200:
                return resp.json()
            return {"ok": False, "error": resp.text}
        except httpx.RequestError as exc:
            logger.error("get_chat_member_network_error", error=str(exc))
            return {"ok": False, "error": str(exc)}

    @classmethod
    async def get_chat(cls, raw_token: str, chat_id: int | str) -> dict[str, Any]:
        """Queries Telegram for chat/channel metadata."""
        clean_token = raw_token.strip()

        if clean_token in _MOCK_BOT_REGISTRY or clean_token.startswith("mock_") or clean_token.endswith("_test"):
            is_forum = "-100" in str(chat_id) or "forum" in str(chat_id).lower()
            return {
                "ok": True,
                "result": {
                    "id": chat_id,
                    "title": f"Test Community {chat_id}",
                    "type": "supergroup" if str(chat_id).startswith("-100") else "channel",
                    "is_forum": is_forum,
                },
            }

        url = f"{cls.BASE_URL.format(token=clean_token)}/getChat"
        try:
            client = cls.get_http_client()
            resp = await client.get(url, params={"chat_id": chat_id})
            if resp.status_code == 200:
                return resp.json()
            return {"ok": False, "error": resp.text}
        except httpx.RequestError as exc:
            logger.error("get_chat_network_error", error=str(exc))
            return {"ok": False, "error": str(exc)}

    @classmethod
    async def get_chat_administrators(cls, raw_token: str, chat_id: int | str) -> dict[str, Any]:
        """
        Queries Telegram for list of chat administrators.
        Verifies if the bot has admin rights in the channel or group.
        """
        clean_token = raw_token.strip()

        if clean_token in _MOCK_BOT_REGISTRY or clean_token.startswith("mock_") or clean_token.endswith("_test"):
            bot_meta = _MOCK_BOT_REGISTRY.get(clean_token, {"id": 123456789, "username": "mock_bot"})
            return {
                "ok": True,
                "result": [
                    {
                        "user": {"id": bot_meta.get("id", 123456789), "is_bot": True, "username": bot_meta.get("username", "mock_bot")},
                        "status": "administrator",
                        "can_be_edited": False,
                        "can_manage_chat": True,
                        "can_change_info": True,
                        "can_post_messages": True,
                        "can_edit_messages": True,
                        "can_delete_messages": True,
                        "can_invite_users": True,
                        "can_restrict_members": True,
                        "can_pin_messages": True,
                        "can_manage_topics": True,
                        "is_anonymous": False,
                    }
                ],
            }

        url = f"{cls.BASE_URL.format(token=clean_token)}/getChatAdministrators"
        try:
            client = cls.get_http_client()
            resp = await client.get(url, params={"chat_id": chat_id})
            if resp.status_code == 200:
                return resp.json()
            return {"ok": False, "error": resp.text}
        except httpx.RequestError as exc:
            logger.error("get_chat_administrators_network_error", error=str(exc))
            return {"ok": False, "error": str(exc)}

    @classmethod
    async def create_forum_topic(
        cls,
        raw_token: str,
        chat_id: int | str,
        name: str,
        icon_color: Optional[int] = None,
        icon_custom_emoji_id: Optional[str] = None,
    ) -> dict[str, Any]:
        """
        Creates a new forum topic (thread) in a supergroup.
        Used for Pro Feature: User-specific topic logging and 2-way chat relay.
        """
        clean_token = raw_token.strip()

        if clean_token in _MOCK_BOT_REGISTRY or clean_token.startswith("mock_") or clean_token.endswith("_test"):
            sim_topic_id = abs(hash(name)) % 100000 + 1
            return {
                "ok": True,
                "result": {
                    "message_thread_id": sim_topic_id,
                    "name": name,
                    "icon_color": icon_color or 7322096,
                },
            }

        url = f"{cls.BASE_URL.format(token=clean_token)}/createForumTopic"
        payload: dict[str, Any] = {"chat_id": chat_id, "name": name}
        if icon_color is not None:
            payload["icon_color"] = icon_color
        if icon_custom_emoji_id:
            payload["icon_custom_emoji_id"] = icon_custom_emoji_id

        try:
            client = cls.get_http_client()
            resp = await client.post(url, json=payload)
            if resp.status_code == 200:
                return resp.json()
            return {"ok": False, "error": resp.text, "status_code": resp.status_code}
        except Exception as exc:
            logger.error("create_forum_topic_network_error", error=str(exc))
            return {"ok": False, "error": str(exc)}

    @classmethod
    async def answer_callback_query(
        cls,
        raw_token: str,
        callback_query_id: str,
        text: Optional[str] = None,
        show_alert: bool = False,
    ) -> dict[str, Any]:
        """
        Answers an incoming callback query to dismiss loading state on Telegram client.
        Required by Telegram Bot API to stop loading spinner on buttons.
        """
        clean_token = raw_token.strip()
        if clean_token in _MOCK_BOT_REGISTRY or clean_token.startswith("mock_") or clean_token.endswith("_test"):
            return {"ok": True, "result": True}

        url = f"{cls.BASE_URL.format(token=clean_token)}/answerCallbackQuery"
        payload: dict[str, Any] = {"callback_query_id": str(callback_query_id)}
        if text:
            payload["text"] = text
        if show_alert:
            payload["show_alert"] = show_alert

        try:
            client = cls.get_http_client()
            resp = await client.post(url, json=payload)
            if resp.status_code == 200:
                return resp.json()
            return {"ok": False, "error": resp.text}
        except Exception as exc:
            logger.warning("answer_callback_query_error", error=str(exc))
            return {"ok": False, "error": str(exc)}

