#!/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=('time-tools')
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.14#subdirectory=adapters/python'
fi
  $PIP_BIN install 'urirun-connector-time-tools @ git+https://github.com/if-uri/urirun-connector-time-tools.git@v0.1.2'
echo "Ensuring selected urirun runtime after connector package installs..."
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.14#subdirectory=adapters/python'
fi

REG_DIR="${IFURI_REGISTRY_DIR:-$HOME/.ifuri}"
WANT_PLANFILE=0
WANT_SQLITE_CONTEXT=0
WANT_DOMAIN_MONITOR=0
WANT_NAMECHEAP_DNS=0
WANT_GRPC_TRANSPORT=0
MODULES=('urirun_connector_time_tools')

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

if [ -n "${URIRUN_BIN:-}" ]; then
  read -r -a URIRUN_CMD <<< "$URIRUN_BIN"
else
  URIRUN_CMD=("$PYTHON_BIN" -m urirun.v2)
fi

echo
echo "installer urirun runtime:"
"${URIRUN_CMD[@]}" --help | head -5 || true

mkdir -p "$REG_DIR"
HOST_DB="${IFURI_HOST_DB:-$REG_DIR/host.db}"
PLANFILE_PROJECT="${IFURI_PLANFILE_PROJECT:-$REG_DIR/planfile-project}"
SCREENSHOT_DIR="${IFURI_SCREENSHOT_DIR:-$REG_DIR/screenshots}"
BINDING_FILES=()

if [ "${#MODULES[@]}" -gt 0 ]; then
  echo
  echo "Building bindings from connector packages..."
  $PYTHON_BIN - "$REG_DIR/connector-packages.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 - installer must not silently drop selected packages
        raise SystemExit(f"connector package import failed for {name}: {exc}") from exc
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
  BINDING_FILES+=("$REG_DIR/connector-packages.bindings.v2.json")
fi

if [ "$WANT_SQLITE_CONTEXT" = "1" ]; then
  echo "Building bundled sqlite-context bindings..."
  "${URIRUN_CMD[@]}" host data bindings --target host --db "$HOST_DB" --out "$REG_DIR/sqlite-context.bindings.v2.json"
  BINDING_FILES+=("$REG_DIR/sqlite-context.bindings.v2.json")
fi

if [ "$WANT_DOMAIN_MONITOR" = "1" ] || [ "$WANT_NAMECHEAP_DNS" = "1" ]; then
  echo "Building bundled domain/namecheap bindings..."
  mkdir -p "$PLANFILE_PROJECT" "$SCREENSHOT_DIR"
  "${URIRUN_CMD[@]}" host monitor bindings \
    --target host \
    --db "$HOST_DB" \
    --project "$PLANFILE_PROJECT" \
    --screenshot-dir "$SCREENSHOT_DIR" \
    --out "$REG_DIR/domain-monitor.bindings.v2.json"
  BINDING_FILES+=("$REG_DIR/domain-monitor.bindings.v2.json")
fi

if [ "$WANT_PLANFILE" = "1" ]; then
  echo "Building bundled planfile bindings..."
  mkdir -p "$PLANFILE_PROJECT"
  "${URIRUN_CMD[@]}" host task bindings --target host --project "$PLANFILE_PROJECT" --out "$REG_DIR/planfile.bindings.v2.json"
  BINDING_FILES+=("$REG_DIR/planfile.bindings.v2.json")
fi

if [ "$WANT_GRPC_TRANSPORT" = "1" ]; then
  echo "gRPC transport installed. Use: python3 -m urirun.v2_grpc serve <registry.json>"
fi

if [ "${#BINDING_FILES[@]}" -gt 0 ]; then
  echo
  echo "Compiling selected connector registry..."
  for file in "${BINDING_FILES[@]}"; do
    "${URIRUN_CMD[@]}" validate "$file"
  done
  "${URIRUN_CMD[@]}" compile "${BINDING_FILES[@]}" --out "$REG_DIR/connectors.registry.json" --on-conflict keep
  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
