#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# SPDX-FileCopyrightText: 2025-2026 Marcus Quinn
set -euo pipefail

# AmpCode CLI Integration Script
# Professional AI coding assistant integration
#
# Usage: ./ampcode-cli.sh [command] [options]
# Commands:
#   install     - Install AmpCode CLI
#   setup       - Configure AmpCode with API key
#   scan        - Run code scan and analysis
#   review      - Get AI code review
#   fix         - Apply AI-suggested fixes
#   status      - Check AmpCode status
#
# Author: AI DevOps Framework
# Version: 1.1.0
# License: MIT

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" || exit
# shellcheck source=./shared-constants.sh
source "${SCRIPT_DIR}/shared-constants.sh"

# Configuration
readonly AMPCODE_API_CONFIG="configs/ampcode-config.json"
readonly AMPCODE_RESULTS_DIR=".agents/tmp/ampcode"
readonly -a ALLOWED_OUTPUT_FORMATS=(json text csv html md)
readonly -a ALLOWED_SEVERITY_LEVELS=(low medium high critical)

# Print functions
print_header() {
	local message="$1"
	echo -e "${PURPLE}🤖 $message${NC}"
	return 0
}

# Ensure results directory exists
ensure_results_dir() {
	mkdir -p "$AMPCODE_RESULTS_DIR"
	return 0
}

# Create a private output file for potentially sensitive results
create_private_output_file() {
	local file_path="$1"
	: >"$file_path"
	chmod 600 "$file_path"
	return 0
}

# Load API configuration
load_api_config() {
	# Check environment variable first (set via credentials.sh, sourced by .zshrc)
	if [[ -n "${AMPCODE_API_KEY:-}" ]]; then
		print_info "Using AmpCode API key from environment"
		return 0
	fi

	# Fallback to config file
	if [[ -f "$AMPCODE_API_CONFIG" ]] && command -v jq >/dev/null 2>&1; then
		local api_key
		api_key=$(jq -r '.api_key // empty' "$AMPCODE_API_CONFIG")
		if [[ -n "$api_key" ]]; then
			export AMPCODE_API_KEY="$api_key"
			print_info "Loaded AmpCode API key from configuration"
			return 0
		fi
	fi

	print_warning "AMPCODE_API_KEY not found in environment"
	print_info "Add to ~/.config/aidevops/credentials.sh:"
	print_info "  export AMPCODE_API_KEY=\"your-api-key\""
	return 1
}

# Check if AmpCode CLI is installed
check_ampcode_cli() {
	local ampcode_cmd="amp" # Likely CLI command name

	if command -v "$ampcode_cmd" &>/dev/null; then
		local version
		version=$("$ampcode_cmd" --version || echo "unknown")
		print_success "AmpCode CLI installed: $version"
		return 0
	else
		print_warning "AmpCode CLI not found"
		print_info "Expected CLI command: amp"
		return 1
	fi
}

# Install AmpCode CLI
install_ampcode_cli() {
	print_header "Installing AmpCode CLI"

	# Check if already installed
	if check_ampcode_cli; then
		print_info "AmpCode CLI is already installed"
		return 0
	fi

	# Detect platform and install method
	local platform
	case "$(uname -s)" in
	Darwin*)
		platform="macOS"
		if command -v brew &>/dev/null; then
			print_info "Installing via Homebrew..."
			# Install via npm as common method
			if command -v npm &>/dev/null; then
				# NOSONAR - npm scripts required for CLI binary installation
				npm install -g @ampcode/cli
			else
				print_error "npm not found. Please install Node.js first"
				return 1
			fi
		else
			print_error "Homebrew not found. Please install Homebrew first"
			return 1
		fi
		;;
	Linux*)
		platform="Linux"
		if command -v npm &>/dev/null; then
			print_info "Installing via npm..."
			# NOSONAR - npm scripts required for CLI binary installation
			npm install -g @ampcode/cli
		else
			print_error "npm not found. Please install Node.js first"
			return 1
		fi
		;;
	*)
		print_error "Unsupported platform: $(uname -s)"
		return 1
		;;
	esac

	# Verify installation
	if check_ampcode_cli; then
		print_success "AmpCode CLI installed successfully on $platform"
		return 0
	else
		print_error "Installation failed"
		print_info "Alternative: Visit https://ampcode.com to download CLI"
		return 1
	fi
}

# Setup AmpCode configuration
setup_ampcode_config() {
	print_header "Setting Up AmpCode Configuration"

	# Load existing config
	if ! load_api_config; then
		print_info "Please visit https://ampcode.com to get your API key"
		print_info "Then run: Add AMPCODE_API_KEY to ~/.config/aidevops/credentials.sh"
		return 1
	fi

	# Create config file
	mkdir -p configs
	cat >"$AMPCODE_API_CONFIG" <<'EOF'
{
  "api_key": "",
  "organisation": "",
  "workspace": "",
  "preferences": {
    "auto_review": true,
    "severity_threshold": "medium",
    "focus_areas": ["security", "performance", "maintainability"]
  }
}
EOF

	# Update config with API key
	if command -v jq >/dev/null 2>&1 && [[ -n "$AMPCODE_API_KEY" ]]; then
		jq --arg api_key "$AMPCODE_API_KEY" '.api_key = $api_key' "$AMPCODE_API_CONFIG" >"${AMPCODE_API_CONFIG}.tmp"
		mv "${AMPCODE_API_CONFIG}.tmp" "$AMPCODE_API_CONFIG"
	fi

	print_success "AmpCode configuration created: $AMPCODE_API_CONFIG"
	print_info "You can customize the configuration file as needed"
	return 0
}

# Validate a value against a whitelist array
# Usage: validate_whitelist "value" "label" "${array[@]}"
validate_whitelist() {
	local value="$1"
	local label="$2"
	shift 2
	local allowed
	for allowed in "$@"; do
		if [[ "$value" == "$allowed" ]]; then
			return 0
		fi
	done
	print_error "Invalid $label: $value"
	print_info "Allowed values: $*"
	return 1
}

# Run code scan
run_code_scan() {
	local target_path="${1:-.}"
	local output_format="${2:-json}"

	print_header "Running AmpCode Code Scan"

	if ! validate_whitelist "$output_format" "output format" "${ALLOWED_OUTPUT_FORMATS[@]}"; then
		return 1
	fi

	# Ensure CLI is installed
	if ! check_ampcode_cli; then
		print_error "AmpCode CLI not installed"
		print_info "Run: $0 install"
		return 1
	fi

	# Load API configuration
	if ! load_api_config; then
		print_error "API configuration not found"
		print_info "Run: $0 setup"
		return 1
	fi

	ensure_results_dir
	local output_file
	output_file="$AMPCODE_RESULTS_DIR/scan-$(date +%Y%m%d-%H%M%S).$output_format"
	create_private_output_file "$output_file"

	print_info "Scanning path: $target_path"
	print_info "Output format: $output_format"

	local -a cmd=(amp scan --path "$target_path" --format "$output_format" --output "$output_file")
	print_info "Executing: ${cmd[*]}"

	local start_time
	start_time=$(date +%s)
	"${cmd[@]}"
	local exit_code=$?
	local end_time
	end_time=$(date +%s)
	local duration
	duration=$((end_time - start_time))

	if [[ $exit_code -eq 0 ]]; then
		print_success "Code scan completed in ${duration}s"
		print_info "Results saved to: $output_file"

		# Show summary
		if [[ -f "$output_file" && "$output_format" == "json" ]] && command -v jq >/dev/null 2>&1; then
			local issues
			issues=$(jq '.issues | length // 0' "$output_file" || echo "0")
			local suggestions
			suggestions=$(jq '.suggestions | length // 0' "$output_file" || echo "0")
			print_info "Issues found: $issues"
			print_info "AI suggestions: $suggestions"
		fi
		return 0
	else
		print_error "Code scan failed after ${duration}s"
		return 1
	fi
}

# Get AI code review
get_ai_review() {
	local target_path="${1:-.}"
	local severity_level="${2:-medium}"

	print_header "Getting AmpCode AI Review"

	if ! validate_whitelist "$severity_level" "severity level" "${ALLOWED_SEVERITY_LEVELS[@]}"; then
		return 1
	fi

	# Ensure CLI is installed
	if ! check_ampcode_cli; then
		print_error "AmpCode CLI not installed"
		return 1
	fi

	# Load API configuration
	if ! load_api_config; then
		print_error "API configuration not found"
		return 1
	fi

	ensure_results_dir
	local review_file
	review_file="$AMPCODE_RESULTS_DIR/review-$(date +%Y%m%d-%H%M%S).md"
	create_private_output_file "$review_file"

	print_info "Reviewing path: $target_path"
	print_info "Severity level: $severity_level"

	local -a cmd=(amp review --path "$target_path" --severity "$severity_level" --output "$review_file")
	print_info "Executing: ${cmd[*]}"

	local start_time
	start_time=$(date +%s)
	"${cmd[@]}"
	local exit_code=$?
	local end_time
	end_time=$(date +%s)
	local duration
	duration=$((end_time - start_time))

	if [[ $exit_code -eq 0 ]]; then
		print_success "AI review completed in ${duration}s"
		print_info "Review saved to: $review_file"

		# Show preview
		if [[ -f "$review_file" ]]; then
			print_info "Review preview:"
			echo ""
			head -20 "$review_file"
			echo ""
			local total_lines
			total_lines=$(wc -l <"$review_file")
			print_info "Total review lines: $total_lines"
		fi
		return 0
	else
		print_error "AI review failed after ${duration}s"
		return 1
	fi
}

# Apply AI-suggested fixes
apply_fixes() {
	local target_path="${1:-.}"
	local auto_apply="${2:-false}"

	print_header "Applying AmpCode AI Fixes"

	# Ensure CLI is installed
	if ! check_ampcode_cli; then
		print_error "AmpCode CLI not installed"
		return 1
	fi

	# Load API configuration
	if ! load_api_config; then
		print_error "API configuration not found"
		return 1
	fi

	ensure_results_dir
	local fixes_file
	fixes_file="$AMPCODE_RESULTS_DIR/fixes-$(date +%Y%m%d-%H%M%S).json"
	create_private_output_file "$fixes_file"

	print_info "Analyzing fixes for: $target_path"

	local -a cmd=(amp analyze --path "$target_path" --suggest-fixes --output "$fixes_file")
	print_info "Executing: ${cmd[*]}"

	local start_time
	start_time=$(date +%s)
	"${cmd[@]}"
	local exit_code=$?
	local end_time
	end_time=$(date +%s)
	local duration
	duration=$((end_time - start_time))

	if [[ $exit_code -eq 0 && -f "$fixes_file" ]]; then
		print_success "Fix analysis completed in ${duration}s"

		if command -v jq >/dev/null 2>&1; then
			local fixes_count
			fixes_count=$(jq '.fixes | length // 0' "$fixes_file" || echo "0")
			print_info "AI fixes available: $fixes_count"
		fi

		if [[ "$auto_apply" == "true" ]]; then
			print_warning "Auto-apply enabled - Apply with caution!"
			print_info "Applying fixes..."

			local -a apply_cmd=(amp apply-fixes --file "$fixes_file")
			"${apply_cmd[@]}"
			local apply_exit_code=$?

			if [[ $apply_exit_code -eq 0 ]]; then
				print_success "Fixes applied successfully"
			else
				print_error "Failed to apply some fixes"
				return 1
			fi
		else
			print_info "Use --auto-apply flag to automatically apply fixes"
			print_info "Review fixes file: $fixes_file"
		fi

		return 0
	else
		print_error "Fix analysis failed after ${duration}s"
		return 1
	fi
}

# Show AmpCode status
show_status() {
	print_header "AmpCode CLI Status"

	# Check CLI installation
	if check_ampcode_cli; then
		echo ""
	else
		print_info "Run: $0 install"
		echo ""
	fi

	# Check configuration
	echo "Configuration Status:"
	if load_api_config; then
		print_success "API Key: ✅ Configured"
	else
		print_warning "API Key: ⚠️ Not configured"
		print_info "Run: $0 setup"
	fi

	if [[ -f "$AMPCODE_API_CONFIG" ]]; then
		print_success "Config File: ✅ $AMPCODE_API_CONFIG"
	else
		print_warning "Config File: ❌ Not found"
	fi

	echo ""
	print_info "Recent Results:"
	if [[ -d "$AMPCODE_RESULTS_DIR" ]]; then
		local -a result_files=()
		while IFS= read -r -d '' f; do
			result_files+=("$f")
		done < <(find "$AMPCODE_RESULTS_DIR" \( -name "*.json" -o -name "*.md" \) -print0 | sort -z -r)

		local shown=0
		local file size ext
		for file in "${result_files[@]}"; do
			[[ $shown -ge 3 ]] && break
			size=$(du -h "$file" | cut -f1 || echo "unknown")
			ext="${file##*.}"
			print_info "  $(basename "$file") (${ext} - $size)"
			((++shown))
		done
	fi

	return 0
}

# Show help
show_help() {
	print_header "AmpCode CLI Integration Help"
	echo ""
	echo "Usage: $0 [command] [options]"
	echo ""
	echo "Commands:"
	echo "  install           - Install AmpCode CLI"
	echo "  setup             - Configure AmpCode with API key"
	echo "  scan [path]       - Run code scan and analysis"
	echo "  review [path]     - Get AI code review"
	echo "  fix [path]        - Apply AI-suggested fixes"
	echo "  status            - Check AmpCode status"
	echo "  help              - Show this help message"
	echo ""
	echo "Examples:"
	echo "  $0 install"
	echo "  $0 setup"
	echo "  $0 scan ./src"
	echo "  $0 review --severity high"
	echo "  $0 fix --auto-apply"
	echo ""
	echo "Setup:"
	echo "  1. Visit https://ampcode.com to create account"
	echo "  2. Get your API key"
	echo "  3. Run: Add AMPCODE_API_KEY to ~/.config/aidevops/credentials.sh"
	echo "  4. Run: $0 setup"
	echo ""
	echo "This script integrates AmpCode's professional AI coding assistant"
	echo "with the AI DevOps Framework for enhanced code quality and productivity."
	echo ""
	return 0
}

# Main function
main() {
	local command="${1:-help}"
	shift || true

	# Ensure temp directory exists
	mkdir -p .agents/tmp

	case "$command" in
	"install")
		install_ampcode_cli
		;;
	"setup")
		setup_ampcode_config
		;;
	"scan")
		run_code_scan "${1:-.}" "${2:-json}"
		;;
	"review")
		get_ai_review "${1:-.}" "${2:-medium}"
		;;
	"fix")
		if [[ "${1:-}" == "--auto-apply" ]]; then
			apply_fixes "${2:-.}" "true"
		else
			apply_fixes "${1:-.}" "false"
		fi
		;;
	"status")
		show_status
		;;
	"help" | "--help" | "-h")
		show_help
		;;
	*)
		print_error "${ERROR_UNKNOWN_COMMAND:-Unknown command:} $command"
		show_help
		return 1
		;;
	esac
	return 0
}

# Execute main function with all arguments
main "$@"
