import os
from fastapi import FastAPI, Request, Response, Query
import httpx

app = FastAPI()

# Meta Credentials (Replace with your actual keys or use environment variables)
VERIFY_TOKEN = os.getenv("VERIFY_TOKEN", "my_secret_verify_token")
WHATSAPP_TOKEN = os.getenv("WHATSAPP_TOKEN", "YOUR_TEMPORARY_OR_PERMANENT_ACCESS_TOKEN")
PHONE_NUMBER_ID = os.getenv("PHONE_NUMBER_ID", "YOUR_PHONE_NUMBER_ID")

WHATSAPP_API_URL = f"https://graph.facebook.com/v19.0/{PHONE_NUMBER_ID}/messages"

@app.get("/webhook")
async def verify_webhook(
    hub_mode: str = Query(None, alias="hub.mode"),
    hub_challenge: str = Query(None, alias="hub.challenge"),
    hub_verify_token: str = Query(None, alias="hub.verify_token")
):
    """ Meta calls this to verify your webhook subscription. """
    if hub_mode == "subscribe" and hub_verify_token == VERIFY_TOKEN:
        return Response(content=hub_challenge, status_code=200)
    return Response(content="Verification failed", status_code=403)

@app.post("/webhook")
async def receive_message(request: Request):
    """ Meta posts incoming messages to this endpoint. """
    data = await request.json()

    try:
        # Extract incoming message details from Meta payload structure
        entry = data["entry"][0]["changes"][0]["value"]
        if "messages" in entry:
            message = entry["messages"][0]
            sender_phone = message["from"]  # User's phone number
            message_type = message.get("type")

            if message_type == "text":
                user_text = message["text"]["body"]
                
                # Echo back a response (or process with your logic/LLM)
                reply_text = f"You said: '{user_text}'"
                await send_whatsapp_message(sender_phone, reply_text)

    except Exception as e:
        print("Error processing webhook payload:", e)

    # Meta expects a fast 200 OK response
    return {"status": "ok"}

async def send_whatsapp_message(to_phone: str, text: str):
    """ Helper function to send a message back to the user via WhatsApp API. """
    headers = {
        "Authorization": f"Bearer {WHATSAPP_TOKEN}",
        "Content-Type": "application/json"
    }
    payload = {
        "messaging_product": "whatsapp",
        "to": to_phone,
        "type": "text",
        "text": {"body": text}
    }

    async with httpx.AsyncClient() as client:
        response = await client.post(WHATSAPP_API_URL, json=payload, headers=headers)
        print(f"Sent status: {response.status_code}, Response: {response.json()}")