"""Webhook for the WhatsApp Cloud API. Registered only when WHATSAPP_ENABLED=true.

A patient texts the number linked to Cloud API; if their phone matches a Patient
row (set during web registration), we reply with their latest clinical summary.

TODO (phase 2, when this is actually activated): a caregiver's WhatsApp number
identifies the *account*, not a single patient — with multiple managed profiles
(see CaregiverLink) this needs the same "¿para quién es esto?" disambiguation
the email channel already handles (see app/processing/email_intake.py and
IntakeEvent.STATUS_AMBIGUOUS_PATIENT), e.g. a numbered quick-reply menu.
"""
from flask import Blueprint, request, current_app

from app.models import Patient
from app.whatsapp.whatsapp_client import send_text_message

whatsapp_bp = Blueprint("whatsapp", __name__, url_prefix="/whatsapp")

NOT_FOUND_REPLY = (
    "No encontramos tu número registrado. Crea tu cuenta gratis en la web de Memodoc "
    "con este mismo número de teléfono para poder consultar tu resumen médico por aquí."
)
NO_SUMMARY_REPLY = (
    "Aún no tenemos un resumen generado. Sube tus documentos médicos en la web y "
    "vuelve a escribirnos en unos minutos."
)


@whatsapp_bp.route("/webhook", methods=["GET"])
def verify_webhook():
    mode = request.args.get("hub.mode")
    token = request.args.get("hub.verify_token")
    challenge = request.args.get("hub.challenge", "")

    if mode == "subscribe" and token == current_app.config["WHATSAPP_VERIFY_TOKEN"]:
        return challenge, 200
    return "Forbidden", 403


@whatsapp_bp.route("/webhook", methods=["POST"])
def receive_webhook():
    payload = request.get_json(silent=True) or {}

    for entry in payload.get("entry", []):
        for change in entry.get("changes", []):
            for message in change.get("value", {}).get("messages", []):
                from_phone = message.get("from")
                if from_phone:
                    _handle_incoming_message(from_phone)

    return "OK", 200


def _handle_incoming_message(from_phone: str) -> None:
    patient = Patient.query.filter_by(phone=from_phone).first()
    if patient is None:
        send_text_message(from_phone, NOT_FOUND_REPLY)
        return

    summary = patient.latest_summary()
    if summary is None:
        send_text_message(from_phone, NO_SUMMARY_REPLY)
        return

    send_text_message(from_phone, summary.content)
