# Provisioning Platform Installer - Justfile Module
# Interactive installer, configuration management, and deployment automation
# ===========================================================================

# ============================================================================
# Installer Module Configuration
# ============================================================================

installer_dir := provisioning_root / "platform/installer"
installer_binary := provisioning_root / "platform/target/release/provisioning-installer"
installer_scripts := installer_dir / "scripts"
installer_config_dir := provisioning_root / "config"
installer_examples := installer_config_dir / "installer-examples"

# ============================================================================
# Help and Information
# ============================================================================

# Show installer module help
@installer-help:
    echo "📦 PROVISIONING PLATFORM INSTALLER MODULE"
    echo "=========================================="
    echo ""
    echo "🏗️  BUILD & COMPILE"
    echo "   installer-build         - Build installer binary (release mode)"
    echo "   installer-build-debug   - Build installer with debug symbols"
    echo "   installer-check         - Check installer compilation without building"
    echo "   installer-clean         - Clean installer build artifacts"
    echo ""
    echo "🚀 RUN INSTALLER"
    echo "   installer-run           - Run interactive TUI installer"
    echo "   installer-headless      - Run in headless mode (CLI arguments)"
    echo "   installer-unattended    - Run in unattended mode (config file)"
    echo "   installer-config-only   - Generate config without deploying"
    echo ""
    echo "⚙️  CONFIGURATION MANAGEMENT"
    echo "   config-review           - Review current installer configuration"
    echo "   config-validate         - Validate installer config file"
    echo "   config-template         - Generate config template"
    echo "   config-examples         - List available example configs"
    echo "   config-show-example     - Show specific example config"
    echo ""
    echo "📋 SETTINGS & PREFERENCES"
    echo "   installer-settings      - Show installer settings and defaults"
    echo "   installer-detect        - Detect platform and available tools"
    echo "   installer-resources     - Check system resources"
    echo ""
    echo "🧪 TESTING & VALIDATION"
    echo "   installer-test          - Test installer compilation"
    echo "   installer-test-config   - Test configuration loading"
    echo "   installer-test-deploy   - Test deployment (dry-run)"
    echo ""
    echo "🔧 MCP INTEGRATION"
    echo "   installer-mcp-settings  - Query MCP for installer settings"
    echo "   installer-mcp-status    - Check MCP server status"
    echo ""
    echo "📦 DEPLOYMENT EXAMPLES"
    echo "   installer-solo          - Quick solo developer deployment"
    echo "   installer-team          - Team collaboration deployment"
    echo "   installer-cicd          - CI/CD pipeline deployment"
    echo "   installer-enterprise    - Enterprise production deployment"
    echo ""
    echo "💡 EXAMPLES"
    echo "   # Build and run interactively"
    echo "   just installer-build && just installer-run"
    echo ""
    echo "   # Headless deployment"
    echo "   just installer-headless mode=solo platform=docker"
    echo ""
    echo "   # Unattended from config"
    echo "   just installer-unattended config=provisioning/config/installer-examples/solo.toml"
    echo ""
    echo "   # Validate configuration"
    echo "   just config-validate config=my-config.toml"

# ============================================================================
# Build Recipes
# ============================================================================

# Build installer binary (release mode)
@installer-build:
    echo "🔨 Building provisioning installer (release)..."
    cd {{installer_dir}} && {{cargo}} build --release
    echo "✅ Installer built: {{installer_binary}}"

# Build installer with debug symbols
@installer-build-debug:
    echo "🔨 Building provisioning installer (debug)..."
    cd {{installer_dir}} && {{cargo}} build
    echo "✅ Debug installer built: {{provisioning_root}}/platform/target/debug/provisioning-installer"

# Check installer compilation without building
@installer-check:
    echo "🔍 Checking installer compilation..."
    cd {{installer_dir}} && {{cargo}} check
    echo "✅ Installer check passed"

# Clean installer build artifacts
@installer-clean:
    echo "🧹 Cleaning installer artifacts..."
    cd {{installer_dir}} && {{cargo}} clean
    echo "✅ Installer artifacts cleaned"

# ============================================================================
# Run Installer - Different Modes
# ============================================================================

# Run interactive TUI installer
@installer-run:
    echo "🚀 Launching interactive installer..."
    {{installer_binary}}

# Run installer in headless mode
@installer-headless mode="solo" platform="docker" domain="localhost" services="":
    echo "🚀 Running installer in headless mode..."
    {{installer_binary}} \
        --headless \
        --mode {{mode}} \
        --platform {{platform}} \
        --domain {{domain}} \
        {{if services != "" { "--services " + services } else { "" } }} \
        --yes

# Run installer in unattended mode (requires config file)
@installer-unattended config="":
    #!/usr/bin/env bash
    if [ -z "{{config}}" ]; then
        echo "❌ Error: config file required"
        echo "Usage: just installer-unattended config=path/to/config.toml"
        echo ""
        echo "Example configs available:"
        ls -1 {{installer_examples}}/*.toml | sed 's/^/  - /'
        exit 1
    fi
    echo "🚀 Running installer in unattended mode..."
    echo "Config: {{config}}"
    {{installer_binary}} --unattended --config "{{config}}"

# Generate configuration without deploying
@installer-config-only:
    echo "📝 Generating installer configuration..."
    {{installer_binary}} --config-only
    echo "✅ Configuration saved to ~/.provisioning/installer-config.toml"

# ============================================================================
# Configuration Management
# ============================================================================

# Review current installer configuration
@config-review:
    #!/usr/bin/env bash
    echo "📋 INSTALLER CONFIGURATION REVIEW"
    echo "=================================="
    echo ""

    config_file="$HOME/.provisioning/installer-config.toml"

    if [ -f "$config_file" ]; then
        echo "✅ Configuration file exists: $config_file"
        echo ""
        echo "Contents:"
        cat "$config_file"
    else
        echo "⚠️  No configuration file found at: $config_file"
        echo ""
        echo "Generate one with:"
        echo "  just installer-config-only"
    fi

# Validate installer configuration file
@config-validate config="":
    #!/usr/bin/env bash
    if [ -z "{{config}}" ]; then
        config_file="$HOME/.provisioning/installer-config.toml"
    else
        config_file="{{config}}"
    fi

    echo "🔍 Validating installer configuration..."
    echo "File: $config_file"

    if [ ! -f "$config_file" ]; then
        echo "❌ Error: Configuration file not found: $config_file"
        exit 1
    fi

    # Validate TOML syntax using nu
    {{nu}} -c "open '$config_file' | to toml" > /dev/null 2>&1

    if [ $? -eq 0 ]; then
        echo "✅ Configuration is valid TOML"

        # Show key configuration values
        echo ""
        echo "Key Settings:"
        {{nu}} -c "
            let config = (open '$config_file')
            print $'  Platform: ($config.deployment?.platform? | default \"not set\")'
            print $'  Mode: ($config.deployment?.mode? | default \"not set\")'
            print $'  Domain: ($config.deployment?.domain? | default \"not set\")'
        "
    else
        echo "❌ Configuration has invalid TOML syntax"
        exit 1
    fi

# Generate configuration template
@config-template output="installer-config.toml":
    echo "📄 Generating installer configuration template..."
    cp {{installer_config_dir}}/installer-config.toml.template "{{output}}"
    echo "✅ Template saved to: {{output}}"
    echo ""
    echo "Edit the file and use with:"
    echo "  just installer-unattended config={{output}}"

# List available example configurations
@config-examples:
    #!/usr/bin/env bash
    echo "📚 AVAILABLE EXAMPLE CONFIGURATIONS"
    echo "===================================="
    echo ""
    ls -1 {{installer_examples}}/*.toml | while read file; do
        name=$(basename "$file" .toml)
        size=$(wc -l < "$file" | xargs)
        echo "  📄 $name ($size lines)"
        echo "     Path: $file"
        echo "     Use:  just installer-unattended config=$file"
        echo ""
    done

# Show specific example configuration
@config-show-example name="solo":
    echo "📄 EXAMPLE CONFIGURATION: {{name}}"
    echo "=================================="
    cat {{installer_examples}}/{{name}}.toml

# ============================================================================
# Settings & Detection
# ============================================================================

# Show installer settings and defaults
@installer-settings:
    #!/usr/bin/env bash
    echo "⚙️  INSTALLER SETTINGS & DEFAULTS"
    echo "================================="
    echo ""
    echo "Deployment Modes:"
    echo "  • Solo        - 2 CPU, 4GB RAM,  20GB disk  (5 services)"
    echo "  • Multi-User  - 4 CPU, 8GB RAM,  50GB disk  (7 services)"
    echo "  • CI/CD       - 8 CPU, 16GB RAM, 100GB disk (8-10 services)"
    echo "  • Enterprise  - 16 CPU, 32GB RAM, 500GB disk (15+ services)"
    echo ""
    echo "Supported Platforms:"
    echo "  • Docker      - Standard docker-compose deployment"
    echo "  • Podman      - Rootless container deployment"
    echo "  • Kubernetes  - Production K8s deployment"
    echo "  • OrbStack   - Optimized macOS development"
    echo ""
    echo "Configuration Hierarchy:"
    echo "  1. CLI arguments (highest priority)"
    echo "  2. Environment variables"
    echo "  3. Config file"
    echo "  4. MCP server query"
    echo "  5. System defaults (lowest priority)"

# Detect platform and available tools
@installer-detect:
    #!/usr/bin/env bash
    echo "🔍 PLATFORM DETECTION"
    echo "====================="
    echo ""

    detect_tool() {
        if command -v "$1" >/dev/null 2>&1; then
            version=$($1 --version 2>/dev/null | head -1 || echo "installed")
            echo "  ✅ $1: $version"
            return 0
        else
            echo "  ❌ $1: not found"
            return 1
        fi
    }

    echo "Container Platforms:"
    detect_tool docker
    detect_tool podman
    detect_tool orb
    detect_tool kubectl

    echo ""
    echo "Build Tools:"
    detect_tool cargo
    detect_tool rustc

    echo ""
    echo "Provisioning Tools:"
    detect_tool nu
    detect_tool kcl

# Check system resources
@installer-resources:
    #!/usr/bin/env bash
    echo "💻 SYSTEM RESOURCES"
    echo "==================="
    echo ""

    # CPU
    if [[ "$OSTYPE" == "darwin"* ]]; then
        cpus=$(sysctl -n hw.ncpu)
        mem_gb=$(echo "$(sysctl -n hw.memsize) / 1024 / 1024 / 1024" | bc)
    else
        cpus=$(nproc)
        mem_gb=$(free -g | awk '/^Mem:/{print $2}')
    fi

    echo "CPU Cores: $cpus"
    echo "Memory: ${mem_gb}GB"
    echo ""

    # Recommendations
    echo "Mode Recommendations:"
    if [ "$cpus" -ge 16 ] && [ "$mem_gb" -ge 32 ]; then
        echo "  ✅ Enterprise mode supported"
    fi
    if [ "$cpus" -ge 8 ] && [ "$mem_gb" -ge 16 ]; then
        echo "  ✅ CI/CD mode supported"
    fi
    if [ "$cpus" -ge 4 ] && [ "$mem_gb" -ge 8 ]; then
        echo "  ✅ Multi-User mode supported"
    fi
    if [ "$cpus" -ge 2 ] && [ "$mem_gb" -ge 4 ]; then
        echo "  ✅ Solo mode supported"
    else
        echo "  ⚠️  Insufficient resources for any mode"
    fi

# ============================================================================
# Testing & Validation
# ============================================================================

# Test installer compilation
@installer-test:
    echo "🧪 Testing installer compilation..."
    cd {{installer_dir}} && {{cargo}} test
    echo "✅ Installer tests passed"

# Test configuration loading
@installer-test-config:
    #!/usr/bin/env bash
    echo "🧪 Testing configuration loading..."
    {{nu}} -c "
        use {{installer_scripts}}/helpers.nu *
        let result = check-prerequisites
        print $result
    "
    echo "✅ Configuration loading test completed"

# Test deployment (dry-run)
@installer-test-deploy mode="solo" platform="docker":
    echo "🧪 Testing deployment (dry-run)..."
    {{installer_binary}} \
        --headless \
        --mode {{mode}} \
        --platform {{platform}} \
        --config-only
    echo "✅ Deployment test completed (no actual deployment)"

# ============================================================================
# MCP Integration
# ============================================================================

# Query MCP server for installer settings
@installer-mcp-settings query="":
    #!/usr/bin/env bash
    mcp_url="${PROVISIONING_MCP_URL:-http://localhost:8084}"

    echo "🤖 Querying MCP server for installer settings..."
    echo "MCP URL: $mcp_url"

    if [ -n "{{query}}" ]; then
        echo "Query: {{query}}"
    fi

    curl -s "$mcp_url/tools/installer_get_settings" \
        -H "Content-Type: application/json" \
        -d "{\"query\": \"{{query}}\"}" | jq .

    if [ $? -ne 0 ]; then
        echo "❌ Failed to query MCP server"
        echo "Make sure MCP server is running: just mcp-server"
    fi

# Check MCP server status
@installer-mcp-status:
    #!/usr/bin/env bash
    mcp_url="${PROVISIONING_MCP_URL:-http://localhost:8084}"

    echo "🔍 Checking MCP server status..."

    if curl -s -f "$mcp_url/health" > /dev/null 2>&1; then
        echo "✅ MCP server is running at $mcp_url"
    else
        echo "❌ MCP server is not accessible at $mcp_url"
        echo "Start it with: just mcp-server"
    fi

# ============================================================================
# Quick Deployment Examples
# ============================================================================

# Quick solo developer deployment
@installer-solo:
    echo "🚀 Quick Solo Developer Deployment"
    echo "==================================="
    just installer-headless mode=solo platform=docker

# Team collaboration deployment
@installer-team domain="localhost":
    echo "🚀 Team Collaboration Deployment"
    echo "================================="
    just installer-headless mode=multi-user platform=docker domain={{domain}}

# CI/CD pipeline deployment
@installer-cicd:
    echo "🚀 CI/CD Pipeline Deployment"
    echo "============================"
    just installer-unattended config={{installer_examples}}/cicd.toml

# Enterprise production deployment
@installer-enterprise:
    echo "🚀 Enterprise Production Deployment"
    echo "===================================="
    just installer-unattended config={{installer_examples}}/enterprise.toml

# ============================================================================
# Installation & Update Management
# ============================================================================

# Install provisioning platform using installer
@install mode="solo" platform="":
    #!/usr/bin/env bash
    echo "📦 INSTALLING PROVISIONING PLATFORM"
    echo "===================================="

    # Auto-detect platform if not specified
    if [ -z "{{platform}}" ]; then
        if command -v docker >/dev/null 2>&1; then
            platform="docker"
        elif command -v podman >/dev/null 2>&1; then
            platform="podman"
        elif command -v kubectl >/dev/null 2>&1; then
            platform="kubernetes"
        else
            echo "❌ No supported platform found"
            echo "Install one of: docker, podman, kubectl"
            exit 1
        fi
    else
        platform="{{platform}}"
    fi

    echo "Mode: {{mode}}"
    echo "Platform: $platform"
    echo ""

    just installer-build
    just installer-headless {{mode}} $platform

# Update existing installation
@update config="":
    #!/usr/bin/env bash
    echo "🔄 UPDATING PROVISIONING PLATFORM"
    echo "=================================="

    if [ -z "{{config}}" ]; then
        config_file="$HOME/.provisioning/installer-config.toml"
    else
        config_file="{{config}}"
    fi

    if [ ! -f "$config_file" ]; then
        echo "❌ No configuration file found"
        echo "Cannot update without existing configuration"
        exit 1
    fi

    echo "Using config: $config_file"
    just installer-build
    just installer-unattended config=$config_file

# Show installation status
@install-status:
    #!/usr/bin/env bash
    echo "📊 INSTALLATION STATUS"
    echo "======================"

    config_file="$HOME/.provisioning/installer-config.toml"

    if [ -f "$config_file" ]; then
        echo "✅ Configuration exists: $config_file"

        # Try to detect running services
        if command -v docker >/dev/null 2>&1; then
            echo ""
            echo "Docker Services:"
            docker ps --filter "label=provisioning.platform=true" --format "table {{"{{"}}.Names{{"}}"}}\t{{"{{"}}.Status{{"}}"}}" 2>/dev/null || echo "  No running services"
        fi

        if command -v kubectl >/dev/null 2>&1; then
            echo ""
            echo "Kubernetes Services:"
            kubectl get pods -n provisioning-platform 2>/dev/null || echo "  No running services"
        fi
    else
        echo "⚠️  No installation detected"
        echo ""
        echo "Install with:"
        echo "  just install mode=solo"
    fi
