from contextlib import asynccontextmanager
from fastapi import FastAPI



from neonize.aioze.client import NewAClient
from neonize.aioze.events import MessageEv
from neonize.utils.jid import build_jid

whatsapp_client = NewAClient("meow.sqlite3")

@whatsapp_client.event(MessageEv)
async def on_message(client: NewAClient, event: MessageEv):
    if event.Message.conversation == "/api_status":
        await client.reply_message("API is running! ✅", event)

@asynccontextmanager
async def lifespan(app: FastAPI):
    # connect() automatically picks up the running event loop
    await whatsapp_client.connect()
    yield
    await whatsapp_client.disconnect()

app = FastAPI(lifespan=lifespan)

@app.get("/send")
async def send_message(phone: str, message: str):
    jid = build_jid(phone)
    await whatsapp_client.send_message(jid, message)
    return {"status": "sent"}


import uvicorn
if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8010)
