import os
from flask import Flask, request, abort, Response
from dotenv import load_dotenv
from twilio.request_validator import RequestValidator
from twilio.twiml.messaging_response import MessagingResponse

load_dotenv()

app = Flask(__name__)

twilio_auth_token = os.environ["TWILIO_AUTH_TOKEN"]
public_webhook_url = os.environ["PUBLIC_WEBHOOK_URL"]

validator = RequestValidator(twilio_auth_token)


@app.post("/whatsapp")
def whatsapp_webhook():
    signature = request.headers.get("X-Twilio-Signature", "")

    is_valid = validator.validate(
        public_webhook_url,
        request.form.to_dict(),
        signature
    )

    if not is_valid:
        print("Firma inválida. Request rechazado.")
        abort(403)

    incoming_message = request.form.get("Body", "")
    sender = request.form.get("From", "")

    print("Mensaje recibido desde WhatsApp")
    print("De:", sender)
    print("Texto:", incoming_message)

    response = MessagingResponse()
    response.message(f"Hola. Recibí tu mensaje: {incoming_message}")

    return Response(str(response), mimetype="text/xml")


if __name__ == "__main__":
    app.run(port=3000, debug=True)
