#!/usr/bin/env bash
set -euo pipefail

# Extract code-signing identifier from macOS application bundles
# Usage: get_app_id [app_name|app_path]

extract_identifier() {
	local app="$1"
	codesign -dr - "$app" 2>&1 | grep -m1 "identifier" | sed -E 's/.*identifier "([^"]+)".*/\1/'
}

validate_and_extract() {
	local app_path="$1"

	if [[ ! -d "$app_path" ]]; then
		echo "Error: Application not found: $app_path" >&2
		return 1
	fi

	# Extract identifier
	local identifier
	identifier=$(extract_identifier "$app_path")

	if [[ -z "$identifier" ]]; then
		echo "Error: No code signature found for: $(basename "$app_path")" >&2
		return 1
	fi

	echo "$identifier"
}

get_app_id() {
	local app_path="${1:-}"

	# If no argument, use fzf to select
	if [[ -z "$app_path" ]]; then
		if ! command -v fzf &>/dev/null; then
			echo "Error: fzf is required for interactive selection" >&2
			echo "Install with: brew install fzf" >&2
			return 1
		fi

		# shellcheck disable=SC2016
		app_path=$(
			find /Applications -maxdepth 3 -name "*.app" -type d |
				sort |
				fzf --prompt="Select app: " \
					--preview='
					app={}
					printf "Application: %s\n\n" "$(basename "$app")"
					id=$(codesign -dr - "$app" 2>&1 | grep -m1 "identifier" | sed -E "s/.*identifier \"([^\"]+)\".*/\1/")
					if [[ -n "$id" ]]; then
						printf "Bundle ID:\n%s\n" "$id"
					else
						printf "No code signature found\n"
					fi
				' \
					--preview-window="up:5:wrap" \
					--height="50%"
		)

		extract_identifier "$app_path"
		return 0
	fi

	# Resolve app path
	if [[ "$app_path" != /* ]]; then
		if [[ "$app_path" == *.app ]]; then
			app_path="/Applications/$app_path"
		else
			app_path="/Applications/$app_path.app"
		fi
	fi

	validate_and_extract "$app_path"
}

# Main execution
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
	get_app_id "$@"
fi
