#!/bin/bash
# Setup Platform Configuration with Forms
# Uses TypeDialog bash wrappers if available, falls back to basic prompts

set -euo pipefail

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

PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../" && pwd)"
TYPEDIALOG_DIR="${PROJECT_ROOT}/provisioning/.typedialog/core"
SHLIB_DIR="${PROJECT_ROOT}/provisioning/core/shlib"
CONFIG_DIR="${PROJECT_ROOT}/provisioning/platform/config"

echo -e "${BLUE}═════════════════════════════════════════════════════════════${NC}"
echo -e "${BLUE}Platform Configuration Setup${NC}"
echo -e "${BLUE}═════════════════════════════════════════════════════════════${NC}"
echo ""

# Check if TypeDialog is available
if command -v typedialog &> /dev/null; then
    echo -e "${GREEN}✅ TypeDialog found${NC}"
    USE_TYPEDIALOG=true
else
    echo -e "${YELLOW}⚠️  TypeDialog not installed${NC}"
    USE_TYPEDIALOG=false
fi

# Function: Setup with TypeDialog
setup_with_typedialog() {
    local service=$1
    local mode=$2

    echo -e "${BLUE}→ Configuring $service for $mode mode (TypeDialog)${NC}"

    local form="${TYPEDIALOG_DIR}/provisioning/platform/forms/${service}.form.toml"
    local output="${CONFIG_DIR}/runtime/${service}.${mode}.ncl"

    if [ ! -f "$form" ]; then
        echo -e "${YELLOW}⚠️  Form not found: $form${NC}"
        echo "    Generating form from schema..."

        local schema="${PROJECT_ROOT}/provisioning/schemas/platform/${service}.ncl"
        if [ -f "$schema" ]; then
            mkdir -p "$(dirname "$form")"
            typedialog generate-form \
                --schema "$schema" \
                --output "$form" \
                --description "Configure ${service} service"
            echo -e "${GREEN}✅ Form generated: $form${NC}"
        else
            echo -e "${YELLOW}⚠️  Schema not found: $schema${NC}"
            return 1
        fi
    fi

    # Run interactive form
    mkdir -p "$(dirname "$output")"
    typedialog run-form \
        --form "$form" \
        --output "$output" \
        --validate

    echo -e "${GREEN}✅ Config saved: $output${NC}"

    # Export to TOML
    local toml="${CONFIG_DIR}/runtime/generated/${service}.${mode}.toml"
    mkdir -p "$(dirname "$toml")"
    nickel export --format toml "$output" > "$toml"
    echo -e "${GREEN}✅ TOML exported: $toml${NC}"
}

# Function: Setup with basic prompts (Fallback)
setup_with_fallback() {
    local service=$1
    local mode=$2

    echo -e "${BLUE}→ Configuring $service for $mode mode (basic prompts)${NC}"
    echo -e "${YELLOW}⚠️  TypeDialog not available - using basic configuration${NC}"

    local output="${CONFIG_DIR}/runtime/values/${service}.${mode}.ncl"
    mkdir -p "$(dirname "$output")"

    echo ""
    echo "Using default configuration for $service in $mode mode"
    echo "To customize, install TypeDialog or edit: $output"
    echo ""

    # Use Nushell wizard with basic prompts as fallback
    if command -v nu &> /dev/null; then
        echo -e "${BLUE}→ Running Nushell setup wizard (basic prompts)${NC}"
        nu -c "use ${PROJECT_ROOT}/provisioning/core/nulib/lib_provisioning/setup/wizard.nu *; run-setup-wizard" || true
    else
        echo -e "${RED}✗ Nushell not available - cannot run fallback wizard${NC}"
        echo "  Please install TypeDialog for full form support"
        return 1
    fi
}

# Main setup flow
main() {
    local services=("orchestrator" "control-center" "vault-service" "rag" "extension-registry" "mcp-server" "provisioning-daemon" "ai-service")
    local modes=("solo" "multiuser" "enterprise" "cicd")

    echo "Select configuration:"
    echo "1) Interactive (configure one service)"
    echo "2) Batch (configure all services)"
    echo "3) Skip"
    echo ""
    read -rp "Choice (1-3): " choice

    case $choice in
        1)
            echo ""
            echo "Available services:"
            for i in "${!services[@]}"; do
                echo "$((i+1))) ${services[$i]}"
            done
            read -rp "Select service (1-${#services[@]}): " service_choice

            local service_idx=$((service_choice - 1))
            if [ $service_idx -ge 0 ] && [ $service_idx -lt ${#services[@]} ]; then
                local selected_service="${services[$service_idx]}"

                echo ""
                echo "Deployment modes:"
                for i in "${!modes[@]}"; do
                    echo "$((i+1))) ${modes[$i]}"
                done
                read -rp "Select mode (1-${#modes[@]}): " mode_choice

                local mode_idx=$((mode_choice - 1))
                if [ $mode_idx -ge 0 ] && [ $mode_idx -lt ${#modes[@]} ]; then
                    local selected_mode="${modes[$mode_idx]}"

                    if [ "$USE_TYPEDIALOG" = true ]; then
                        setup_with_typedialog "$selected_service" "$selected_mode"
                    else
                        setup_with_fallback "$selected_service" "$selected_mode"
                    fi
                fi
            fi
            ;;
        2)
            echo ""
            echo -e "${YELLOW}Batch configuration - this may take a while${NC}"
            for service in "${services[@]}"; do
                for mode in "${modes[@]}"; do
                    if [ "$USE_TYPEDIALOG" = true ]; then
                        setup_with_typedialog "$service" "$mode" || true
                    else
                        setup_with_fallback "$service" "$mode" || true
                    fi
                done
            done
            ;;
        3)
            echo "Skipped."
            ;;
        *)
            echo "Invalid choice"
            exit 1
            ;;
    esac

    echo ""
    echo -e "${GREEN}═════════════════════════════════════════════════════════════${NC}"
    echo -e "${GREEN}✅ Setup complete!${NC}"
    echo -e "${GREEN}═════════════════════════════════════════════════════════════${NC}"
    echo ""
    echo "Generated configs:"
    ls -lh "${CONFIG_DIR}/runtime/generated/"*.toml 2>/dev/null || echo "No configs generated"
}

main "$@"
