#!/usr/bin/env bash
# ensure-typedialog.sh
# Ensures TypeDialog is installed and available in PATH
# Used by setup commands and scripts that depend on TypeDialog
#
# Usage:
#   source ensure-typedialog.sh        # Load as functions
#   ensure_typedialog_installed        # Check and install if needed
#   ensure_typedialog_component tui    # Ensure specific component

set -euo pipefail

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# Configuration
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
INSTALLER_SCRIPT="${SCRIPT_DIR}/install-typedialog.sh"

# ============================================================================
# Helper Functions
# ============================================================================

print_info() {
    echo -e "${BLUE}ℹ️  $1${NC}" >&2
}

print_success() {
    echo -e "${GREEN}✅ $1${NC}" >&2
}

print_warning() {
    echo -e "${YELLOW}⚠️  $1${NC}" >&2
}

print_error() {
    echo -e "${RED}❌ $1${NC}" >&2
}

check_command() {
    command -v "$1" &> /dev/null
}

# ============================================================================
# TypeDialog Installation Checks
# ============================================================================

ensure_typedialog_installed() {
    local force=${1:-false}

    if check_command "typedialog"; then
        local version=$(typedialog --version 2>/dev/null | head -1)
        print_success "TypeDialog available ($version)"
        return 0
    fi

    if [[ "$force" == "true" ]]; then
        print_warning "TypeDialog not found - installing..."

        if [[ ! -f "$INSTALLER_SCRIPT" ]]; then
            print_error "TypeDialog installer not found at: $INSTALLER_SCRIPT"
            return 1
        fi

        # Run installer
        if bash "$INSTALLER_SCRIPT" --components all --skip-validation 2>&1 | grep -E "(✅|❌|⚠️)" >&2; then
            if check_command "typedialog"; then
                print_success "TypeDialog installed successfully"
                return 0
            else
                print_error "Installation completed but typedialog not in PATH"
                return 1
            fi
        else
            print_error "TypeDialog installation failed"
            return 1
        fi
    else
        print_warning "TypeDialog not found (--force to install)"
        return 1
    fi
}

ensure_typedialog_component() {
    local component=$1
    local component_binary="typedialog"

    case "$component" in
        cli)        component_binary="typedialog" ;;
        tui)        component_binary="typedialog-tui" ;;
        web)        component_binary="typedialog-web" ;;
        ag)         component_binary="typedialog-ag" ;;
        ai)         component_binary="typedialog-ai" ;;
        prov-gen)   component_binary="typedialog-prov-gen" ;;
        *)
            print_error "Unknown component: $component"
            return 1
            ;;
    esac

    if check_command "$component_binary"; then
        local version=$("$component_binary" --version 2>/dev/null | head -1 || echo "unknown")
        print_success "TypeDialog $component available ($version)"
        return 0
    else
        print_warning "TypeDialog $component not available"
        return 1
    fi
}

ensure_typedialog_backends() {
    local required_backends=${1:-"cli"}  # Default to CLI

    print_info "Checking required backends: $required_backends"

    IFS=',' read -ra backends <<< "$required_backends"

    local missing=()
    for backend in "${backends[@]}"; do
        backend=$(echo "$backend" | xargs)  # trim

        if ! ensure_typedialog_component "$backend"; then
            missing+=("$backend")
        fi
    done

    if [[ ${#missing[@]} -gt 0 ]]; then
        print_warning "Missing backends: ${missing[*]}"
        return 1
    fi

    print_success "All required backends available"
    return 0
}

# ============================================================================
# Version Checking
# ============================================================================

check_typedialog_version() {
    if ! check_command "typedialog"; then
        print_error "TypeDialog not installed"
        return 1
    fi

    local installed=$(typedialog --version 2>/dev/null | head -1 | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' || echo "unknown")
    local required=$(grep -A 2 'name = "typedialog"' "${PROJECT_ROOT}/core/versions.ncl" 2>/dev/null | grep 'current = "' | sed 's/.*current = "\([^"]*\)".*/\1/' || echo "unknown")

    echo "$installed"

    if [[ "$installed" == "$required" ]] || [[ "$required" == "unknown" ]]; then
        return 0
    fi

    print_warning "Version mismatch: installed=$installed, expected=$required"
    return 1
}

# ============================================================================
# Main Entry Point (when run as script)
# ============================================================================

if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    # Script mode
    case "${1:-check}" in
        check)
            ensure_typedialog_installed false
            ;;
        install|ensure)
            ensure_typedialog_installed true
            ;;
        component)
            ensure_typedialog_component "${2:-cli}"
            ;;
        backends)
            ensure_typedialog_backends "${2:-cli}"
            ;;
        version)
            check_typedialog_version
            ;;
        help)
            cat <<EOF
${BLUE}ensure-typedialog.sh${NC}
Helper script to ensure TypeDialog is installed and available

Usage (as script):
  ensure-typedialog.sh check              # Check if installed (non-blocking)
  ensure-typedialog.sh install            # Install if missing (blocking)
  ensure-typedialog.sh component COMP     # Check specific component
  ensure-typedialog.sh backends BACKEND   # Check backends (comma-separated)
  ensure-typedialog.sh version            # Show installed version

Usage (as library):
  source ensure-typedialog.sh
  ensure_typedialog_installed true        # Install if missing
  ensure_typedialog_component tui         # Check TUI backend
  ensure_typedialog_backends "cli,tui"    # Check multiple backends
  check_typedialog_version                # Get version

Examples:
  # In another script:
  source provisioning/scripts/ensure-typedialog.sh
  ensure_typedialog_installed true || exit 1

  # From command line:
  ./ensure-typedialog.sh install
  ./ensure-typedialog.sh backends "cli,tui,web"

EOF
            ;;
        *)
            print_error "Unknown command: $1"
            echo "Use: $0 help"
            exit 1
            ;;
    esac
fi
