import hashlib import hmac import logging from fastapi import APIRouter, Header, HTTPException, Request from app.config import settings from app.services.task_tracker import handle_webhook_completion logger = logging.getLogger(__name__) router = APIRouter(prefix='/api/v1', tags=['webhooks']) @router.post('/webhooks/task-complete') async def webhook_task_complete( request: Request, x_webhook_signature: str | None = Header(None), ): body = await request.body() if settings.webhook_secret: if not x_webhook_signature: raise HTTPException(status_code=401, detail='Missing webhook signature') expected = hmac.new( settings.webhook_secret.encode(), body, hashlib.sha256, ).hexdigest() if not hmac.compare_digest(expected, x_webhook_signature): raise HTTPException(status_code=401, detail='Invalid webhook signature') data = await request.json() task_id = data.get('task_id') or data.get('id') if not task_id: raise HTTPException(status_code=400, detail='Missing task_id in webhook payload') handle_webhook_completion(str(task_id), data) return {'status': 'ok'}