"""Webhook тест-сервер для проверки что RunBlob шлёт колбэки.

Запуск:
    pip install fastapi uvicorn
    python examples/webhook_server.py

Потом при генерации указываешь callback_url:
    await client.nanobanana.generate(
        prompt="A cat",
        callback_url="https://60b9-192-71-233-125.ngrok-free.app/webhook"
    )
"""
import json
import uvicorn
from datetime import datetime
from fastapi import FastAPI, Request, Header
from runblob import parse_webhook_payload, verify_webhook_signature

app = FastAPI()


@app.post("/webhook")
async def webhook_handler(
    request: Request,
    x_runblob_signature: str | None = Header(default=None),
):
    body = await request.body()
    data = json.loads(body)

    timestamp = datetime.now().strftime("%H:%M:%S")
    print(f"\n{'='*50}")
    print(f"[{timestamp}] Webhook received!")
    print(f"{'='*50}")
    print(f"Headers:")
    for k, v in request.headers.items():
        if k.startswith("x-"):
            print(f"  {k}: {v}")

    print(f"\nBody:")
    print(json.dumps(data, indent=2))

    event = parse_webhook_payload(data)
    print(f"\nParsed:")
    print(f"  task_uuid: {event.task_uuid}")
    print(f"  status:    {event.status}")
    if event.is_completed:
        print(f"  image_url: {event.result_image_url}")
    if event.is_failed:
        print(f"  error:     {event.message}")

    # Если настроен webhook secret — проверяем подпись
    # WEBHOOK_SECRET = "whsec_your_secret"
    # if x_runblob_signature:
    #     valid = verify_webhook_signature(body, x_runblob_signature, WEBHOOK_SECRET)
    #     print(f"  signature: {'valid' if valid else 'INVALID'}")

    print(f"{'='*50}\n")

    return {"ok": True}


@app.get("/")
async def health():
    return {"status": "webhook server running"}


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