#!/usr/bin/env bash
# AI DevOps Framework CLI wrapper
# This wrapper handles npm/brew/bun global installs and local development.
#
# Priority order (highest to lowest):
#   1. ~/.aidevops/agents/aidevops.sh — coherent setup-deployed CLI and modules
#      (skip with AIDEVOPS_PREFER_LOCAL=1 for checkout development)
#   2. ~/Git/aidevops/aidevops.sh     — bootstrap/development checkout
#   3. Auto-clone the git repo         — first-run bootstrap
#   4. npm-bundled aidevops.sh         — snapshot at publish time
#
# Setup's deployed copy is preferred so updates take effect without requiring a
# package-manager refresh or reading a stale canonical checkout.

set -euo pipefail

REAL_HOME="${HOME:-}"
if [[ -n "${SUDO_USER:-}" && "$(id -u)" -eq 0 ]]; then
	_tmp_real_home=""
	if command -v getent &>/dev/null; then
		_tmp_real_home=$(getent passwd "$SUDO_USER" | cut -d: -f6 || true)
	elif command -v dscl &>/dev/null; then
		_tmp_real_home=$(dscl . -read "/Users/${SUDO_USER}" NFSHomeDirectory 2>/dev/null | awk '{print $2; exit}' || true)
	elif [[ -d "/Users/${SUDO_USER}" ]]; then
		_tmp_real_home="/Users/${SUDO_USER}"
	fi
	if [[ -n "$_tmp_real_home" ]]; then
		REAL_HOME="$_tmp_real_home"
	fi
fi

if [[ -z "$REAL_HOME" ]]; then
	printf 'Error: HOME is not set; unable to resolve aidevops installation paths.\n' >&2
	exit 1
fi

REPO_DIR="$REAL_HOME/Git/aidevops"
REPO_URL="https://github.com/marcusquinn/aidevops.git"
DEPLOYED_CLI="$REAL_HOME/.aidevops/agents/aidevops.sh"

# 1. Prefer the setup-deployed copy. It is released atomically with its modules,
# so a stale or dirty canonical checkout cannot split the CLI version from them.
if [[ -z "${AIDEVOPS_PREFER_LOCAL:-}" && -f "$DEPLOYED_CLI" ]]; then
	DEPLOYED_ROOT="$(cd "$(dirname "$DEPLOYED_CLI")" && pwd -P)"
	export AIDEVOPS_AGENTS_DIR="$DEPLOYED_ROOT"
	exec bash "$DEPLOYED_ROOT/aidevops.sh" "$@"
fi

# 2. Use the git repo for bootstrap and local development.
if [[ -f "$REPO_DIR/aidevops.sh" ]]; then
    exec bash "$REPO_DIR/aidevops.sh" "$@"
fi

# 3. Git repo not found — bootstrap it automatically
# This runs once on first use after a package manager install (npm/brew/bun).
# After this, step 1 will always match and the deployed copy runs directly.
if command -v git >/dev/null 2>&1; then
    echo "[aidevops] First run — cloning git repo to $REPO_DIR for transparent updates..."
    mkdir -p "$(dirname "$REPO_DIR")"
    if git clone "$REPO_URL" "$REPO_DIR" 2>/dev/null; then
        echo "[aidevops] Running setup..."
        if [[ -f "$REPO_DIR/setup.sh" ]]; then
            bash "$REPO_DIR/setup.sh" --non-interactive
        fi
        echo ""
        echo "[aidevops] Setup complete. The git repo at $REPO_DIR is now your canonical install."
        echo "[aidevops] Run 'aidevops update' to stay current. You can safely remove the"
        echo "[aidevops] package manager copy (npm/brew/bun) — it's no longer needed."
        echo ""
        exec bash "$REPO_DIR/aidevops.sh" "$@"
    else
        echo "[aidevops] Git clone failed — falling back to bundled copy." >&2
    fi
fi

# 3. Fall back to the npm-bundled copy (resolve symlinks first)
# npm install -g creates a symlink: /usr/local/bin/aidevops -> .../node_modules/aidevops/bin/aidevops
# BASH_SOURCE[0] returns the symlink path, not the target, so we must resolve it
SOURCE="${BASH_SOURCE[0]}"
while [[ -L "$SOURCE" ]]; do
    DIR="$(cd "$(dirname "$SOURCE")" && pwd)"
    SOURCE="$(readlink "$SOURCE")"
    [[ "$SOURCE" != /* ]] && SOURCE="$DIR/$SOURCE"
done
SCRIPT_DIR="$(cd "$(dirname "$SOURCE")" && pwd)"

if [[ -f "$SCRIPT_DIR/../aidevops.sh" ]]; then
    exec bash "$SCRIPT_DIR/../aidevops.sh" "$@"
fi

echo "Error: aidevops.sh not found"
echo "Please run: bash <(curl -fsSL https://aidevops.sh/install)"
exit 1
