from __future__ import annotations

import logging
from typing import Any

import httpx

from app.core.settings import get_settings
from app.models.telegram_schemas import TelegramResponse, TelegramServiceStatus
from app.modules.integrations.domain.ports.telegram_port import TelegramPort

logger = logging.getLogger("dscons.infrastructure.adapter.telegram")


class TelegramHttpAdapter(TelegramPort):
    """Secondary (Driven) Adapter for communicating with Telegram Bot HTTP API."""

    def __init__(
        self,
        bot_token: str | None = None,
        default_chat_id: str | None = None,
        timeout_seconds: float = 15.0,
    ) -> None:
        settings = get_settings()
        self.bot_token = (
            bot_token if bot_token is not None else settings.telegram_bot_token
        )
        self.default_chat_id = (
            default_chat_id
            if default_chat_id is not None
            else settings.telegram_chat_id
        )
        self.enabled = settings.telegram_enabled
        self._timeout = timeout_seconds

    async def send_message(
        self,
        text: str,
        chat_id: str | None = None,
        parse_mode: str = "HTML",
        disable_web_page_preview: bool = False,
        reply_markup: dict[str, Any] | None = None,
    ) -> TelegramResponse:
        """Dispatches an outbound message to Telegram API."""
        target_chat = chat_id or self.default_chat_id
        if not target_chat:
            target_chat = "dscons_management_channel"

        if not self.enabled:
            logger.info("Telegram service is disabled. Skipping message send.")
            return TelegramResponse(
                ok=False,
                status="disabled",
                details={"reason": "Telegram service disabled in configuration"},
            )

        if not self.bot_token:
            logger.info(
                "[TELEGRAM MOCK DISPATCH] Chat: %s | Text: %s", target_chat, text[:120]
            )
            return TelegramResponse(
                ok=True,
                message_id="mock-msg-" + str(hash(text))[:8],
                status="simulated_success",
                details={
                    "chat_id": target_chat,
                    "preview": text[:150],
                    "mode": "development_offline",
                },
            )

        api_url = f"https://api.telegram.org/bot{self.bot_token}/sendMessage"
        payload: dict[str, Any] = {
            "chat_id": target_chat,
            "text": text,
            "parse_mode": parse_mode,
            "disable_web_page_preview": disable_web_page_preview,
        }
        if reply_markup:
            payload["reply_markup"] = reply_markup

        try:
            async with httpx.AsyncClient(timeout=self._timeout) as client:
                res = await client.post(api_url, json=payload)
                data = res.json()
                if res.is_success and data.get("ok"):
                    msg_id = data.get("result", {}).get("message_id")
                    return TelegramResponse(
                        ok=True,
                        message_id=msg_id,
                        status="delivered",
                        details={"telegram_result": data.get("result")},
                    )
                return TelegramResponse(
                    ok=False,
                    status="api_error",
                    details={
                        "error_code": data.get("error_code"),
                        "description": data.get("description"),
                    },
                )
        except Exception as exc:
            logger.error("Failed to dispatch Telegram message: %s", exc)
            return TelegramResponse(
                ok=False,
                status="network_error",
                details={"error": str(exc)},
            )

    def get_status(self) -> TelegramServiceStatus:
        """Return operational status and connectivity metrics of Telegram Suite."""
        return TelegramServiceStatus(
            enabled=self.enabled,
            bot_configured=bool(self.bot_token),
            default_chat_configured=bool(self.default_chat_id),
            live_gateway=True,
            supported_commands=[
                "/start",
                "/help",
                "/duan",
                "/camay",
                "/hoadon",
                "/nhatky",
                "/vattu",
                "/warroom",
                "/telematics",
                "/doisoat",
                "/ai",
            ],
            webhook_url=get_settings().app_public_url + "/v1/telegram/webhook"
            if get_settings().app_public_url
            else None,
        )
