import requests
from datetime import datetime
from pathlib import Path
from .config_manager import ConfigManager


class TelegramAPI:
    def __init__(self, config: ConfigManager, database, logger):
        self.config = config
        self.db = database
        self.logger = logger

    def check_secret_token(self, received_token):
        expected_token = self.config.get("TELEGRAM", "webhook_secret_token", fallback="")
        if not expected_token:
            return True
        return received_token == expected_token

    def parse_webhook_payload(self, payload):
        data = payload or {}
        message = data.get("message") or data.get("edited_message") or {}
        if not message:
            return []

        message_id = message.get("message_id")
        chat = message.get("chat", {})
        sender = message.get("from", {})
        chat_id = chat.get("id")
        text = self._extract_text(message)
        client_phone = self._extract_contact_phone(message)
        attachment = self._download_photo(message, chat_id, message_id)
        if not message_id or not chat_id or (not text and not client_phone and not attachment):
            return []

        telegram_message_id = f"telegram-{chat_id}-{message_id}"
        if self.db.message_exists(telegram_message_id):
            self.logger.info(f"Duplicate Telegram message ignored: {telegram_message_id}")
            return []

        timestamp = message.get("date")
        received_at = (
            datetime.utcfromtimestamp(int(timestamp)).strftime("%Y-%m-%d %H:%M:%S")
            if timestamp
            else datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
        )
        contact_name = self._format_contact_name(sender)
        if client_phone and not text:
            text = f"Contact partage depuis Telegram. Telephone: {client_phone}"
        if attachment and not text:
            text = "Photo envoyee par le client."
        attachment = attachment or {}
        record_id = self.db.insert_support_request(
            source="telegram",
            external_id=telegram_message_id,
            requester_contact=str(chat_id),
            contact_name=contact_name,
            message=text,
            received_at=received_at,
            subject="Message Telegram",
            attachment_path=attachment.get("path", ""),
            attachment_url=attachment.get("url", ""),
        )
        return [{
            "id": record_id,
            "whatsapp_message_id": telegram_message_id,
            "source": "telegram",
            "subject": "Message Telegram",
            "phone": str(chat_id),
            "contact_name": contact_name,
            "client_phone": client_phone,
            "attachment_path": attachment.get("path", ""),
            "attachment_url": attachment.get("url", ""),
            "message": text,
            "received_at": received_at,
        }]

    def send_text_message(self, chat_id, text):
        if not chat_id or not text:
            raise ValueError("Telegram chat_id and text message are required")
        if self.config.getboolean("APP", "mock_mode", fallback=False):
            self.logger.info(f"MOCK_MODE: send Telegram message to {chat_id}: {text}")
            return {"status": "mocked", "message": text}

        bot_token = self.config.get("TELEGRAM", "bot_token")
        endpoint = f"https://api.telegram.org/bot{bot_token}/sendMessage"
        payload = {
            "chat_id": chat_id,
            "text": text,
        }
        try:
            response = requests.post(endpoint, json=payload, timeout=15)
            response.raise_for_status()
            self.logger.info(f"Telegram response sent to {chat_id}")
            return response.json()
        except requests.RequestException as exc:
            self.logger.error(f"Telegram API error: {exc}")
            raise

    def _extract_text(self, message):
        text = message.get("text") or message.get("caption") or ""
        return text.strip()

    def _extract_contact_phone(self, message):
        contact = message.get("contact") or {}
        return (contact.get("phone_number") or "").strip()

    def _download_photo(self, message, chat_id, message_id):
        photos = message.get("photo") or []
        if not photos:
            return None
        best_photo = photos[-1]
        file_id = best_photo.get("file_id")
        if not file_id:
            return None

        bot_token = self.config.get("TELEGRAM", "bot_token")
        if not bot_token or bot_token == "XXXXX":
            self.logger.warning("Photo Telegram ignoree: TELEGRAM.bot_token manquant")
            return None

        try:
            file_info = requests.get(
                f"https://api.telegram.org/bot{bot_token}/getFile",
                params={"file_id": file_id},
                timeout=15,
            )
            file_info.raise_for_status()
            file_path = file_info.json().get("result", {}).get("file_path")
            if not file_path:
                return None

            extension = Path(file_path).suffix or ".jpg"
            attachments_dir = self.config.project_root / "data" / "attachments"
            attachments_dir.mkdir(parents=True, exist_ok=True)
            filename = f"telegram_{chat_id}_{message_id}{extension}"
            local_path = attachments_dir / filename

            download = requests.get(f"https://api.telegram.org/file/bot{bot_token}/{file_path}", timeout=30)
            download.raise_for_status()
            local_path.write_bytes(download.content)

            public_base_url = self.config.get("APP", "public_base_url", fallback="").rstrip("/")
            attachment_url = f"{public_base_url}/attachments/{filename}" if public_base_url else ""
            self.logger.info(f"Photo Telegram enregistree: {local_path}")
            return {
                "path": str(local_path),
                "url": attachment_url,
            }
        except requests.RequestException as exc:
            self.logger.error(f"Erreur telechargement photo Telegram: {exc}")
            return None

    def _format_contact_name(self, sender):
        parts = [sender.get("first_name", ""), sender.get("last_name", "")]
        name = " ".join(part for part in parts if part).strip()
        username = sender.get("username")
        if username and name:
            return f"{name} (@{username})"
        if username:
            return f"@{username}"
        return name
