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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REGISTRY_TOOL="${SCRIPT_DIR}/instance-registry.py"
REGISTRY_PATH_DEFAULT="${SCRIPT_DIR}/runtime/registry/instances.json"
REGISTRY_PATH="${REGISTRY_PATH:-$REGISTRY_PATH_DEFAULT}"
JSON_OUTPUT=0

usage() {
  cat <<'EOF'
Usage:
  ./list-instances.sh [--json] [--registry <path>]
EOF
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --json)
      JSON_OUTPUT=1
      shift
      ;;
    --registry)
      REGISTRY_PATH="${2:-}"
      shift 2
      ;;
    --help|-h)
      usage
      exit 0
      ;;
    *)
      printf '[list-instances] unknown argument: %s\n' "$1" >&2
      exit 1
      ;;
  esac
done

if [[ "$JSON_OUTPUT" -eq 1 ]]; then
  python3 - <<'PY' "$REGISTRY_TOOL" "$REGISTRY_PATH"
import json
import subprocess
import sys

tool = sys.argv[1]
registry = sys.argv[2]
raw = subprocess.check_output([tool, "--registry", registry, "list", "--json"], text=True)
data = json.loads(raw)

for item in data.get("instances", []):
    container = item.get("container_name", "")
    try:
        status = subprocess.check_output(
            ["docker", "inspect", "-f", "{{.State.Status}}", container],
            text=True,
            stderr=subprocess.DEVNULL,
        ).strip()
    except subprocess.CalledProcessError:
        status = "missing"
    item["docker_status"] = status

json.dump(data, sys.stdout, indent=2, ensure_ascii=False)
sys.stdout.write("\n")
PY
  exit 0
fi

python3 - <<'PY' "$REGISTRY_TOOL" "$REGISTRY_PATH"
import json
import subprocess
import sys

tool = sys.argv[1]
registry = sys.argv[2]
raw = subprocess.check_output([tool, "--registry", registry, "list", "--json"], text=True)
data = json.loads(raw)
items = data.get("instances", [])

headers = ["INSTANCE_ID", "USERNAME", "HOST", "SLUG", "STATUS", "PORT", "CONTAINER", "PUBLIC_URL"]
rows = [headers]

for item in items:
    container = item.get("container_name", "")
    try:
        status = subprocess.check_output(
            ["docker", "inspect", "-f", "{{.State.Status}}", container],
            text=True,
            stderr=subprocess.DEVNULL,
        ).strip()
    except subprocess.CalledProcessError:
        status = "missing"

    rows.append(
        [
            str(item.get("instance_id", "")),
            str(item.get("username", "")),
            str(item.get("instance_host", "")),
            str(item.get("instance_slug", "")),
            status,
            str(item.get("host_port", "")),
            container,
            str(item.get("public_url", "")),
        ]
    )

widths = [max(len(row[idx]) for row in rows) for idx in range(len(headers))]
for row in rows:
    print("  ".join(value.ljust(widths[idx]) for idx, value in enumerate(row)))
PY
