# Setup Command Handler
# Routes setup subcommands to appropriate setup modules
# Integrates with complete setup system

use ../../lib_provisioning/setup/mod.nu *
use ../../lib_provisioning/setup/detection.nu *
use ../../lib_provisioning/setup/validation.nu *
use ../../lib_provisioning/setup/wizard.nu *
use ../../lib_provisioning/setup/system.nu *
use ../../lib_provisioning/setup/platform.nu *
use ../../lib_provisioning/setup/provider.nu *
use ../../lib_provisioning/setup/provctl_integration.nu *

# Main setup command handler
export def cmd-setup [
    command: string
    args: list<string>
    --check = false
    --verbose = false
    --yes = false
    --interactive = false
] {
    # Parse command and route appropriately
    match $command {
        "system" => {
            setup-command-system $args --check=$check --verbose=$verbose --interactive=$interactive
        }

        "workspace" => {
            setup-command-workspace $args --check=$check --verbose=$verbose
        }

        "provider" => {
            setup-command-provider $args --check=$check --verbose=$verbose
        }

        "platform" => {
            setup-command-platform $args --check=$check --verbose=$verbose
        }

        "profile" => {
            setup-command-profile $args --check=$check --verbose=$verbose --interactive=$interactive --yes=$yes
        }

        "update" => {
            setup-command-update $args --check=$check --verbose=$verbose
        }

        "wizard" | "wiz" => {
            setup-command-wizard --verbose=$verbose
        }

        "validate" | "val" => {
            setup-command-validate --verbose=$verbose
        }

        "detect" | "detection" => {
            setup-command-detect --verbose=$verbose
        }

        "migrate" | "migration" => {
            setup-command-migrate $args --verbose=$verbose
        }

        "status" => {
            setup-command-status --verbose=$verbose
        }

        "versions" | "gen-versions" => {
            setup-command-versions $args --verbose=$verbose
        }

        "help" | "h" | "" => {
            print-setup-help
        }

        _ => {
            print-setup-help
        }
    }
}

# ============================================================================
# SETUP SUBCOMMAND HANDLERS
# ============================================================================

# Complete system setup
def setup-command-system [
    args: list<string>
    --check
    --verbose
    --interactive
] {
    # Only show help if explicitly requested
    if ($args | any { |a| $a == "--help" or $a == "-h" }) {
        print ""
        print "Setup System Configuration"
        print "─────────────────────────────────────────────────────────────"
        print ""
        print "USAGE:"
        print "  provisioning setup system [OPTIONS]"
        print ""
        print "OPTIONS:"
        print "  --interactive         Run interactive wizard (default)"
        print "  --defaults            Use recommended defaults"
        print "  --minimal             Minimal configuration"
        print "  --check, -c           Dry-run without changes"
        print "  --verbose, -v         Verbose output"
        print ""
        print "EXAMPLES:"
        print "  provisioning setup system --interactive"
        print "  provisioning setup system --defaults"
        print "  provisioning setup system --minimal"
        return
    }

    let mode = if ($args | any { |a| $a == "--defaults" }) {
        "defaults"
    } else if ($args | any { |a| $a == "--minimal" }) {
        "minimal"
    } else {
        "interactive"
    }

    match $mode {
        "interactive" => {
            print ""
            let result = (run-interactive-setup --verbose=$verbose)
            if $result.success {
                print-setup-success "System setup completed successfully!"
                print-setup-status
            } else {
                print-setup-error $"Setup failed: ($result.reason)"
            }
        }
        "defaults" => {
            print ""
            let result = (run-setup-defaults --verbose=$verbose)
            if $result.success {
                print-setup-success "System setup completed with defaults!"
                print-setup-status
            } else {
                print-setup-error $"Setup failed: ($result.reason)"
            }
        }
        "minimal" => {
            print ""
            let result = (run-setup-minimal --verbose=$verbose)
            if $result.success {
                print-setup-success "Minimal system setup completed!"
                print-setup-status
            } else {
                print-setup-error $"Setup failed: ($result.reason)"
            }
        }
    }
}

# Workspace setup
def setup-command-workspace [
    args: list<string>
    --check
    --verbose
] {
    if ($args | length) == 0 {
        print ""
        print "Setup Workspace"
        print "─────────────────────────────────────────────────────────────"
        print ""
        print "USAGE:"
        print "  provisioning setup workspace <name> [OPTIONS]"
        print ""
        print "OPTIONS:"
        print "  --check, -c           Dry-run without changes"
        print "  --verbose, -v         Verbose output"
        print ""
        print "EXAMPLES:"
        print "  provisioning setup workspace myproject"
        print "  provisioning setup workspace myproject --check"
        return
    }

    let workspace_name = ($args | get 0)
    print-setup-header $"Setting up Workspace: ($workspace_name)"
    print ""
    print-setup-info "Workspace setup not yet implemented"
    print "Please use: provisioning workspace init ($workspace_name)"
}

# Provider setup
def setup-command-provider [
    args: list<string>
    --check
    --verbose
] {
    if ($args | length) == 0 {
        print ""
        print "Setup Provider Configuration"
        print "─────────────────────────────────────────────────────────────"
        print ""
        print "USAGE:"
        print "  provisioning setup provider <name> [OPTIONS]"
        print ""
        print "AVAILABLE PROVIDERS:"
        print "  upcloud               UpCloud infrastructure provider"
        print "  aws                   Amazon Web Services provider"
        print "  hetzner               Hetzner Cloud provider"
        print "  local                 Local development provider (no credentials needed)"
        print ""
        print "OPTIONS:"
        print "  --check, -c           Dry-run without changes"
        print "  --verbose, -v         Verbose output"
        print ""
        print "EXAMPLES:"
        print "  provisioning setup provider upcloud"
        print "  provisioning setup provider aws --verbose"
        print ""
        print "CREDENTIALS:"
        print "All provider credentials are stored encrypted in RustyVault."
        print "Config files contain references only, never actual credentials."
        return
    }

    let provider = ($args | get 0)
    let config_base = (get-config-base-path)
    let result = (setup-provider $provider $config_base)

    if $result.success {
        print-setup-success $"Provider ($provider) configured successfully"
        print-provider-setup-instructions
    } else {
        print-setup-error $result.error
    }
}

# Platform services setup
def setup-command-platform [
    args: list<string>
    --check
    --verbose
] {
    if ($args | length) == 0 {
        print ""
        print "Setup Platform Services"
        print "─────────────────────────────────────────────────────────────"
        print ""
        print "USAGE:"
        print "  provisioning setup platform [MODE] [OPTIONS]"
        print ""
        print "MODES:"
        print "  solo                  Single-user local development (Docker Compose)"
        print "  multiuser             Team environment (Docker/Kubernetes/SSH)"
        print "  cicd                  CI/CD pipeline deployment (Kubernetes)"
        print ""
        print "OPTIONS:"
        print "  --check, -c           Dry-run without changes"
        print "  --verbose, -v         Verbose output"
        print ""
        print "EXAMPLES:"
        print "  provisioning setup platform solo"
        print "  provisioning setup platform multiuser --verbose"
        print "  provisioning setup platform cicd --check"
        return
    }

    let mode = ($args | get 0) | default "solo"
    let result = (setup-platform-complete $mode --verbose=$verbose)

    if $result.success {
        print-setup-success "Platform services setup completed"
        print-platform-status
    } else {
        print-setup-error $"Platform setup failed: ($result.error)"
    }
}

# Unified profile-based setup
def setup-command-profile [
    args: list<string>
    --check
    --verbose
    --interactive
    --yes
] {
    if ($args | any { |a| $a == "--help" or $a == "-h" }) {
        print ""
        print "Setup via Profile (Unified Setup System)"
        print "─────────────────────────────────────────────────────────────"
        print ""
        print "USAGE:"
        print "  provisioning setup profile [OPTIONS]"
        print "  provisioning setup profile --profile <developer|production|cicd>"
        print ""
        print "PROFILES:"
        print "  developer               Fast local setup (<5 min, Docker Compose)"
        print "  production              Full validated setup (Kubernetes, HA, security)"
        print "  cicd                    Ephemeral pipeline setup (automated, cleanup)"
        print ""
        print "OPTIONS:"
        print "  --profile <PROFILE>     Specify profile (asks if not provided)"
        print "  --interactive, -i       Interactive mode (default if TTY)"
        print "  --yes, -y               Skip confirmations"
        print "  --check, -c             Dry-run without changes"
        print "  --verbose, -v           Verbose output"
        print ""
        print "EXAMPLES:"
        print "  provisioning setup profile --profile developer"
        print "  provisioning setup profile --profile production --interactive"
        print "  provisioning setup profile --yes --verbose"
        return
    }

    # Extract profile from args or prompt
    mut profile = ""
    mut idx = 0
    while ($idx < ($args | length)) {
        let arg = ($args | get $idx)
        if ($arg | str starts-with "--profile") {
            if ($arg | str contains "=") {
                # Format: --profile=developer
                let parts = ($arg | split column "=" --collapse-empty)
                $profile = (($parts.column1 | get 1) | str trim)
            } else if (($idx + 1) < ($args | length)) {
                # Format: --profile developer
                $profile = ($args | get ($idx + 1) | str trim)
                $idx = ($idx + 1)
            }
            break
        }
        $idx = ($idx + 1)
    }

    # Determine profile to use
    let selected_profile = if ($profile != "") {
        # Validate profile argument
        if ($profile in ["developer", "production", "cicd"]) {
            $profile
        } else {
            print-setup-error $"Invalid profile: ($profile). Must be: developer, production, or cicd"
            return
        }
    } else if $interactive {
        # Interactive mode - prompt for profile
        (prompt-profile-selection)
    } else if $yes {
        # Assume developer profile if --yes without --profile
        "developer"
    } else {
        # Default to interactive mode
        (prompt-profile-selection)
    }

    print-setup-header "Setup Profile: $(($selected_profile | str upcase))"
    print ""

    # Get config base path (platform-specific)
    let config_base = (get-config-base-path)

    if $check {
        print-setup-warning "DRY-RUN MODE - No changes will be made"
        print ""
    }

    # Execute profile-specific setup
    let result = (match $selected_profile {
        "developer" => {
            setup-platform-developer $config_base --verbose=$verbose
        }
        "production" => {
            setup-platform-production $config_base --verbose=$verbose
        }
        "cicd" => {
            setup-platform-cicd-nickel $config_base --verbose=$verbose
        }
        _ => {
            {
                success: false
                error: $"Unknown profile: ($selected_profile)"
            }
        }
    })

    if $result.success {
        print-setup-success $"Profile setup completed: ($selected_profile)"
        print ""
        print "Configuration Details:"
        print $"  Profile:       ($selected_profile)"
        print $"  Location:      ($config_base)"
        print $"  Deployment:    ($result.deployment | default 'unknown')"
        print ""
        print-setup-success "Services configured and ready to start"
    } else {
        print-setup-error $"Profile setup failed: ($result.error)"
    }
}

# Update configuration
def setup-command-update [
    args: list<string>
    --check
    --verbose
] {
    print ""
    print "Update Provisioning Configuration"
    print "─────────────────────────────────────────────────────────────"
    print ""
    print "USAGE:"
    print "  provisioning setup update [COMPONENT] [OPTIONS]"
    print ""
    print "COMPONENTS:"
    print "  provider                Update provider configuration"
    print "  platform                Update platform services"
    print "  preferences             Update user preferences"
    print ""
    print "This command updates existing configuration without re-running"
    print "the complete setup wizard. IMMUTABLE settings cannot be changed."
    print ""
    print-setup-info "Update functionality not yet implemented"
}

# Interactive wizard
def setup-command-wizard [
    --verbose
] {
    let result = (run-setup-wizard --verbose=$verbose)

    if $result.completed {
        print ""
        print-setup-success "Setup configuration confirmed!"
        print ""
    } else {
        print ""
        print-setup-warning "Setup wizard cancelled by user"
    }
}

# Validate configuration
def setup-command-validate [
    --verbose
] {
    print-setup-header "Validating Provisioning Configuration"
    print ""

    let config_base = (get-config-base-path)

    # Load and validate system config
    let system_config = (load-config-toml $"($config_base)/system.toml")
    let system_validation = (validate-system-config $system_config)

    if $verbose {
        print-validation-report $system_validation
    }

    # Load and validate platform config
    let platform_config = (load-config-toml $"($config_base)/platform/deployment.toml")
    let platform_validation = (validate-platform-config $platform_config)

    if $verbose {
        print-validation-report $platform_validation
    }

    if ($system_validation.valid and $platform_validation.valid) {
        print-setup-success "All configurations are valid!"
    } else {
        print-setup-error "Some configurations have errors"
    }
}

# Detect system capabilities
def setup-command-detect [
    --verbose
] {
    print-setup-header "Detecting System Capabilities"
    print ""

    let detection_report = (generate-detection-report)
    print-detection-report $detection_report

    if $verbose {
        print ""
        print "Recommended Settings:"
        print "─────────────────────────────────────────────────────────────"
        let recommended = (get-recommended-config $detection_report)
        print $"Deployment Mode: ($recommended.deployment_mode)"
        print $"Supported Modes: ($recommended.supported_modes | to json)"
        if ($recommended.required_tools_missing | length) > 0 {
            print ""
            print "⚠️  Missing Required Tools:"
            for tool in $recommended.required_tools_missing {
                print $"  • ($tool)"
            }
        }
    }
}

# Migration
def setup-command-migrate [
    args: list<string>
    --verbose
] {
    if ($args | length) == 0 {
        print ""
        print "Migrate Existing Configuration"
        print "─────────────────────────────────────────────────────────────"
        print ""
        print "This command migrates existing workspace configurations to the"
        print "new setup system with automatic backup and rollback support."
        print ""
        print "USAGE:"
        print "  provisioning setup migrate [OPTIONS]"
        print ""
        print "OPTIONS:"
        print "  --auto                Automatically migrate detected workspaces"
        print "  --workspace <name>    Migrate specific workspace"
        print "  --rollback            Rollback a migration"
        print "  --verbose, -v         Verbose output"
        print ""
        print "EXAMPLES:"
        print "  provisioning setup migrate --auto"
        print "  provisioning setup migrate --workspace librecloud"
        print "  provisioning setup migrate --rollback --workspace librecloud"
        return
    }

    let config_base = (get-config-base-path)

    let auto_migrate = ($args | any { |a| $a == "--auto" })
    if $auto_migrate {
        let result = (auto-migrate-existing $config_base --verbose=$verbose)
        if $result.success {
            print-setup-success $"Migration completed: ($result.migrated_count) workspace(s) migrated"
        } else {
            print-setup-error "Migration failed"
        }
    } else {
        print-setup-info "No migration options specified"
    }
}

# Setup status
def setup-command-status [
    --verbose
] {
    print-setup-status
    print-platform-status

    if $verbose {
        print ""
        print "Detailed Information:"
        print "─────────────────────────────────────────────────────────────"
        let detection = (generate-detection-report)
        print-detection-report $detection
    }
}

# Generate versions file from versions.ncl
def setup-command-versions [
    args: list<string>
    --verbose
] {
    use ../../lib_provisioning/setup/utils.nu create_versions_file

    if ($args | any { |a| $a == "--help" or $a == "-h" }) {
        print ""
        print "Generate Versions File"
        print "─────────────────────────────────────────────────────────────"
        print ""
        print "USAGE:"
        print "  provisioning setup versions [OPTIONS]"
        print ""
        print "OPTIONS:"
        print "  --output FILE         Output filename (default: versions)"
        print "  --help, -h            Show this help message"
        print ""
        print "DESCRIPTION:"
        print "  Generates a bash-compatible versions file from versions.ncl"
        print "  in KEY=VALUE format for use by shell scripts."
        print ""
        return
    }

    let output_file = (
        if ($args | any { |a| $a == "--output" }) {
            let idx = ($args | position { |a| $a == "--output" })
            if ($idx + 1) < ($args | length) {
                $args | get ($idx + 1)
            } else {
                "versions"
            }
        } else {
            "versions"
        }
    )

    print-setup-info $"Generating versions file: ($output_file)"

    if (create_versions_file $output_file) {
        print-setup-success $"Versions file generated successfully"
        if $verbose {
            let provisioning = ($env.PROVISIONING? | default ($env.PWD))
            let versions_file = ($provisioning | path join "core" | path join $output_file)
            print $"Location: ($versions_file)"
            print ""
            print "Content:"
            print (open $versions_file)
        }
    } else {
        print-setup-error "Failed to generate versions file"
    }
}

# ============================================================================
# HELP DISPLAY
# ============================================================================

def print-setup-help [] {
    print ""
    print "╔═══════════════════════════════════════════════════════════════╗"
    print "║              PROVISIONING SETUP SYSTEM                       ║"
    print "║                                                               ║"
    print "║  Complete system initialization and configuration management ║"
    print "╚═══════════════════════════════════════════════════════════════╝"
    print ""

    print "USAGE:"
    print "  provisioning setup <command> [OPTIONS]"
    print ""

    print "COMMANDS:"
    print "  system              Complete system setup (interactive, defaults, minimal)"
    print "  workspace           Create and configure workspaces"
    print "  provider            Setup infrastructure providers (UpCloud, AWS, Hetzner)"
    print "  platform            Configure platform services (Orchestrator, Control-Center, KMS)"
    print "  update              Update existing configuration"
    print "  wizard              Interactive setup wizard"
    print "  validate            Validate current configuration"
    print "  detect              Detect system capabilities"
    print "  migrate             Migrate existing configurations"
    print "  versions            Generate bash-compatible versions file"
    print "  status              Show setup status"
    print "  help                Show this help message"
    print ""

    print "COMMON EXAMPLES:"
    print "  # Interactive setup (recommended)"
    print "  provisioning setup system --interactive"
    print ""
    print "  # Setup with defaults"
    print "  provisioning setup system --defaults"
    print ""
    print "  # Check system capabilities"
    print "  provisioning setup detect --verbose"
    print ""
    print "  # Validate configuration"
    print "  provisioning setup validate"
    print ""
    print "  # Migrate existing workspace"
    print "  provisioning setup migrate --auto"
    print ""
    print "  # Generate bash versions file (for shell scripts)"
    print "  provisioning setup versions"
    print ""

    print "OPTIONS:"
    print "  --check, -c         Dry-run without making changes"
    print "  --verbose, -v       Show detailed output"
    print "  --yes, -y           Auto-confirm prompts"
    print ""

    print "CONFIGURATION LOCATIONS:"
    print "  macOS:              ~/Library/Application Support/provisioning/"
    print "  Linux:              ~/.config/provisioning/"
    print "  Windows:            %APPDATA%/provisioning/"
    print ""

    print "For help on specific commands:"
    print "  provisioning setup <command> --help"
    print ""
}
