import aiohttp
from flask import current_app


class EvolutionClient:
    def _get_config(self):
        return {
            "api_url": current_app.config.get("EVOLUTION_API_URL", "http://localhost:8080"),
            "api_key": current_app.config.get("EVOLUTION_API_KEY", ""),
        }

    async def create_instance(self, instance_name: str, phone_number: str = None) -> dict:
        cfg = self._get_config()
        url = f"{cfg['api_url']}/instance/create"
        headers = {"apikey": cfg["api_key"], "Content-Type": "application/json"}
        payload = {"instanceName": instance_name, "integration": "WHATSAPP-BAILEYS"}
        if phone_number:
            payload["number"] = phone_number
        async with aiohttp.ClientSession() as session:
            async with session.post(url, json=payload, headers=headers) as resp:
                return await resp.json()

    async def get_qr_code(self, instance_name: str) -> dict:
        cfg = self._get_config()
        url = f"{cfg['api_url']}/instance/connect/{instance_name}"
        headers = {"apikey": cfg["api_key"]}
        async with aiohttp.ClientSession() as session:
            async with session.get(url, headers=headers) as resp:
                return await resp.json()

    async def send_text(self, instance_name: str, api_key: str, phone: str, message: str) -> dict:
        cfg = self._get_config()
        url = f"{cfg['api_url']}/message/sendText/{instance_name}"
        headers = {"apikey": api_key, "Content-Type": "application/json"}
        payload = {"number": phone, "text": message}
        async with aiohttp.ClientSession() as session:
            async with session.post(url, json=payload, headers=headers) as resp:
                return await resp.json()

    async def send_media(self, instance_name: str, api_key: str, phone: str, media_url: str, caption: str = "", media_type: str = "video") -> dict:
        cfg = self._get_config()
        url = f"{cfg['api_url']}/message/sendMedia/{instance_name}"
        headers = {"apikey": api_key, "Content-Type": "application/json"}
        payload = {"number": phone, "mediatype": media_type, "media": media_url, "caption": caption}
        async with aiohttp.ClientSession() as session:
            async with session.post(url, json=payload, headers=headers) as resp:
                return await resp.json()

    async def send_bulk(self, instance_name: str, api_key: str, phones: list, message: str, delay_ms: int = 2000) -> list:
        results = []
        for phone in phones:
            result = await self.send_text(instance_name, api_key, phone, message)
            results.append({"phone": phone, "result": result})
        return results

    async def get_instance_status(self, instance_name: str) -> dict:
        cfg = self._get_config()
        url = f"{cfg['api_url']}/instance/connectionState/{instance_name}"
        headers = {"apikey": cfg["api_key"]}
        async with aiohttp.ClientSession() as session:
            async with session.get(url, headers=headers) as resp:
                return await resp.json()
