"""Webhook notification for run completion events."""

import logging
from typing import Any

import httpx

from agenteval.config import get_settings

logger = logging.getLogger(__name__)


async def send_run_webhook(run_id: str, status: str, summary: dict[str, Any]) -> None:
    """POST run completion payload to the configured webhook URL.

    Silently logs and returns on any error — webhook failure must never
    affect the run itself.
    """
    settings = get_settings()
    if not settings.webhook_url:
        return

    payload = {
        "event": "run_completed",
        "run_id": run_id,
        "status": status,
        "summary": summary,
        "report_url": f"/api/reports/{run_id}",
    }

    headers = {"Content-Type": "application/json"}
    if settings.webhook_secret:
        headers["X-Webhook-Secret"] = settings.webhook_secret

    try:
        async with httpx.AsyncClient(timeout=10) as client:
            resp = await client.post(settings.webhook_url, json=payload, headers=headers)
        logger.info("webhook sent: run=%s status=%s http=%d", run_id, status, resp.status_code)
    except Exception as exc:
        logger.warning("webhook failed (non-fatal): run=%s error=%s", run_id, exc)
