#!/usr/bin/env python3
"""Observable data loader: fetches a single workstream by ID."""
import json
import os
import sys
import urllib.request
import urllib.error

API_BASE = os.environ.get("API_BASE", "http://127.0.0.1:8000").rstrip("/")

ws_id = sys.argv[1] if len(sys.argv) > 1 else ""

if not ws_id:
    print(json.dumps({"error": "No workstream ID provided"}))
    sys.exit(1)

try:
    with urllib.request.urlopen(f"{API_BASE}/workstreams/{ws_id}", timeout=10) as resp:
        data = json.loads(resp.read())
    print(json.dumps(data))
except urllib.error.HTTPError as e:
    if e.code == 404:
        print(json.dumps({"error": f"Workstream {ws_id!r} not found"}))
        sys.exit(1)
    print(json.dumps({"error": f"HTTP {e.code}: {e.reason}"}))
    sys.exit(1)
except urllib.error.URLError as e:
    print(json.dumps({"error": str(e)}))
    sys.exit(1)
