#!/usr/bin/env bash
set -euo pipefail

if ! command -v python3 >/dev/null 2>&1; then
  echo "python3 is required" >&2
  exit 1
fi

PYTHON_BIN="${PYTHON_BIN:-python3}"
PIP_BIN="${PIP_BIN:-$PYTHON_BIN -m pip}"

if ! $PYTHON_BIN -m pip --version >/dev/null 2>&1; then
  echo "python3 -m pip is required" >&2
  exit 1
fi

CONNECTORS=('http-check')
echo "Installing ifuri connectors: ${CONNECTORS[*]}"
if [ -n "${URIRUN_PIP_SPEC:-}" ]; then
  $PIP_BIN install "$URIRUN_PIP_SPEC"
else
  $PIP_BIN install 'urirun @ git+https://github.com/tellmesh/urirun.git@v0.3.13#subdirectory=adapters/python'
fi
  $PIP_BIN install 'urirun-connector-http-check @ git+https://github.com/if-uri/urirun-connector-http-check.git@v0.1.4'

REG_DIR="${IFURI_REGISTRY_DIR:-$HOME/.ifuri}"
MODULES=('urirun_connector_http_check')

if command -v urirun >/dev/null 2>&1; then
  echo
  echo "urirun installed:"
  urirun --help | head -5 || true
fi

mkdir -p "$REG_DIR"
if [ "${#MODULES[@]}" -gt 0 ]; then
  echo
  echo "Building a urirun registry from the installed connectors..."
  $PYTHON_BIN - "$REG_DIR/connectors.bindings.v2.json" "${MODULES[@]}" <<'PY'
import importlib, json, sys
import urirun

out = sys.argv[1]
for name in sys.argv[2:]:
    try:
        importlib.import_module(name)  # registers the package's connector-declared URI routes
    except Exception as exc:  # noqa: BLE001 - skip a connector that failed to install
        print(f"  skip {name}: {exc}", file=sys.stderr)
doc = urirun.connector_bindings()  # all routes registered by the imported connectors
with open(out, "w", encoding="utf-8") as fh:
    json.dump(doc, fh, indent=2)
print(f"  bindings: {len(doc.get('bindings', {}))} route(s) -> {out}")
PY
  urirun validate "$REG_DIR/connectors.bindings.v2.json"
  urirun compile "$REG_DIR/connectors.bindings.v2.json" --out "$REG_DIR/connectors.registry.json"
  echo "  registry: $REG_DIR/connectors.registry.json"
  echo
  echo "Run a connector route:"
  echo "  ifuri-app urirun-call <uri> --registry $REG_DIR/connectors.registry.json --execute"
  echo "  urirun run <uri> $REG_DIR/connectors.registry.json --execute --allow '<scheme>://*'"
else
  echo
  echo "No installable connectors selected (planned connectors have no package yet)."
fi
