#!/usr/bin/env bash

PROFILES_DIR="$HOME/.config/wezterm/plugins/profiles"
FZF_THEME=$("$HOME"/.local/bin/scripts/fzf_theme.sh)

# Check if tools are available
has() { command -v "$1" >/dev/null 2>&1; }

# Detect profile list using fd or find
get_profiles() {
	if has fd; then
		fd . "$PROFILES_DIR" -e lua -d 1 -x basename {} .lua
	else
		find "$PROFILES_DIR" -maxdepth 1 -type f -name "*.lua" -printf "%f\n" | sed 's/\.lua$//'
	fi
}

# Fast profile existence check
profiles_exist() {
	if has fd; then
		if has rg; then
			fd . "$PROFILES_DIR" -e lua -d 1 | rg -q .
		else
			fd . "$PROFILES_DIR" -e lua -d 1 | grep -q .
		fi
	else
		if has rg; then
			find "$PROFILES_DIR" -maxdepth 1 -type f -name "*.lua" | rg -q .
		else
			find "$PROFILES_DIR" -maxdepth 1 -type f -name "*.lua" | grep -q .
		fi
	fi
}

# Exit early if no profiles found
if ! profiles_exist; then
	echo "No profiles found in $PROFILES_DIR"
	exit 1
fi

# Fuzzy select a profile
profile=$(get_profiles | fzf "$FZF_THEME" --cycle --no-info --layout=reverse)

if [[ -z "$profile" ]]; then
	echo "No profile selected"
	exit 1
fi

# Launch the selected domain
wezterm start --domain-name "$profile" --always-new-process >/dev/null 2>&1 &
