#!/usr/bin/env python3
"""Observable data loader: runs gitea_inventory.py and returns JSON output."""
import json
import os
import subprocess
import sys

SCRIPTS_DIR = os.path.join(os.path.dirname(__file__), "..", "..", "..", "scripts")
SCRIPTS_DIR = os.path.normpath(SCRIPTS_DIR)
PYTHON = os.path.join(os.path.dirname(sys.executable), "python")
if not os.path.exists(PYTHON):
    PYTHON = sys.executable

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

try:
    result = subprocess.run(
        [PYTHON, os.path.join(SCRIPTS_DIR, "gitea_inventory.py"), "--json",
         "--api-base", API_BASE],
        capture_output=True, text=True, timeout=30,
    )
    if result.returncode == 0 and result.stdout.strip():
        print(result.stdout)
    else:
        print(json.dumps({
            "error": result.stderr or "empty output",
            "registered": [], "unregistered": [], "hub_only": [],
        }))
except Exception as exc:
    print(json.dumps({
        "error": str(exc),
        "registered": [], "unregistered": [], "hub_only": [],
    }))
