#!/usr/bin/env bash
# claude-profile — Launch Claude Code with a named config profile
# Profiles are directories matching ~/.claude-*/
# Usage:
#   claude-profile              # interactive menu
#   claude-profile <name>       # direct launch (e.g. claude-profile work)

set -euo pipefail

DEFAULT_DIR="$HOME/.claude"
PROFILE_PATTERN="$HOME/.claude-*"

# Gather profiles
profiles=()
for dir in $PROFILE_PATTERN; do
    [[ -d "$dir" ]] || continue
    name="${dir##*/.claude-}"
    profiles+=("$name")
done

# Direct invocation with a profile name
if [[ ${1:-} ]]; then
    target="$HOME/.claude-$1"
    if [[ -d "$target" ]]; then
        export CLAUDE_CONFIG_DIR="$target"
        echo "Using profile: $1 ($target)"
        exec claude "${@:2}"
    else
        echo "Profile '$1' not found. Create it with: mkdir -p $target" >&2
        exit 1
    fi
fi

# Build menu
echo "Claude Code profiles:"
echo ""
i=1
echo "  $i) default (~/.claude)"
options=("default")
for name in "${profiles[@]}"; do
    ((i++))
    echo "  $i) $name (~/.claude-$name)"
    options+=("$name")
done

echo ""
read -rp "Choose profile [1]: " choice
choice="${choice:-1}"

# Validate choice
if ! [[ "$choice" =~ ^[0-9]+$ ]] || (( choice < 1 || choice > ${#options[@]} )); then
    echo "Invalid choice." >&2
    exit 1
fi

selected="${options[$((choice - 1))]}"

if [[ "$selected" == "default" ]]; then
    echo "Using default profile ($DEFAULT_DIR)"
    export CLAUDE_CONFIG_DIR="$DEFAULT_DIR"
else
    target="$HOME/.claude-$selected"
    echo "Using profile: $selected ($target)"
    export CLAUDE_CONFIG_DIR="$target"
fi

#set -uo pipefail

# Load the context
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
CONTEXT_LOADER="${SCRIPT_DIR}/context-load"

if [[ ! -x "$CONTEXT_LOADER" ]]; then
    echo "Error: context-load not found at $CONTEXT_LOADER" >&2
    exit 1
fi

context="$("$CONTEXT_LOADER")"

if [[ -n "$context" ]]; then
    exec claude --append-system-prompt "$context" "$@"
else
    exec claude "$@"
fi
