"""Webhook notification service."""

import httpx
import asyncio
from typing import Optional


async def send_webhook(
    url: str,
    payload: dict,
    max_retries: int = 3,
    timeout: float = 30.0
) -> dict:
    """
    Send a webhook notification with retry logic.

    Args:
        url: Webhook URL to send to
        payload: JSON payload to send
        max_retries: Maximum number of retry attempts
        timeout: Request timeout in seconds

    Returns:
        Dict with success status and any response/error info
    """
    if not url:
        return {"success": False, "error": "No webhook URL configured"}

    headers = {
        "Content-Type": "application/json",
        "User-Agent": "Whisper-Scribe/2.0"
    }

    last_error = None

    for attempt in range(max_retries):
        try:
            async with httpx.AsyncClient(timeout=timeout) as client:
                response = await client.post(url, json=payload, headers=headers)

                if response.status_code >= 200 and response.status_code < 300:
                    return {
                        "success": True,
                        "status_code": response.status_code,
                        "attempt": attempt + 1
                    }
                else:
                    last_error = f"HTTP {response.status_code}: {response.text[:200]}"

        except httpx.TimeoutException:
            last_error = f"Request timeout after {timeout}s"
        except httpx.RequestError as e:
            last_error = f"Request failed: {str(e)}"
        except Exception as e:
            last_error = f"Unexpected error: {str(e)}"

        # Exponential backoff before retry
        if attempt < max_retries - 1:
            await asyncio.sleep(2 ** attempt)

    return {
        "success": False,
        "error": last_error,
        "attempts": max_retries
    }


def send_webhook_sync(url: str, payload: dict) -> dict:
    """
    Synchronous wrapper for sending webhooks.
    Use this when calling from non-async context.
    """
    loop = None
    try:
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        return loop.run_until_complete(send_webhook(url, payload))
    except Exception as e:
        return {"success": False, "error": str(e)}
    finally:
        if loop is not None:
            loop.close()


def create_transcription_complete_payload(
    job_id: str,
    title: str,
    url: str,
    text: str,
    duration: Optional[str] = None,
    thumbnail: Optional[str] = None
) -> dict:
    """
    Create a standardized payload for transcription completion webhook.

    Args:
        job_id: The transcription job ID
        title: Video/audio title
        url: Source URL
        text: Transcription text
        duration: Optional duration string
        thumbnail: Optional thumbnail URL

    Returns:
        Dict payload for webhook
    """
    return {
        "event": "transcription.complete",
        "id": job_id,
        "title": title,
        "url": url,
        "text": text,
        "text_preview": text[:500] + "..." if len(text) > 500 else text,
        "text_length": len(text),
        "metadata": {
            "duration": duration,
            "thumbnail": thumbnail
        }
    }


def create_transcription_error_payload(
    job_id: str,
    url: str,
    error: str
) -> dict:
    """
    Create a payload for transcription error webhook.

    Args:
        job_id: The transcription job ID
        url: Source URL
        error: Error message

    Returns:
        Dict payload for webhook
    """
    return {
        "event": "transcription.error",
        "id": job_id,
        "url": url,
        "error": error
    }
