"""
WhatsApp media handling: download incoming images, send product images.
"""
import base64
import logging
from typing import Optional, Tuple

import requests
from django.conf import settings

logger = logging.getLogger(__name__)

WA_BASE = "https://graph.facebook.com/v19.0"


def _headers():
    token = getattr(settings, "WHATSAPP_ACCESS_TOKEN", "")
    return {"Authorization": f"Bearer {token}"}


def download_whatsapp_image(media_id: str) -> Tuple[Optional[bytes], str]:
    """
    Download an image sent by the user on WhatsApp.
    Returns (image_bytes, mime_type) or (None, '').
    """
    try:
        # Step 1: get the download URL from the media ID
        resp = requests.get(
            f"{WA_BASE}/{media_id}",
            headers=_headers(),
            timeout=10,
        )
        resp.raise_for_status()
        info = resp.json()
        url = info.get("url", "")
        mime = info.get("mime_type", "image/jpeg")
        if not url:
            return None, ""

        # Step 2: download the actual bytes
        img_resp = requests.get(url, headers=_headers(), timeout=20)
        img_resp.raise_for_status()
        return img_resp.content, mime
    except Exception as exc:
        logger.error("WhatsApp image download failed (media_id=%s): %s", media_id, exc)
        return None, ""


def send_whatsapp_image(to: str, image_url: str, caption: str = "") -> bool:
    """
    Send a product image to a WhatsApp user by URL.
    Falls back silently if the URL is inaccessible.
    """
    phone_id = getattr(settings, "WHATSAPP_PHONE_ID", "")
    token = getattr(settings, "WHATSAPP_ACCESS_TOKEN", "")
    if not phone_id or not token or not image_url:
        return False

    payload = {
        "messaging_product": "whatsapp",
        "recipient_type": "individual",
        "to": to,
        "type": "image",
        "image": {
            "link": image_url,
            "caption": caption[:1024] if caption else "",
        },
    }
    try:
        resp = requests.post(
            f"{WA_BASE}/{phone_id}/messages",
            headers={**_headers(), "Content-Type": "application/json"},
            json=payload,
            timeout=15,
        )
        if not resp.ok:
            logger.error(
                "WhatsApp image send error %s for url=%s: %s",
                resp.status_code,
                image_url[:120],
                resp.text[:300],
            )
        return resp.ok
    except Exception as exc:
        logger.error("WhatsApp image send failed: %s", exc)
        return False


def send_whatsapp_text(to: str, text: str) -> bool:
    """Send a plain text message (reused from views for modularity)."""
    phone_id = getattr(settings, "WHATSAPP_PHONE_ID", "")
    token = getattr(settings, "WHATSAPP_ACCESS_TOKEN", "")
    if not phone_id or not token:
        return False

    chunks = [text[i:i + 4000] for i in range(0, len(text), 4000)]
    for chunk in chunks:
        payload = {
            "messaging_product": "whatsapp",
            "recipient_type": "individual",
            "to": to,
            "type": "text",
            "text": {"preview_url": False, "body": chunk},
        }
        try:
            resp = requests.post(
                f"{WA_BASE}/{phone_id}/messages",
                headers={**_headers(), "Content-Type": "application/json"},
                json=payload,
                timeout=15,
            )
            if not resp.ok:
                logger.error("WhatsApp text send error %s: %s", resp.status_code, resp.text[:200])
                return False
        except Exception as exc:
            logger.error("WhatsApp send failed: %s", exc)
            return False
    return True


def send_whatsapp_list(
    to: str,
    body_text: str,
    button_text: str,
    rows: list,
    header_text: str = "",
    footer_text: str = "",
) -> bool:
    """
    Send an interactive list so user can tap an option.
    rows format: [{"id": "...", "title": "...", "description": "..."}]
    """
    phone_id = getattr(settings, "WHATSAPP_PHONE_ID", "")
    token = getattr(settings, "WHATSAPP_ACCESS_TOKEN", "")
    if not phone_id or not token or not rows:
        return False

    # WhatsApp list limits: max 10 rows, title <= 24 chars.
    safe_rows = []
    for r in rows[:10]:
        rid = str(r.get("id", "")).strip()
        title = str(r.get("title", "")).strip()[:24]
        desc = str(r.get("description", "")).strip()[:72]
        if not rid or not title:
            continue
        row = {"id": rid, "title": title}
        if desc:
            row["description"] = desc
        safe_rows.append(row)
    if not safe_rows:
        return False

    payload = {
        "messaging_product": "whatsapp",
        "recipient_type": "individual",
        "to": to,
        "type": "interactive",
        "interactive": {
            "type": "list",
            "body": {"text": body_text[:1024]},
            "action": {
                "button": button_text[:20] or "Select",
                "sections": [{"title": "Available items", "rows": safe_rows}],
            },
        },
    }
    if header_text:
        payload["interactive"]["header"] = {"type": "text", "text": header_text[:60]}
    if footer_text:
        payload["interactive"]["footer"] = {"text": footer_text[:60]}

    try:
        resp = requests.post(
            f"{WA_BASE}/{phone_id}/messages",
            headers={**_headers(), "Content-Type": "application/json"},
            json=payload,
            timeout=15,
        )
        if not resp.ok:
            logger.error("WhatsApp list send error %s: %s", resp.status_code, resp.text[:300])
        return resp.ok
    except Exception as exc:
        logger.error("WhatsApp list send failed: %s", exc)
        return False