#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# SPDX-FileCopyrightText: 2025-2026 Marcus Quinn
# Core setup functions: requirements, permissions, location
# Part of aidevops setup.sh modularization (t316.3)

# Shell safety baseline
set -Eeuo pipefail
IFS=$'\n\t'
# shellcheck disable=SC2154  # rc is assigned by $? in the trap string
trap 'rc=$?; echo "[ERROR] ${BASH_SOURCE[0]}:${LINENO} exit $rc" >&2' ERR
shopt -s inherit_errexit 2>/dev/null || true

# Install aidevops inside an OrbStack Linux VM (macOS only, user chose option 2)
_bootstrap_orbstack_install() {
	# Install OrbStack if not present
	if ! command -v orb >/dev/null 2>&1 && [[ ! -d "/Applications/OrbStack.app" ]]; then
		if command -v brew >/dev/null 2>&1; then
			print_info "Installing OrbStack via Homebrew..."
			brew install --cask orbstack
		else
			print_error "Homebrew is required to install OrbStack"
			echo "Install Homebrew first: /bin/bash -c \"\$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)\""
			echo "Then re-run this installer."
			exit 1
		fi
	fi

	# Wait for OrbStack to be ready
	if ! command -v orb >/dev/null 2>&1; then
		print_info "Waiting for OrbStack CLI to become available..."
		# OrbStack installs the CLI at /usr/local/bin/orb
		local wait_count=0
		while ! command -v orb >/dev/null 2>&1 && [[ $wait_count -lt 30 ]]; do
			sleep 2
			((++wait_count))
		done
		if ! command -v orb >/dev/null 2>&1; then
			print_error "OrbStack CLI not found after installation"
			echo "Open OrbStack.app manually, then re-run this installer."
			exit 1
		fi
	fi

	# Create or use existing Ubuntu VM
	local vm_name="aidevops"
	if orb list 2>/dev/null | grep -qxF "$vm_name"; then
		print_info "Using existing OrbStack VM: $vm_name"
	else
		print_info "Creating Ubuntu VM: $vm_name..."
		orb create ubuntu "$vm_name"
	fi

	# Run the installer inside the VM
	print_info "Installing aidevops inside the VM..."
	echo ""
	orb run -m "$vm_name" bash -c 'bash <(curl -fsSL https://aidevops.sh/install)'

	echo ""
	print_success "aidevops installed in OrbStack VM: $vm_name"
	echo ""
	echo "To use aidevops in the VM:"
	echo "  orb shell $vm_name              # Enter the VM"
	echo "  orb run -m $vm_name opencode    # Run OpenCode directly"
	echo ""
	exit 0
}

# Auto-install git using the available package manager
_bootstrap_install_git() {
	print_warning "git is required but not installed - attempting auto-install..."
	if [[ "$(uname)" == "Darwin" ]]; then
		# macOS: xcode-select --install triggers git install
		print_info "Installing Xcode Command Line Tools (includes git)..."
		if xcode-select --install 2>/dev/null; then
			# Wait for installation to complete (timeout after 5 minutes)
			print_info "Waiting for Xcode CLT installation to complete (timeout: 5m)..."
			local xcode_wait=0
			local xcode_max_wait=300
			until command -v git >/dev/null 2>&1; do
				sleep 5
				xcode_wait=$((xcode_wait + 5))
				if [[ $xcode_wait -ge $xcode_max_wait ]]; then
					print_error "Timed out waiting for Xcode CLT installation after ${xcode_max_wait}s"
					echo "Complete the installation manually, then re-run this installer."
					exit 1
				fi
			done
			print_success "git installed via Xcode Command Line Tools"
		else
			# Already installed or failed
			if ! command -v git >/dev/null 2>&1; then
				print_error "git installation failed"
				echo "Install git manually: brew install git (macOS)"
				exit 1
			fi
		fi
	elif command -v apt-get >/dev/null 2>&1; then
		print_info "Installing git via apt..."
		sudo apt-get update -qq && sudo apt-get install -y -qq git
		if ! command -v git >/dev/null 2>&1; then
			print_error "git installation failed"
			exit 1
		fi
		print_success "git installed"
	elif command -v dnf >/dev/null 2>&1; then
		print_info "Installing git via dnf..."
		sudo dnf install -y git
		if ! command -v git >/dev/null 2>&1; then
			print_error "git installation failed"
			exit 1
		fi
		print_success "git installed"
	elif command -v yum >/dev/null 2>&1; then
		print_info "Installing git via yum..."
		sudo yum install -y git
		if ! command -v git >/dev/null 2>&1; then
			print_error "git installation failed"
			exit 1
		fi
		print_success "git installed"
	elif command -v pacman >/dev/null 2>&1; then
		print_info "Installing git via pacman..."
		sudo pacman -S --noconfirm git
		if ! command -v git >/dev/null 2>&1; then
			print_error "git installation failed"
			exit 1
		fi
		print_success "git installed"
	elif command -v apk >/dev/null 2>&1; then
		print_info "Installing git via apk..."
		sudo apk add git
		if ! command -v git >/dev/null 2>&1; then
			print_error "git installation failed"
			exit 1
		fi
		print_success "git installed"
	else
		print_error "git is required but not installed and no supported package manager found"
		echo "Install git manually and re-run the installer"
		exit 1
	fi
	return 0
}

bootstrap_repo() {
	# Detect if running from curl (no script directory context)
	local script_path="${BASH_SOURCE[0]}"

	# If script_path is empty, stdin, bash, or /dev/fd/* (process substitution), we're running from curl
	# bash <(curl ...) produces paths like /dev/fd/63
	if [[ -z "$script_path" || "$script_path" == "/dev/stdin" || "$script_path" == "bash" || "$script_path" == /dev/fd/* ]]; then
		print_info "Remote install detected - bootstrapping repository..."

		# On macOS, offer choice: install locally or in an OrbStack VM
		# Skip prompt in non-interactive mode (parse_args hasn't run yet,
		# so check $@ directly for --non-interactive/-n flags)
		local _bootstrap_non_interactive=false
		local _arg
		for _arg in "$@"; do
			case "$_arg" in
			--non-interactive | -n) _bootstrap_non_interactive=true ;;
			esac
		done
		[[ "${AIDEVOPS_NON_INTERACTIVE:-false}" == "true" ]] && _bootstrap_non_interactive=true
		[[ ! -t 0 ]] && _bootstrap_non_interactive=true

		if [[ "$(uname)" == "Darwin" && "$_bootstrap_non_interactive" == "false" ]]; then
			echo ""
			echo "Where would you like to install aidevops?"
			echo ""
			echo "  1) Install on this Mac (recommended)"
			echo "  2) Install in a Linux VM (via OrbStack)"
			echo ""
			# Cannot use setup_prompt here — _common.sh not yet sourced during bootstrap.
			# The _bootstrap_non_interactive guard above prevents reaching this line.
			local install_target=""
			read -r -p "Choose [1/2] (default: 1): " install_target || install_target="1"

			if [[ "$install_target" == "2" ]]; then
				print_info "Setting up OrbStack VM installation..."
				_bootstrap_orbstack_install
			fi
		fi

		# Auto-install git if missing (required for cloning)
		if ! command -v git >/dev/null 2>&1; then
			_bootstrap_install_git
		fi

		# Create parent directory
		mkdir -p "$(dirname "$INSTALL_DIR")"

		if [[ -d "$INSTALL_DIR/.git" ]]; then
			print_info "Existing installation found - updating..."
			cd "$INSTALL_DIR" || exit 1
			if ! git pull --ff-only; then
				print_warning "Git pull failed - trying reset to origin/main"
				git fetch origin
				git reset --hard origin/main
			fi
		else
			print_info "Cloning aidevops to $INSTALL_DIR..."
			if [[ -d "$INSTALL_DIR" ]]; then
				print_warning "Directory exists but is not a git repo - backing up"
				mv "$INSTALL_DIR" "$INSTALL_DIR.backup.$(date +%Y%m%d_%H%M%S)"
			fi
			if ! git clone "$REPO_URL" "$INSTALL_DIR"; then
				print_error "Failed to clone repository"
				exit 1
			fi
		fi

		print_success "Repository ready at $INSTALL_DIR"

		# Re-execute the local script
		cd "$INSTALL_DIR" || exit 1
		exec bash "./setup.sh" "$@"
	fi
	return 0
}

# Detect package manager
detect_package_manager() {
	if command -v brew >/dev/null 2>&1; then
		echo "brew"
	elif command -v apt-get >/dev/null 2>&1; then
		echo "apt"
	elif command -v dnf >/dev/null 2>&1; then
		echo "dnf"
	elif command -v yum >/dev/null 2>&1; then
		echo "yum"
	elif command -v pacman >/dev/null 2>&1; then
		echo "pacman"
	elif command -v apk >/dev/null 2>&1; then
		echo "apk"
	else
		echo "unknown"
	fi
	return 0
}

# Install packages using detected package manager
# For Homebrew: runs 'brew update' with a spinner first (can take 30s+),
# then installs packages with HOMEBREW_NO_AUTO_UPDATE to avoid a second update.
install_packages() {
	local pkg_manager="$1"
	shift
	local packages=("$@")

	# Cache sudo credentials before spinner commands.
	# Backgrounded processes cannot safely prompt for passwords.
	if [[ "$pkg_manager" =~ ^(apt|dnf|yum|pacman|apk)$ ]]; then
		sudo -v
	fi

	case "$pkg_manager" in
	brew)
		# Run brew update with spinner (Homebrew auto-update is slow and silent)
		if ! run_with_spinner "Updating Homebrew" brew update; then
			print_error "Homebrew update failed"
			return 1
		fi
		# Install with auto-update disabled (we just ran it)
		# Note: run_with_spinner auto-exports HOMEBREW_NO_AUTO_UPDATE for brew commands
		run_with_spinner "Installing ${packages[*]}" brew install "${packages[@]}"
		;;
	apt)
		if ! run_with_spinner "Updating package lists" sudo apt-get update -qq; then
			print_error "apt-get update failed"
			return 1
		fi
		run_with_spinner "Installing ${packages[*]}" sudo apt-get install -y -qq "${packages[@]}"
		;;
	dnf)
		run_with_spinner "Installing ${packages[*]}" sudo dnf install -y "${packages[@]}"
		;;
	yum)
		run_with_spinner "Installing ${packages[*]}" sudo yum install -y "${packages[@]}"
		;;
	pacman)
		run_with_spinner "Installing ${packages[*]}" sudo pacman -S --noconfirm "${packages[@]}"
		;;
	apk)
		run_with_spinner "Installing ${packages[*]}" sudo apk add "${packages[@]}"
		;;
	*)
		return 1
		;;
	esac

	return 0
}

# Offer to install Homebrew (Linuxbrew) on Linux when brew is not available
# Many tools in the aidevops ecosystem (Beads, Worktrunk, bv) are distributed
# via Homebrew taps. On macOS, brew is almost always present. On Linux, this
# function offers to install it so those tools can be installed automatically.
# Returns: 0 if brew is now available, 1 if user declined or install failed
ensure_homebrew() {
	# Already available
	if command -v brew &>/dev/null; then
		return 0
	fi

	# Only offer on Linux (macOS users should install Homebrew themselves)
	if [[ "$(uname)" == "Darwin" ]]; then
		print_warning "Homebrew not found. Install from https://brew.sh"
		return 1
	fi

	# Non-interactive mode: skip
	if [[ "$NON_INTERACTIVE" == "true" ]]; then
		return 1
	fi

	echo ""
	print_info "Homebrew (Linuxbrew) is not installed."
	print_info "Several optional tools (Beads CLI, Worktrunk, bv) install via Homebrew taps."
	echo ""
	local install_brew="Y"
	setup_prompt install_brew "Install Homebrew for Linux? [Y/n]: " "Y"

	if [[ ! "$install_brew" =~ ^[Yy]?$ ]]; then
		print_info "Skipped Homebrew installation"
		return 1
	fi

	print_info "Installing Homebrew (Linuxbrew)..."

	# Prerequisites for Linuxbrew
	if command -v apt-get &>/dev/null; then
		sudo apt-get update -qq
		sudo apt-get install -y -qq build-essential procps curl file git
	elif command -v dnf &>/dev/null; then
		sudo dnf groupinstall -y 'Development Tools'
		sudo dnf install -y procps-ng curl file git
	elif command -v yum &>/dev/null; then
		sudo yum groupinstall -y 'Development Tools'
		sudo yum install -y procps-ng curl file git
	fi

	# Install Homebrew using verified_install pattern
	if verified_install "Homebrew" "https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh"; then
		# Add Homebrew to PATH for this session
		local brew_prefix="/home/linuxbrew/.linuxbrew"
		if [[ -x "$brew_prefix/bin/brew" ]]; then
			eval "$("$brew_prefix/bin/brew" shellenv)"
		fi

		# Persist to shell rc files
		local brew_line="eval \"\$($brew_prefix/bin/brew shellenv)\""
		local rc_file
		while IFS= read -r rc_file; do
			[[ -z "$rc_file" ]] && continue
			if ! grep -q 'linuxbrew' "$rc_file" 2>/dev/null; then
				{
					echo ""
					echo "# Homebrew (Linuxbrew) - added by aidevops setup"
					echo "$brew_line"
				} >>"$rc_file"
			fi
		done < <(get_all_shell_rcs)

		if command -v brew &>/dev/null; then
			print_success "Homebrew installed and added to PATH"
			return 0
		else
			print_warning "Homebrew installed but not yet in PATH. Restart your shell or run:"
			echo "  $brew_line"
			return 1
		fi
	else
		print_warning "Homebrew installation failed"
		return 1
	fi
}

# Fix Homebrew PATH for Apple Silicon and Intel Macs when brew is not in PATH.
# Modifies rc files only during interactive setup (not updates).
_check_req_fix_homebrew_path() {
	# Apple Silicon Homebrew
	if [[ -x "/opt/homebrew/bin/brew" ]] && [[ ":$PATH:" != *":/opt/homebrew/bin:"* ]]; then
		eval "$(/opt/homebrew/bin/brew shellenv)"
		print_warning "Homebrew not in PATH - added for this session"

		# Only modify rc files during interactive setup (not updates)
		# Users may intentionally remove these lines; re-adding on every update is harmful
		if [[ "$NON_INTERACTIVE" != "true" ]]; then
			# shellcheck disable=SC2016 # brew_line is written to rc files; must expand at shell startup, not now
			local brew_line='eval "$(/opt/homebrew/bin/brew shellenv)"'
			local fixed_rc=false
			local rc_file
			while IFS= read -r rc_file; do
				[[ -z "$rc_file" ]] && continue
				if ! grep -q '/opt/homebrew/bin/brew' "$rc_file" 2>/dev/null; then
					{
						echo ""
						echo "# Homebrew (added by aidevops setup)"
						echo "$brew_line"
					} >>"$rc_file"
					print_success "Added Homebrew to PATH in $rc_file"
					fixed_rc=true
				fi
			done < <(get_all_shell_rcs)

			if [[ "$fixed_rc" == "false" ]]; then
				echo ""
				echo "  To fix permanently, add to your shell rc file:"
				echo "    $brew_line"
				echo ""
			fi
		fi
	fi

	# Also check Intel Mac Homebrew location
	# Skip entirely on Apple Silicon (ARM brew exists) — Intel brew shellenv prepends
	# /usr/local/bin to PATH, causing x86 binaries to shadow ARM ones (GH#1510)
	if [[ -x "/usr/local/bin/brew" ]] && [[ ":$PATH:" != *":/usr/local/bin:"* ]]; then
		# On Apple Silicon with dual brew, do NOT add Intel brew to PATH — it breaks ARM brew
		if [[ -x "/opt/homebrew/bin/brew" ]]; then
			print_info "Intel Homebrew found but skipped (Apple Silicon uses /opt/homebrew)"
		else
			eval "$(/usr/local/bin/brew shellenv)"
			print_warning "Homebrew (/usr/local/bin) not in PATH - added for this session"

			# Only modify rc files during interactive setup (not updates)
			if [[ "$NON_INTERACTIVE" != "true" ]]; then
				# shellcheck disable=SC2016 # intel_brew_line is written to rc files; must expand at shell startup, not now
				local intel_brew_line='eval "$(/usr/local/bin/brew shellenv)"'
				local intel_fixed_rc=false
				local intel_rc
				while IFS= read -r intel_rc; do
					[[ -z "$intel_rc" ]] && continue
					if ! grep -q '/usr/local/bin/brew' "$intel_rc" 2>/dev/null; then
						{
							echo ""
							echo "# Homebrew Intel Mac (added by aidevops setup)"
							echo "$intel_brew_line"
						} >>"$intel_rc"
						print_success "Added Homebrew to PATH in $intel_rc"
						intel_fixed_rc=true
					fi
				done < <(get_all_shell_rcs)

				if [[ "$intel_fixed_rc" == "false" ]]; then
					echo ""
					echo "  To fix permanently, add to your shell rc file:"
					echo "    $intel_brew_line"
					echo ""
				fi
			fi
		fi
	fi
	return 0
}

# Check system requirements
check_requirements() {
	print_info "Checking system requirements..."

	# Ensure Homebrew is in PATH (macOS Apple Silicon and Intel)
	_check_req_fix_homebrew_path

	local missing_deps=()
	local missing_packages=()

	# Detect package manager once for both package-name resolution and installation
	local pkg_manager
	pkg_manager=$(detect_package_manager)

	# Check for required commands
	# Format: command-name package-name (same when identical)
	if ! command -v jq >/dev/null 2>&1; then
		missing_deps+=("jq")
		missing_packages+=("jq")
	fi
	if ! command -v curl >/dev/null 2>&1; then
		missing_deps+=("curl")
		missing_packages+=("curl")
	fi
	if ! command -v rg >/dev/null 2>&1; then
		missing_deps+=("rg")
		missing_packages+=("ripgrep")
	fi
	if ! command -v sqlite3 >/dev/null 2>&1; then
		missing_deps+=("sqlite3")
		# Package name varies: sqlite3 on Debian/Ubuntu (apt), sqlite on Homebrew/Fedora/Arch/Alpine
		case "$pkg_manager" in
		apt) missing_packages+=("sqlite3") ;;
		*) missing_packages+=("sqlite") ;;
		esac
	fi

	if [[ ${#missing_deps[@]} -gt 0 ]]; then
		print_warning "Missing required dependencies: ${missing_deps[*]}"

		if [[ "$pkg_manager" == "unknown" ]]; then
			print_error "Could not detect package manager"
			echo ""
			echo "Please install manually:"
			echo "  macOS: brew install ${missing_packages[*]}"
			echo "  Ubuntu/Debian: sudo apt-get install ${missing_packages[*]}"
			echo "  Fedora: sudo dnf install ${missing_packages[*]}"
			echo "  CentOS/RHEL: sudo yum install ${missing_packages[*]}"
			echo "  Arch: sudo pacman -S ${missing_packages[*]}"
			echo "  Alpine: sudo apk add ${missing_packages[*]}"
			exit 1
		fi

		# In non-interactive mode, fail fast on missing deps
		if [[ "$NON_INTERACTIVE" == "true" ]]; then
			print_error "Cannot continue without required dependencies (non-interactive mode)"
			exit 1
		fi

		echo ""
		local install_deps="Y"
		setup_prompt install_deps "Install missing dependencies using $pkg_manager? [Y/n]: " "Y"

		if [[ "$install_deps" =~ ^[Yy]?$ ]]; then
			print_info "Installing ${missing_packages[*]}..."
			if install_packages "$pkg_manager" "${missing_packages[@]}"; then
				print_success "Dependencies installed successfully"
			else
				print_error "Failed to install dependencies"
				exit 1
			fi
		else
			print_error "Cannot continue without required dependencies"
			exit 1
		fi
	fi

	print_success "All required dependencies found"
	return 0
}

# Check for quality/linting tools (shellcheck, shfmt, markdownlint)
# These are optional but recommended for development
_check_quality_tool() {
	local tool_name="$1"
	local version=""

	if command -v "$tool_name" >/dev/null 2>&1; then
		case "$tool_name" in
		shellcheck)
			version=$(shellcheck --version 2>/dev/null | head -1 || true)
			;;
		shfmt)
			version=$(shfmt --version 2>/dev/null)
			;;
		esac
		print_success "$tool_name: ${version:-installed}"
	else
		missing_tools+=("$tool_name")
	fi

	return 0
}

_check_markdownlint_tool() {
	local version=""

	if command -v markdownlint >/dev/null 2>&1; then
		version=$(markdownlint --version 2>/dev/null | head -1 || true)
		print_success "markdownlint: ${version:-installed}"
		return 0
	fi

	if command -v markdownlint-cli2 >/dev/null 2>&1; then
		version=$(markdownlint-cli2 --version 2>/dev/null | head -1 || true)
		print_success "markdownlint-cli2: ${version:-installed}"
		return 0
	fi

	missing_npm_tools+=("markdownlint-cli2")
	return 0
}

_report_missing_quality_tools() {
	if [[ ${#missing_tools[@]} -gt 0 ]]; then
		print_warning "Missing quality tools: ${missing_tools[*]}"
	fi

	if [[ ${#missing_npm_tools[@]} -gt 0 ]]; then
		print_warning "Missing npm quality tools: ${missing_npm_tools[*]}"
	fi

	print_info "These tools are used by linters-local.sh for code quality checks"
	return 0
}

_install_missing_quality_tools() {
	local pkg_manager="$1"
	local install_quality="Y"

	if [[ "$pkg_manager" == "unknown" ]]; then
		print_info "Install manually:"
		echo "  macOS: brew install ${missing_tools[*]}"
		echo "  Ubuntu/Debian: sudo apt-get install ${missing_tools[*]}"
		echo "  Fedora: sudo dnf install ${missing_tools[*]}"
		return 0
	fi

	echo ""
	setup_prompt install_quality "Install quality tools using $pkg_manager? [Y/n]: " "Y"

	if [[ "$install_quality" =~ ^[Yy]?$ ]]; then
		print_info "Installing ${missing_tools[*]}..."
		if install_packages "$pkg_manager" "${missing_tools[@]}"; then
			print_success "Quality tools installed successfully"
		else
			print_warning "Failed to install some quality tools - continuing anyway"
		fi
	else
		print_info "Skipped quality tools installation"
		print_info "Install later: $pkg_manager install ${missing_tools[*]}"
	fi

	return 0
}

_install_missing_npm_quality_tools() {
	local install_npm_quality="Y"

	if ! command -v npm >/dev/null 2>&1; then
		print_warning "npm not found; cannot auto-install ${missing_npm_tools[*]}"
		print_info "Install Node.js/npm, then run: npm install -g ${missing_npm_tools[*]}"
		return 0
	fi

	echo ""
	setup_prompt install_npm_quality "Install npm quality tools (npm install -g ${missing_npm_tools[*]})? [Y/n]: " "Y"
	if [[ "$install_npm_quality" =~ ^[Yy]?$ ]]; then
		print_info "Installing npm quality tools: ${missing_npm_tools[*]}..."
		if npm install -g "${missing_npm_tools[@]}" >/dev/null 2>&1; then
			print_success "npm quality tools installed successfully"
		else
			print_warning "Failed to install npm quality tools - continuing anyway"
		fi
	else
		print_info "Skipped npm quality tools installation"
		print_info "Install later: npm install -g ${missing_npm_tools[*]}"
	fi

	return 0
}

check_quality_tools() {
	print_info "Checking quality tools..."

	local missing_tools=()
	local missing_npm_tools=()

	_check_quality_tool "shellcheck"
	_check_quality_tool "shfmt"
	_check_markdownlint_tool

	if [[ ${#missing_tools[@]} -eq 0 && ${#missing_npm_tools[@]} -eq 0 ]]; then
		print_success "All quality tools installed"
		return 0
	fi

	_report_missing_quality_tools

	if [[ "$NON_INTERACTIVE" == "true" ]]; then
		if [[ ${#missing_tools[@]} -gt 0 ]]; then
			print_info "Install later: brew install ${missing_tools[*]}"
		fi
		if [[ ${#missing_npm_tools[@]} -gt 0 ]]; then
			if command -v npm >/dev/null 2>&1; then
				print_info "Install later: npm install -g ${missing_npm_tools[*]}"
			else
				print_info "Install later: install npm, then run npm install -g ${missing_npm_tools[*]}"
			fi
		fi
		return 0
	fi

	# Offer to install
	local pkg_manager
	pkg_manager=$(detect_package_manager)

	if [[ ${#missing_tools[@]} -gt 0 ]]; then
		_install_missing_quality_tools "$pkg_manager"
	fi

	if [[ ${#missing_npm_tools[@]} -gt 0 ]]; then
		_install_missing_npm_quality_tools
	fi

	return 0
}

verify_location() {
	local current_dir
	current_dir="$(pwd)"
	local expected_location="$HOME/Git/aidevops"

	if [[ "$current_dir" != "$expected_location" ]]; then
		print_warning "Repository is not in the recommended location"
		print_info "Current location: $current_dir"
		print_info "Recommended location: $expected_location"
		echo ""
		echo "For optimal AI assistant integration, consider moving this repository to:"
		echo "  mkdir -p ~/git"
		echo "  mv '$current_dir' '$expected_location'"
		echo ""
	else
		print_success "Repository is in the recommended location: $expected_location"
	fi
	return 0
}

set_permissions() {
	print_info "Setting proper file permissions..."

	local deployed_dir="$HOME/.aidevops/agents"

	# Set permissions on DEPLOYED agents (not the git repo, to avoid dirtying the working tree)
	# See: https://github.com/marcusquinn/aidevops/issues/2286
	if [[ -d "$deployed_dir/scripts" ]]; then
		chmod +x "$deployed_dir/scripts/"*.sh 2>/dev/null || true
		# Also handle modularised subdirectories (e.g. memory/, supervisor-modules/)
		find "$deployed_dir/scripts" -mindepth 2 -name "*.sh" -exec chmod +x {} + 2>/dev/null || true
	fi

	# Secure configuration files (these are in the user's config dir, not the repo)
	chmod 600 "$HOME/.config/aidevops/"*.json 2>/dev/null || true
	# Also secure repo-local configs if present (for interactive setup from repo root)
	chmod 600 configs/*.json 2>/dev/null || true

	print_success "File permissions set"
	return 0
}
