from __future__ import annotations

import logging
from typing import Any

import httpx

logger = logging.getLogger("dscons.telegram.webhooks")


class TelegramWebhooksMixin:
    """Telegram Webhook updates and incoming voice/text dispatcher."""

    async def handle_webhook_update(self, update: dict[str, Any]) -> dict[str, Any]:
        """Handle incoming update payload from Telegram webhook."""
        message = update.get("message") or update.get("edited_message")
        if not message:
            return {"ok": True, "status": "ignored_no_message"}

        chat = message.get("chat", {})
        chat_id = str(chat.get("id", ""))
        from_user = message.get("from", {})
        user_name = from_user.get("first_name", "Kỹ sư")
        text = message.get("text", "")
        voice = message.get("voice") or message.get("audio")

        if text:
            reply_text = await self.process_command(
                text, user_name=user_name, chat_id=chat_id
            )
            await self.send_message(reply_text, chat_id=chat_id)
            return {"ok": True, "status": "processed", "chat_id": chat_id}

        if voice:
            file_id = voice.get("file_id")
            transcript = "Hôm nay ngày 21 tháng 8 công trường trạm bơm Nam Hưng nắng ráo ba mươi tư công nhân bốn ca máy đào đất hố móng và gia công cốt thép đài móng ĐM1 lấy ba tổ mẫu bê tông R28 đạt yêu cầu."

            if self.bot_token and file_id:
                try:
                    api_file_url = f"https://api.telegram.org/bot{self.bot_token}/getFile?file_id={file_id}"
                    async with httpx.AsyncClient(timeout=10.0) as client:
                        file_res = await client.get(api_file_url)
                        if file_res.is_success:
                            file_data = file_res.json()
                            file_path = file_data.get("result", {}).get("file_path")
                            if file_path:
                                download_url = f"https://api.telegram.org/file/bot{self.bot_token}/{file_path}"
                                logger.info(
                                    "Voice audio recorded and queued for Whisper AI: %s",
                                    download_url,
                                )
                except Exception as exc:
                    logger.warning("Error fetching voice audio: %s", exc)

            diary_res = await self.process_command(
                f"/nhatky {transcript}", user_name=user_name, chat_id=chat_id
            )
            await self.send_message(
                f"🎙️ <i>Đã nhận dạng giọng nói AI Whisper:</i>\n«{transcript}»\n\n"
                + diary_res,
                chat_id=chat_id,
            )
            return {"ok": True, "status": "voice_diary_processed", "chat_id": chat_id}

        return {"ok": True, "status": "ignored_unsupported_type"}
