import json
import requests
from datetime import datetime
from .config_manager import ConfigManager
from .security import SecurityManager

class WhatsAppAPI:
    def __init__(self, config: ConfigManager, database, logger):
        self.config = config
        self.db = database
        self.logger = logger
        self.security = SecurityManager(config)

    def verify_webhook(self, params):
        mode = params.get("hub.mode")
        token = params.get("hub.verify_token")
        challenge = params.get("hub.challenge")
        if mode == "subscribe" and self.security.verify_token(token):
            self.logger.info("Webhook verification succeeded")
            return challenge or ""
        self.logger.warning("Webhook verification failed")
        return None

    def parse_webhook_payload(self, payload):
        data = payload or {}
        results = []
        entry_list = data.get("entry", [])
        for entry in entry_list:
            changes = entry.get("changes", [])
            for change in changes:
                value = change.get("value", {})
                messages = value.get("messages", [])
                contacts = value.get("contacts", [])
                for message in messages:
                    whatsapp_message_id = message.get("id")
                    phone = message.get("from")
                    timestamp = message.get("timestamp")
                    msg_text = self._extract_text(message)
                    contact_name = self._extract_contact_name(contacts)
                    if not whatsapp_message_id or not phone:
                        continue
                    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")
                    if self.db.message_exists(whatsapp_message_id):
                        self.logger.info(f"Duplicate WhatsApp message ignored: {whatsapp_message_id}")
                        continue
                    record_id = self.db.insert_whatsapp_message(
                        whatsapp_message_id, phone, contact_name, msg_text, received_at
                    )
                    results.append({
                        "id": record_id,
                        "whatsapp_message_id": whatsapp_message_id,
                        "phone": phone,
                        "contact_name": contact_name,
                        "message": msg_text,
                        "received_at": received_at,
                    })
        return results

    def _extract_contact_name(self, contacts):
        if not contacts:
            return ""
        first = contacts[0]
        profile = first.get("profile", {})
        return profile.get("name", "")

    def _extract_text(self, message):
        text_body = message.get("text", {}).get("body")
        if text_body:
            return text_body.strip()
        return message.get("interactive", {}).get("button_reply", {}).get("title", "") or ""

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

        api_version = self.config.get("WHATSAPP", "api_version", fallback="v20.0")
        phone_number_id = self.config.get("WHATSAPP", "phone_number_id")
        access_token = self.config.get("WHATSAPP", "access_token")
        endpoint = f"https://graph.facebook.com/{api_version}/{phone_number_id}/messages"
        headers = {
            "Authorization": f"Bearer {access_token}",
            "Content-Type": "application/json",
        }
        payload = {
            "messaging_product": "whatsapp",
            "to": phone,
            "type": "text",
            "text": {"body": text},
        }
        try:
            response = requests.post(endpoint, json=payload, headers=headers, timeout=15)
            response.raise_for_status()
            self.logger.info(f"WhatsApp response sent to {phone}")
            return response.json()
        except requests.RequestException as exc:
            self.logger.error(f"WhatsApp API error: {exc}")
            raise
