from typing import Any
from aiohttp import web
from userbot.client import userbot_send_message, userbot_edit_message

from middleware import logger


class APIServer:
    """
    Асинхронное API для связи aiogram ↔ pyrogram.
    Предоставляет эндпоинты для отправки и редактирования сообщений через Premium-аккаунт.
    """

    def __init__(self, host: str = "0.0.0.0", port: int = 8081) -> None:
        self.host = host
        self.port = port
        self.app = web.Application()
        self.app.add_routes([
            web.post("/api/send", self.send_message),
            web.post("/api/edit", self.edit_message),
            web.get("/api/health", self.health_check)
        ])
        self.runner: web.AppRunner | None = None
        self.site: web.TCPSite | None = None

    @staticmethod
    async def health_check(_: web.Request) -> web.Response:
        """Простейший эндпоинт для проверки состояния API."""
        return web.json_response({"status": "ok"})

    @staticmethod
    async def send_message(request: web.Request) -> web.Response:
        """
        Эндпоинт: /api/send
        Ожидает JSON:
        {
            "chat_id": str | int,
            "text": str,
            "parse_mode": str | None
        }
        """
        try:
            payload: dict[str, Any] = await request.json()
            chat_id = payload.get("chat_id")
            text = payload.get("text")
            parse_mode = payload.get("parse_mode")

            if not chat_id or not text:
                return web.json_response({"error": "chat_id and text required"}, status=400)

            message = await userbot_send_message(chat_id, text, parse_mode)
            return web.json_response({"status": "ok", "message_id": message.id})
        except Exception as e:
            logger.error(f"Ошибка отправки: {e}")
            return web.json_response({"status": "error", "detail": str(e)}, status=500)

    @staticmethod
    async def edit_message(request: web.Request) -> web.Response:
        """
        Эндпоинт: /api/edit
        Ожидает JSON:
        {
            "chat_id": str | int,
            "message_id": int,
            "text": str,
            "parse_mode": str | None
        }
        """
        try:
            payload: dict[str, Any] = await request.json()
            chat_id = payload.get("chat_id")
            message_id = payload.get("message_id")
            text = payload.get("text")
            parse_mode = payload.get("parse_mode")

            if not all([chat_id, message_id, text]):
                return web.json_response({"error": "chat_id, message_id, text required"}, status=400)

            message = await userbot_edit_message(chat_id, message_id, text, parse_mode)
            return web.json_response({"status": "ok", "message_id": message.id})
        except Exception as e:
            logger.error(f"Ошибка редактирования: {e}")
            return web.json_response({"status": "error", "detail": str(e)}, status=500)

    async def start(self) -> None:
        """Запуск aiohttp API-сервера."""
        self.runner = web.AppRunner(self.app)
        await self.runner.setup()
        self.site = web.TCPSite(self.runner, self.host, self.port)
        await self.site.start()
        log.info(f"🚀 API запущено на http://{self.host}:{self.port}")

    async def stop(self) -> None:
        """Остановка сервера."""
        if self.runner:
            await self.runner.cleanup()
