"""HTTP client for the Relayway API."""
import json
from typing import Any, Dict

import requests

from .config import API_KEY, BASE_URL


class RelayWayError(RuntimeError):
    """Raised when the Relayway API returns an error."""


def enqueue_job(payload: Dict[str, Any], origin: str) -> Dict[str, Any]:
    """Enqueue a background job to the Relayway API."""
    task_data = {
        "payload": payload,
        "origin": origin,
        "language": "python",
        "status": "pending",
    }

    try:
        json.dumps(task_data)
    except (TypeError, ValueError) as exc:
        raise ValueError("Job payload must be JSON serializable") from exc

    headers = {"Content-Type": "application/json"}
    if API_KEY:
        headers["X-API-Key"] = API_KEY

    response = requests.post(
        f"{BASE_URL.rstrip('/')}/api/v1/tasks/create-task",
        json=task_data,
        headers=headers,
        timeout=10
    )

    if response.status_code >= 400:
        raise RelayWayError(f"Relayway API error: {response.status_code} {response.text}")

    return response.json()
