#!/usr/bin/env python3
"""Observable data loader: fetches /state/summary from the API."""
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("/")

try:
    with urllib.request.urlopen(f"{API_BASE}/state/summary", timeout=10) as resp:
        data = json.loads(resp.read())
    print(json.dumps(data))
except urllib.error.URLError as e:
    # Return empty structure so the dashboard can show an error state
    print(json.dumps({
        "error": str(e),
        "generated_at": None,
        "totals": {
            "topics": {"active": 0, "paused": 0, "archived": 0, "total": 0},
            "workstreams": {
                "proposed": 0,
                "ready": 0,
                "active": 0,
                "blocked": 0,
                "backlog": 0,
                "finished": 0,
                "archived": 0,
                "total": 0,
            },
            "tasks": {"wait": 0, "todo": 0, "progress": 0, "done": 0, "cancel": 0, "total": 0},
            "decisions": {"open": 0, "resolved": 0, "escalated": 0, "superseded": 0, "total": 0},
        },
        "topics": [],
        "blocking_decisions": [],
        "waiting_tasks": [],
        "blocked_tasks": [],
        "recent_progress": [],
        "open_workstreams": [],
    }))
