"""Public contact / support enquiry handling — WhatsApp deep links and optional API notify."""
from __future__ import annotations

import logging
from typing import Any, Dict

from sqlalchemy.orm import Session

from app.core.config import settings

logger = logging.getLogger(__name__)


def contact_info() -> Dict[str, str]:
    wa = (getattr(settings, "cnp_contact_whatsapp", None) or settings.whatsapp_default_number or "26774818826")
    wa_digits = "".join(c for c in wa if c.isdigit())
    display = "+267 74 818 826"
    if len(wa_digits) >= 11:
        display = f"+{wa_digits[:3]} {wa_digits[3:5]} {wa_digits[5:8]} {wa_digits[8:]}"
    info_email = getattr(settings, "cnp_contact_email_info", None) or "info@cnpsolutions.co.bw"
    sales_email = getattr(settings, "cnp_contact_email_sales", None) or "sales@cnpsolutions.co.bw"
    return {
        "whatsapp_number": wa_digits,
        "whatsapp_display": display,
        "whatsapp_url": f"https://wa.me/{wa_digits}",
        "email_info": info_email,
        "email_sales": sales_email,
        "phone": f"+{wa_digits}",
        "company": "CNP Solutions",
    }


def _build_message(payload: Dict[str, Any]) -> str:
    lines = [
        f"Hello CNP Solutions,",
        "",
        f"*{payload.get('subject', 'Enquiry')}*",
        "",
        payload.get("message", ""),
        "",
        "—",
        f"Name: {payload.get('name')}",
        f"Email: {payload.get('email')}",
    ]
    if payload.get("phone"):
        lines.append(f"Phone: {payload.get('phone')}")
    lines.append(f"Sent via: {payload.get('source', 'CNPERP')}")
    return "\n".join(lines)


def _pick_email(subject: str) -> str:
    info = contact_info()
    s = (subject or "").lower()
    if any(k in s for k in ("support", "technical", "license", "bug", "error")):
        return info["email_info"]
    return info["email_sales"]


def process_contact_enquiry(db: Session, payload: Dict[str, Any]) -> Dict[str, Any]:
    info = contact_info()
    body_text = _build_message(payload)
    from urllib.parse import quote

    whatsapp_url = f"https://wa.me/{info['whatsapp_number']}?text={quote(body_text)}"
    email_to = _pick_email(payload.get("subject", ""))
    mailto_url = (
        f"mailto:{email_to}"
        f"?subject={quote('[CNPERP] ' + (payload.get('subject') or 'Enquiry'))}"
        f"&body={quote(body_text)}"
    )

    email_sent = False
    whatsapp_api_sent = False

    try:
        from app.services.email_service import EmailService

        if settings.smtp_host and settings.smtp_user:
            email_sent = EmailService().send_email(
                to_email=email_to,
                subject=f"[CNPERP Contact] {payload.get('subject')}",
                body_text=body_text + f"\n\nReply to: {payload.get('email')}",
            )
    except Exception as exc:
        logger.warning("Contact email not sent: %s", exc)

    try:
        from app.services.whatsapp_service import WhatsAppService

        svc = WhatsAppService(db)
        if svc.is_enabled():
            notify = (
                f"📩 *New CNPERP enquiry*\n\n{body_text}"
            )
            result = svc.send_business_document(
                phone_number=info["whatsapp_number"],
                message=notify,
            )
            whatsapp_api_sent = bool(result.get("success"))
    except Exception as exc:
        logger.debug("WhatsApp API notify skipped: %s", exc)

    logger.info(
        "Contact enquiry from %s <%s> subject=%s",
        payload.get("name"),
        payload.get("email"),
        payload.get("subject"),
    )

    channel = payload.get("preferred_channel", "whatsapp")
    msg = (
        "Thank you — open WhatsApp to send your message to our team."
        if channel == "whatsapp"
        else "Thank you — your email client will open with a draft to our team."
    )

    return {
        "success": True,
        "message": msg,
        "whatsapp_url": whatsapp_url,
        "mailto_url": mailto_url,
        "email_sent": email_sent,
        "whatsapp_api_sent": whatsapp_api_sent,
    }
