#!/usr/bin/env bash
# fleet/gen-inventory.sh — regenerate fleet/inventory.yml from the single
# source of host identity, ~/.claude/buildbox-hosts.json. Never hand-edit
# host IPs into inventory.yml; edit the registry and re-run this.
set -euo pipefail

FLEET_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REGISTRY="${BUILDBOX_HOSTS_JSON:-$HOME/.claude/buildbox-hosts.json}"

[[ -f "$REGISTRY" ]] || { echo "fleet/gen-inventory.sh: ERROR: registry not found at $REGISTRY" >&2; exit 1; }

python3 - "$REGISTRY" "$FLEET_DIR/inventory.yml" <<'PY'
import json, sys

registry_path, out_path = sys.argv[1], sys.argv[2]
with open(registry_path) as f:
    registry = json.load(f)

lines = [
    "all:",
    "  vars:",
    "    # deploy_root is where each machine's live overdeck checkout lives —",
    "    # the source PATH bins and ~/.claude symlinks resolve into.",
    "    deploy_root: \"{{ ansible_env.HOME }}/.local/share/overdeck/deploy\"",
    "  hosts:",
    "    laptop:",
    "      ansible_connection: local",
    "      ansible_python_interpreter: \"{{ ansible_playbook_python }}\"",
]

buildbox_names = []
skipped = []
for host in registry.get("hosts", []):
    name = host["name"]
    if host.get("state") != "reachable":
        skipped.append((name, host.get("state")))
        continue
    ts = host.get("access", {}).get("tailscale_ip")
    if not ts:
        skipped.append((name, "no tailscale_ip access door"))
        continue
    buildbox_names.append(name)
    lines += [
        f"    {name}:",
        f"      ansible_host: {ts['host']}",
        f"      ansible_port: {ts['port']}",
        f"      ansible_user: {ts['user']}",
        f"      ansible_ssh_private_key_file: {ts['identity_file']}",
        "      ansible_python_interpreter: /usr/bin/python3",
    ]

lines += [
    "  children:",
    "    buildboxes:",
    "      hosts:",
]
for name in buildbox_names:
    lines.append(f"        {name}: {{}}")
lines += [
    "    workstations:",
    "      hosts:",
    "        laptop: {}",
]

with open(out_path, "w") as f:
    f.write("\n".join(lines) + "\n")

print(f"wrote {out_path}: {len(buildbox_names)} buildbox(es) from registry — {buildbox_names}")
if skipped:
    print(f"skipped (not reachable / no access door): {skipped}", file=sys.stderr)
PY
