pipeline {
    agent any

    parameters {
        choice(
            name: 'PLAYBOOK',
            choices: ['dockerUpdate.yml', 'dockerPrune.yaml'],
            description: 'Select the playbook to run'
        )
        string(
            name: 'LIMIT',
            defaultValue: '',
            description: 'Limit to specific hosts or groups (e.g., "vms", "lxcs", "docker_hosts", or hostname) no.lan required'
        )
        booleanParam(
            name: 'DRY_RUN',
            defaultValue: false,
            description: 'Run in check mode (no changes made)'
        )
    }

    environment {
        PROXMOX_URL = 'https://192.168.0.166:8006'
        PROXMOX_USER = 'dynamic-inventory@pve'
        PROXMOX_TOKEN_ID = 'dynamic-inventory'
        PROXMOX_TOKEN_SECRET = credentials('PROXMOX_TOKEN_SECRET')
        ANSIBLE_HOST_KEY_CHECKING = 'False'
    }

    stages {
        stage('Checkout') {
            steps {
                checkout scm
            }
        }

        stage('Verify Inventory') {
            steps {
                sh '''
                    echo "Testing dynamic inventory connection..."
                    ansible-inventory -i inventories/inventory.proxmox.yml --list | head -10
                '''
            }
        }

        stage('Run Playbook') {
            steps {
                script {
                    def dockerPlaybooks = ['dockerUpdate.yml', 'dockerPrune.yaml']
                    def isDockerPlaybook = params.PLAYBOOK in dockerPlaybooks

                    // Build the limit flag
                    def limitValue = ''
                    if (isDockerPlaybook) {
                        // Docker playbooks always target 'docker_hosts' group
                        // If user provides a limit, use intersection (docker_hosts AND limit)
                        limitValue = params.LIMIT ? "docker_hosts:&${params.LIMIT}" : 'docker_hosts'
                    } else {
                        limitValue = params.LIMIT ?: ''
                    }

                    def limitFlag = limitValue ? "--limit '${limitValue}'" : ''
                    def checkFlag = (params.DRY_RUN == true) ? '--check --diff' : ''

                    echo "DRY_RUN parameter: ${params.DRY_RUN}"
                    echo "Check flag: '${checkFlag}'"
                    echo "Limit: '${limitValue}'"
                    if (isDockerPlaybook) {
                        echo "Docker playbook detected - targeting 'docker_hosts' group"
                    }

                    sh """
                        ansible-playbook \
                            -i inventories/inventory.proxmox.yml \
                            playbooks/${params.PLAYBOOK} \
                            ${limitFlag} \
                            ${checkFlag}
                    """
                }
            }
        }
    }

    post {
        success {
            echo "Playbook ${params.PLAYBOOK} completed successfully"
        }
        failure {
            echo "Playbook ${params.PLAYBOOK} failed"
        }
    }
}
