pipeline {
    agent any
    
    parameters {
        choice(
            name: 'K8S_VERSION',
            choices: ['1.25', '1.26', '1.27', '1.28'],
            description: 'Kubernetes version to test'
        )
        booleanParam(
            name: 'RUN_ALL_CONFIGS',
            defaultValue: true,
            description: 'Run all configurations (c0-c5)'
        )
        choice(
            name: 'SPECIFIC_CONFIG',
            choices: ['c0', 'c1', 'c2', 'c3', 'c4', 'c5'],
            description: 'Run specific configuration only (ignored if RUN_ALL_CONFIGS is true)'
        )
    }
    
    stages {
        stage('Setup Configuration Matrix') {
            steps {
                script {
                    // Define host types and their available nodes
                    def hostTypes = [
                        'xeon': ['xeon-node-1', 'xeon-node-2'],
                        'gaudi': ['gaudi-node-1', 'gaudi-node-2']
                    ]
                    
                    // Configuration definitions
                    def configurations = [
                        'c0': [
                            name: 'Default (All Off)',
                            hpa: false,
                            rbac: false,
                            fqdn: false,
                            balloon: false,
                            gaudi_operator: false,
                            hostTypes: ['xeon', 'gaudi']
                        ],
                        'c1': [
                            name: 'HPA On',
                            hpa: true,
                            rbac: false,
                            fqdn: false,
                            balloon: false,
                            gaudi_operator: false,
                            hostTypes: ['xeon', 'gaudi']
                        ],
                        'c2': [
                            name: 'RBAC On',
                            hpa: false,
                            rbac: true,
                            fqdn: false,
                            balloon: false,
                            gaudi_operator: false,
                            hostTypes: ['xeon', 'gaudi']
                        ],
                        'c3': [
                            name: 'FQDN On',
                            hpa: false,
                            rbac: false,
                            fqdn: true,
                            balloon: false,
                            gaudi_operator: false,
                            hostTypes: ['xeon', 'gaudi']
                        ],
                        'c4': [
                            name: 'Balloon On (Xeon Only)',
                            hpa: false,
                            rbac: false,
                            fqdn: false,
                            balloon: true,
                            gaudi_operator: false,
                            hostTypes: ['xeon'] // Only xeon supports balloon
                        ],
                        'c5': [
                            name: 'HPA + RBAC + FQDN On',
                            hpa: true,
                            rbac: true,
                            fqdn: true,
                            balloon: false,
                            gaudi_operator: false,
                            hostTypes: ['xeon', 'gaudi']
                        ]
                    ]
                    
                    // Determine which configurations to run
                    def configsToRun = []
                    if (params.RUN_ALL_CONFIGS) {
                        configsToRun = configurations.keySet().toList()
                    } else {
                        configsToRun = [params.SPECIFIC_CONFIG]
                    }
                    
                    echo "=== Release Configuration Matrix ==="
                    echo "Kubernetes Version: ${params.K8S_VERSION}"
                    echo "Configurations to run: ${configsToRun.join(', ')}"
                    echo "======================================="
                    
                    // Store for use in parallel stages
                    env.CONFIGS_TO_RUN = configsToRun.join(',')
                    env.HOST_TYPES_JSON = writeJSON returnText: true, json: hostTypes
                    env.CONFIGURATIONS_JSON = writeJSON returnText: true, json: configurations
                }
            }
        }
        
        stage('Execute Configuration Matrix') {
            steps {
                script {
                    def hostTypes = readJSON text: env.HOST_TYPES_JSON
                    def configurations = readJSON text: env.CONFIGURATIONS_JSON
                    def configsToRun = env.CONFIGS_TO_RUN.split(',')
                    
                    def parallelStages = [:]
                    
                    // Build parallel stages for each configuration
                    configsToRun.each { configId ->
                        def config = configurations[configId]
                        
                        config.hostTypes.each { hostType ->
                            def stageKey = "${configId}-${hostType}"
                            
                            parallelStages[stageKey] = {
                                stage("${configId} on ${hostType}") {
                                    script {
                                        def nodes = hostTypes[hostType]
                                        def jobTriggered = false
                                        
                                        echo "=== Configuration ${configId} (${config.name}) on ${hostType} ==="
                                        
                                        // Try each node until one succeeds or all fail
                                        for (int i = 0; i < nodes.size() && !jobTriggered; i++) {
                                            def targetNode = nodes[i]
                                            
                                            try {
                                                echo "Attempting to trigger job on ${targetNode}"
                                                
                                                // Determine job parameters based on configuration
                                                def jobParams = [
                                                    string(name: 'GIT_BRANCH_NAME', value: env.GIT_BRANCH ?: 'main'),
                                                    string(name: 'GIT_COMMIT', value: env.GIT_COMMIT ?: ''),
                                                    string(name: 'GIT_AUTHOR', value: env.GIT_AUTHOR ?: ''),
                                                    string(name: 'GIT_EMAIL', value: env.GIT_EMAIL ?: ''),
                                                    string(name: 'TEST_GROUP', value: '*'),
                                                    string(name: 'K8S_VERSION', value: params.K8S_VERSION),
                                                    string(name: 'CONFIG_ID', value: configId),
                                                    booleanParam(name: 'HPA_ENABLED', value: config.hpa),
                                                    booleanParam(name: 'EDP_RBAC_ENABLED', value: config.rbac),
                                                    booleanParam(name: 'BALLOONS_ENABLED', value: config.balloon),
                                                    booleanParam(name: 'GAUDI_OPERATOR', value: config.gaudi_operator)
                                                ]
                                                
                                                // Add FQDN parameter if enabled
                                                if (config.fqdn) {
                                                    jobParams.add(string(name: 'FQDN', value: 'test.erag.com'))
                                                }
                                                
                                                // Trigger the job
                                                build job: "../${targetNode}", 
                                                      parameters: jobParams,
                                                      wait: false
                                                
                                                echo "✓ Successfully triggered job on ${targetNode}"
                                                jobTriggered = true
                                                
                                            } catch (Exception e) {
                                                echo "✗ Failed to trigger job on ${targetNode}: ${e.message}"
                                                if (i < nodes.size() - 1) {
                                                    echo "→ Retrying on next available node..."
                                                }
                                            }
                                        }
                                        
                                        if (!jobTriggered) {
                                            echo "⚠ WARNING: Failed to trigger job on all ${hostType} nodes for ${configId}"
                                            echo "→ Proceeding with next configuration as requested"
                                        }
                                    }
                                }
                            }
                        }
                    }
                    
                    // Execute all configurations in parallel
                    parallel parallelStages
                }
            }
        }
        
        stage('Summary') {
            steps {
                script {
                    echo "=== Matrix Execution Summary ==="
                    echo "Kubernetes Version: ${params.K8S_VERSION}"
                    echo "Configurations executed: ${env.CONFIGS_TO_RUN}"
                    echo "All configuration jobs have been triggered"
                    echo "Check individual job logs for execution status"
                    echo "==============================="
                }
            }
        }
        
        stage('Cleanup') {
            steps {
                cleanWs()
            }
        }
    }
}

simplify