"""
Shared HTTP utilities for Outpost9 SDK.

Centralizes HTTP communication with the Worker to avoid duplication.
"""

import json
import os
import urllib.request
import urllib.error
from typing import Optional


# SDK version for User-Agent
SDK_VERSION = "0.0.1"

# Default timeout for HTTP requests
HTTP_TIMEOUT_SECONDS = 5


def notify_run_complete(run_id: str, status_code: int) -> None:
    """
    Notify the Worker that a request handler completed.

    This updates the run status in D1 to 'completed'.
    Called after both sync (JSON) and async (SSE) handlers finish.

    Args:
        run_id: The run ID from X-Run-Id header
        status_code: HTTP status code (200 for success, 500 for error)
    """
    log_url = os.environ.get("OUTPOST9_LOG_URL")
    agent_id = os.environ.get("OUTPOST9_AGENT_ID")
    internal_token = os.environ.get("OUTPOST9_INTERNAL_TOKEN")

    if not log_url or not agent_id or not run_id:
        return

    payload = json.dumps({
        "agentId": agent_id,
        "runId": run_id,
        "logs": [{
            "type": "system",
            "event": "run_complete",
            "metadata": {"statusCode": status_code},
        }],
    }).encode("utf-8")

    headers = {
        "Content-Type": "application/json",
        "User-Agent": f"Outpost9-SDK/{SDK_VERSION}",
    }
    if internal_token:
        headers["X-Internal-Token"] = internal_token

    req = urllib.request.Request(
        log_url,
        data=payload,
        headers=headers,
        method="POST",
    )

    try:
        with urllib.request.urlopen(req, timeout=HTTP_TIMEOUT_SECONDS) as resp:
            resp.read()
    except Exception:
        # Don't block on notification failures
        pass
