#!/usr/bin/env python3
"""Observable data loader: fetches a single repo by slug."""
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("/")

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

if not slug:
    print(json.dumps({"error": "No repo slug provided"}))
    sys.exit(1)

try:
    with urllib.request.urlopen(f"{API_BASE}/repos/{slug}/", 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"Repo {slug!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)
