#!/usr/bin/env python3
"""UOCL Loop Start v1 — CURRENT Ride Start inbound example.

Replace YOUR_API_KEY. Never commit real secrets.
"""

from __future__ import annotations

import json
import os
import sys
import urllib.error
import urllib.request

API_KEY = os.environ.get("UOCL_API_KEY", "YOUR_API_KEY")
ENDPOINT = os.environ.get(
    "UOCL_LOOP_START_URL",
    "https://flows.mmdirect-n8n.com/webhook/ride-start",
)

payload = {
    "hubspot_deal_id": "TEST_DEAL_123",
    "source": "docs_python_example",
    "title": "Ride Confirmation",
    "instructions": "Please review the trip and complete the driver fields.",
    "submitLabel": "Submit Ride",
    "booking": {
        "name": "Jane Smith",
        "email": "jane@example.com",
    },
    "fields": [
        {
            "name": "name",
            "label": "Name",
            "type": "text",
            "value": "Jane Smith",
            "editable": False,
        },
        {
            "name": "driver_name",
            "label": "Driver Name",
            "type": "text",
            "value": "",
            "editable": True,
        },
    ],
}

req = urllib.request.Request(
    ENDPOINT,
    data=json.dumps(payload).encode("utf-8"),
    headers={
        "Content-Type": "application/json",
        "x-api-key": API_KEY,
    },
    method="POST",
)

try:
    with urllib.request.urlopen(req, timeout=60) as resp:
        body = json.loads(resp.read().decode("utf-8"))
except urllib.error.HTTPError as exc:
    err_body = exc.read().decode("utf-8", errors="replace")
    print(f"HTTP {exc.code}: {err_body}", file=sys.stderr)
    sys.exit(1)

if not body.get("ok"):
    print(json.dumps(body, indent=2), file=sys.stderr)
    sys.exit(1)

print(
    json.dumps(
        {
            "token": body.get("token"),
            "ride_url": body.get("ride_url"),
            "qr_png_url": body.get("qr_png_url"),
        },
        indent=2,
    )
)
