#!/usr/bin/env bash
set -o errexit -o pipefail -o noclobber -o nounset

# direnv: Load 1Password secrets
# Usage: use op [-s|--section <section>] [-w|--wrap <command>]
#   -s|--section: Load a section from a 1Password item.
#   -w|--wrap: Create an alias for a command that uses 1Password secrets.
#
# Example:
#   use op -s "Personal/Secrets/Scripts#MY_VARS_"
#   It will load every field from the "Scripts" section of the "Secrets" item
#   in the "Personal" vault and export them with the "MY_VARS_" prefix.
#
#   use op -w "my-command"
#   It will create an alias for "my-command" that will load the 1Password secrets
function use_op() {
	local section=""
	local wrap=""

	echo "op: Loading 1Password secrets..."

	while true; do
		if test "$#" -eq 0; then
			break
		fi

		case "$1" in
			-s|--section)
				if test -n "$section"; then
					section="$section $2"
				else
					section="$2"
				fi

				shift 2
				;;
			-w|--wrap)
				if test -n "$wrap"; then
					wrap="$wrap $2"
				else
					wrap="$2"
				fi

				shift 2
				;;
		esac
	done

	if test -z "$section" -a -z "$wrap"; then
		echo "op: Nothing to do - use '-s' or '-w'."
		return
	fi

	for w in $wrap; do
		eval "alias $w='op run -- $w'"
	done

	for s in $section; do
		local vault="$(echo $s | cut -d/ -f1)"
		local item="$(echo $s | cut -d/ -f2)"
		local label="$(echo $s | cut -d/ -f3 | cut -d'#' -f1)"
		local prefix="$(echo $s | cut -d'#' -f2)"
		prefix=${prefix:-""}

		local data="$(op item get $item --vault $vault --format json | jq -c)"

		eval "$(echo $data | jq -r '.fields[] | select(.section.label == "'$label'") | "export '$prefix'\(.label)=\"\(.value)\"; "')"
	done
}

# direnv: Load MCP servers for Claude Code
# Usage: use_mcp <server1> [server2] [server3] ...
# 
# Example:
#   use_mcp filesystem brave-search
#   This will create an alias for claude that includes the specified MCP servers
function use_mcp() {
	if test "$#" -eq 0; then
		echo "mcp: No servers specified. Usage: use_mcp <server1> [server2] ..."
		return
	fi
	
	if test ! -f "$HOME/mcp.yaml"; then
		echo "mcp: Error - $HOME/mcp.yaml not found"
		return
	fi
	
	if ! command -v yq &> /dev/null; then
		echo "mcp: Error - yq command not found"
		return
	fi
	
	echo "mcp: Adding MCP servers: $*"
	
	local mcp_config=""
	
	for server in "$@"; do
		# Check if the server exists in the YAML file
		if ! yq eval ".mcpServers | has(\"$server\")" "$HOME/mcp.yaml" | grep -q "true"; then
			echo "mcp: Warning - server '$server' not found in mcp.yaml"
			continue
		fi
		
		# Extract the server configuration and convert to JSON
		local server_config=$(yq eval ".mcpServers.$server" "$HOME/mcp.yaml" -o json)
		
		if test -n "$mcp_config"; then
			mcp_config="$mcp_config,$server_config"
		else
			mcp_config="$server_config"
		fi
	done
	
	if test -n "$mcp_config"; then
		# Wrap the servers in a proper JSON object
		local full_config="{\"mcpServers\":{$mcp_config}}"
		eval "alias claude='claude --mcp-config <(echo '\''$full_config'\'')'"
	else
		echo "mcp: No valid servers found"
	fi
}

# devenv's generated direnv integration runs `devenv direnv-export` and evals
# its stdout.  On first reload after a config change, the TUI/progress output can
# occasionally leak onto stdout, making direnv try to execute words like
# "Running" as shell commands.  Force non-TUI quiet mode for direnv activations.
eval "$(devenv direnvrc | sed 's/local devenv_cmd=("${DEVENV_BIN}")/local devenv_cmd=("${DEVENV_BIN}" --quiet --no-tui)/')"

# Preserve devenv's generated implementation so the wrapper can select a source.
eval "$(declare -f use_devenv | sed '1s/use_devenv/_use_devenv/')"

function use_devenv() {
	if test "$#" -gt 0 && test "${1#-}" = "$1" && test -e "$1"; then
		local source="$1"
		shift
		watch_file "$source/default.nix" "$source/devenv.nix" "$source/devenv.lock" "$source/devenv.yaml" "$source/devenv.local.nix" "$source/devenv.local.yaml"
		_use_devenv --from "path:$source" "$@"
	elif test -f devenv.nix && test -f .nix/default.nix; then
		log_error "both devenv.nix and .nix/default.nix exist; pass the desired directory to 'use devenv'"
		return 1
	elif test -f .nix/default.nix; then
		watch_file .nix/default.nix .nix/devenv.lock .nix/devenv.yaml .nix/devenv.local.nix .nix/devenv.local.yaml
		_use_devenv --from path:.nix "$@"
	else
		_use_devenv "$@"
	fi
}
