import httpx
from typing import Optional, Dict, Any
from app.services.base_service import SocialMediaService


class TelegramService(SocialMediaService):
    """
    Telegram Bot API service.
    Credentials: api_key = Bot Token, extra = Chat ID
    """
    platform_name = "telegram"

    def validate_credentials(self) -> bool:
        return bool(self.credentials.get("api_key") and self.credentials.get("extra"))

    def post(self, content: str, media_path: Optional[str] = None) -> Dict[str, Any]:
        bot_token = self.credentials.get("api_key", "")
        chat_id = self.credentials.get("extra", "")

        if not bot_token or not chat_id:
            return self._error("Missing bot token or chat ID")

        try:
            base_url = f"https://api.telegram.org/bot{bot_token}"

            if media_path:
                # Send photo with caption
                with open(media_path, "rb") as photo:
                    resp = httpx.post(
                        f"{base_url}/sendPhoto",
                        data={"chat_id": chat_id, "caption": content},
                        files={"photo": photo},
                        timeout=30,
                    )
            else:
                resp = httpx.post(
                    f"{base_url}/sendMessage",
                    json={"chat_id": chat_id, "text": content, "parse_mode": "Markdown"},
                    timeout=30,
                )

            data = resp.json()
            if data.get("ok"):
                return self._success("Message sent to Telegram successfully", data)
            else:
                return self._error(f"Telegram API error: {data.get('description', 'Unknown error')}")

        except Exception as e:
            return self._error(f"Telegram connection error: {str(e)}")
