import json
import requests
from django.conf import settings
from typing import Optional

import re

def normalize_phone(number: str) -> str:
    """Normalize phone to digits-only international format (best-effort).

    - Keeps digits only
    - If looks like Nigerian local (0XXXXXXXXXX), converts to 234XXXXXXXXXX
    """
    if not number:
        return ""
    digits = re.sub(r"\D", "", str(number))
    if digits.startswith("0") and len(digits) == 11:
        digits = "234" + digits[1:]
    return digits


def _parse_rules():
    rules = {}
    raw = getattr(settings, "WHATSAPP_ROUTING_RULES", "") or ""
    for part in raw.split(","):
        part = part.strip()
        if not part or "=" not in part:
            continue
        k, v = part.split("=", 1)
        rules[k.strip()] = v.strip()
    return rules

def route_number(enquiry_type: str) -> str:
    rules = _parse_rules()
    return rules.get(enquiry_type, getattr(settings, "WHATSAPP_DEFAULT_ROUTE", ""))

def send_whatsapp_text(to_number: str, text: str) -> Optional[dict]:
    token = getattr(settings, "WHATSAPP_CLOUD_TOKEN", "") or ""
    phone_id = getattr(settings, "WHATSAPP_PHONE_NUMBER_ID", "") or ""
    if not token or not phone_id or not to_number:
        return None

    # WhatsApp Cloud API expects E.164 without '+' in wa.me; but Cloud uses phone format.
    # We'll keep the number as digits with optional '+' and let Meta validate.
    url = f"https://graph.facebook.com/v19.0/{phone_id}/messages"
    headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
    
    payload = {
    "messaging_product": "whatsapp",
    "to": normalize_phone(to_number),
    "type": "text",
    "text": {"body": text[:4096]},
}
    # payload = {
    #     "messaging_product": "whatsapp",
    #     "to": normalize_phone(to_number),
    #     "type": "text",
    #     "text": {"body": text[:4096]},
    # }
    try:
        r = requests.post(url, headers=headers, data=json.dumps(payload), timeout=15)
        try:
            return r.json()
        except Exception:
            return {"status_code": r.status_code, "text": r.text}
    except Exception as e:
        return {"error": str(e)}