import os
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request, Query, BackgroundTasks
from fastapi.responses import PlainTextResponse
import httpx
from dotenv import load_dotenv

# Import database initialization and save method from database.py
from database import init_db, save_chat_message

load_dotenv()

VERIFY_TOKEN = os.getenv("VERIFY_TOKEN")
WHATSAPP_TOKEN = os.getenv("WHATSAPP_TOKEN")
PHONE_NUMBER_ID = os.getenv("PHONE_NUMBER_ID")

if not all([VERIFY_TOKEN, WHATSAPP_TOKEN, PHONE_NUMBER_ID]):
    print("⚠️ Warning: One or more WhatsApp environment variables are missing!")

WHATSAPP_API_URL = f"https://graph.facebook.com/v19.0/{PHONE_NUMBER_ID}/messages"

http_client: httpx.AsyncClient = None

@asynccontextmanager
async def lifespan(app: FastAPI):
    global http_client
    http_client = httpx.AsyncClient()
    # Call init_db from database.py on startup
    await init_db()
    yield
    await http_client.aclose()

app = FastAPI(lifespan=lifespan)


@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")
):
    if hub_mode == "subscribe" and hub_verify_token == VERIFY_TOKEN:
        return PlainTextResponse(content=hub_challenge, status_code=200)
    return PlainTextResponse(content="Verification failed", status_code=403)


# Helper task to save inbound message, send WhatsApp reply, and save outbound message
async def process_and_respond(sender_phone: str, user_text: str, wamid: str, sender_name: str):
    # 1. Call save_chat_message from database.py (INBOUND)
    await save_chat_message(
        direction="inbound",
        sender_phone=sender_phone,
        message_body=user_text,
        whatsapp_id=wamid,
        sender_name=sender_name
    )

    reply_text = f"You said: '{user_text}'"

    # 2. Send message via Meta API
    headers = {
        "Authorization": f"Bearer {WHATSAPP_TOKEN}",
        "Content-Type": "application/json"
    }
    payload = {
        "messaging_product": "whatsapp",
        "to": sender_phone,
        "type": "text",
        "text": {"body": reply_text}
    }

    try:
        response = await http_client.post(WHATSAPP_API_URL, json=payload, headers=headers)
        response.raise_for_status()
        res_data = response.json()
        outbound_wamid = res_data.get("messages", [{}])[0].get("id")

        # 3. Call save_chat_message from database.py (OUTBOUND)
        await save_chat_message(
            direction="outbound",
            sender_phone=sender_phone,
            message_body=reply_text,
            whatsapp_id=outbound_wamid
        )
    except httpx.HTTPError as err:
        print(f"Failed to send message: {err}")


@app.post("/webhook")
async def receive_message(request: Request, background_tasks: BackgroundTasks):
    data = await request.json()

    try:
        entry = data.get("entry", [{}])[0].get("changes", [{}])[0].get("value", {})

        if "messages" in entry:
            message = entry["messages"][0]
            sender_phone = message["from"]
            message_type = message.get("type")
            wamid = message.get("id")

            contacts = entry.get("contacts", [{}])[0]
            sender_name = contacts.get("profile", {}).get("name")

            if message_type == "text":
                user_text = message["text"]["body"]
                # Background task runs DB operations and message dispatch asynchronously
                background_tasks.add_task(
                    process_and_respond, sender_phone, user_text, wamid, sender_name
                )

    except Exception as e:
        print("Error processing webhook payload:", e)

    return {"status": "ok"}