#!/usr/bin/env bash
# Human-run read-only Fabric inventory helper.
# It never writes to .env, memory, or Fabric resources.

set -euo pipefail

usage() {
    cat <<'USAGE'
Usage: bin/fabric-inventory-readonly [--workspace-id <id>] [--items]

Read-only helper that prints Fabric workspace or item inventory using the Fabric CLI.
It never writes .env, memory, or Fabric resources. Humans copy approved sandbox IDs
manually after review.

Options:
  --workspace-id <id>  Workspace ID to inspect when using --items.
  --items              List items in the specified workspace.
  -h, --help           Show this help.
USAGE
}

workspace_id="${FABRIC_WORKSPACE_ID:-}"
list_items=false

while [[ $# -gt 0 ]]; do
    case "$1" in
        --workspace-id)
            workspace_id="${2:-}"
            shift 2
            ;;
        --items)
            list_items=true
            shift
            ;;
        -h|--help)
            usage
            exit 0
            ;;
        *)
            echo "Unknown argument: $1" >&2
            usage >&2
            exit 2
            ;;
    esac
done

user_home="$(python3 -c 'import os,pwd; print(pwd.getpwuid(os.getuid()).pw_dir)' 2>/dev/null || true)"
fab_bin="${user_home}/.local/bin/fab"
if [[ -z "$user_home" || ! -x "$fab_bin" ]]; then
    echo "Fabric CLI (fab) is not installed at the expected user-local path. Run './setup.sh --install-tools' first." >&2
    exit 127
fi

if [[ "$list_items" == "true" ]]; then
    if [[ -z "$workspace_id" ]]; then
        echo "--workspace-id is required for --items when FABRIC_WORKSPACE_ID is not set." >&2
        exit 2
    fi
    echo "# Fabric items for workspace (read-only): ${workspace_id}"
    "$fab_bin" api get "/v1/workspaces/${workspace_id}/items"
else
    echo "# Fabric workspaces (read-only)"
    "$fab_bin" api get "/v1/workspaces"
fi
