| from fastapi import APIRouter, Request, HTTPException, Query |
| from fastapi.responses import PlainTextResponse, JSONResponse |
| from pydantic import BaseModel |
| from typing import Optional |
| from datetime import datetime |
|
|
| from config import VERIFY_TOKEN, supabase, OPENAI_API_KEY, WHATSAPP_API_TOKEN |
| from database import get_user, list_users, update_user_name |
| from ai_chat import process_message |
|
|
| router = APIRouter() |
|
|
| |
| @router.get("/webhook") |
| def verify_webhook( |
| hub_mode: str = Query(None, alias="hub.mode"), |
| hub_token: str = Query(None, alias="hub.verify_token"), |
| hub_challenge: str = Query(None, alias="hub.challenge") |
| ): |
| if hub_mode == "subscribe" and hub_token == VERIFY_TOKEN: |
| return PlainTextResponse(hub_challenge) |
| raise HTTPException(status_code=403, detail="Invalid token") |
|
|
| |
| class ChatRequest(BaseModel): |
| message: str |
| model: Optional[str] = "gpt-4o-mini" |
| max_tokens: Optional[int] = 1500 |
|
|
| class ChatResponse(BaseModel): |
| response: str |
| model: str |
| tokens_used: Optional[int] = None |
|
|
| @router.post("/chat", response_model=ChatResponse) |
| async def chat_with_ai(request: ChatRequest): |
| response = await process_message(request.message) |
| return ChatResponse(response=response, model=request.model) |
|
|
| |
| @router.get("/ping") |
| def ping(): |
| return {"pong": True} |
|
|
| @router.get("/health") |
| def health_check(): |
| status = { |
| "api": "healthy", |
| "whatsapp": "configured" if WHATSAPP_API_TOKEN else "not configured", |
| "openai": "configured" if OPENAI_API_KEY else "not configured", |
| "supabase": "configured" if supabase else "not configured" |
| } |
| return status |
|
|
| |
| @router.get("/users/{wa_id}") |
| async def get_user_endpoint(wa_id: str): |
| """Get user by WhatsApp ID""" |
| if not supabase: |
| raise HTTPException(status_code=503, detail="Database not configured") |
| |
| user = await get_user(wa_id) |
| if user: |
| return user |
| else: |
| raise HTTPException(status_code=404, detail="User not found") |
|
|
| @router.get("/users") |
| async def list_users_endpoint(limit: int = 50, offset: int = 0): |
| """List all users with pagination""" |
| if not supabase: |
| raise HTTPException(status_code=503, detail="Database not configured") |
| |
| result = await list_users(limit, offset) |
| return result |
|
|
| @router.put("/users/{wa_id}") |
| async def update_user_endpoint(wa_id: str, name: str): |
| """Update user name""" |
| if not supabase: |
| raise HTTPException(status_code=503, detail="Database not configured") |
| |
| user = await update_user_name(wa_id, name) |
| if user: |
| return user |
| else: |
| raise HTTPException(status_code=404, detail="User not found") |