pipeline {
    agent any
    
    parameters {
        choice(name: 'BROWSER', choices: ['chrome', 'firefox'], description: 'Browser to run tests')
        choice(name: 'TEST_ENV', choices: ['dev', 'qa', 'prod'], description: 'Test environment')
    }
    
    environment {
        PYTHON_VERSION = '3.8+'
        HEADLESS = 'true'
    }
    
    stages {
        stage('Setup') {
            steps {
                script {
                    echo "Setting up Python ${PYTHON_VERSION}"
                    sh '''
                        python${PYTHON_VERSION} -m venv venv
                        . venv/bin/activate
                        python -m pip install --upgrade pip
                        pip install -r requirements.txt
                    '''
                }
            }
        }
        
        stage('Run Tests') {
            steps {
                script {
                    sh '''
                        . venv/bin/activate
                        pytest -v -n auto
                    '''
                }
            }
        }
        
        stage('Install Allure CLI') {
            steps {
                script {
                    sh '''
                        mkdir -p ${WORKSPACE}/allure
                        wget https://github.com/allure-framework/allure2/releases/download/2.25.0/allure-2.25.0.tgz
                        tar -zxvf allure-2.25.0.tgz -C ${WORKSPACE}/allure --strip-components=1
                        chmod +x ${WORKSPACE}/allure/bin/allure
                    '''
                }
            }
        }
        
        stage('Generate Allure Report') {
            steps {
                script {
                    sh '''
                        ${WORKSPACE}/allure/bin/allure generate allure-results --clean -o allure-report
                    '''
                }
            }
        }
    }
    
    post {
        always {
            archiveArtifacts artifacts: 'allure-results/**', allowEmptyArchive: true
            archiveArtifacts artifacts: 'allure-report/**', allowEmptyArchive: true
            allure([
                includeProperties: false,
                jdk: '',
                properties: [],
                reportBuildPolicy: 'ALWAYS',
                results: [[path: 'allure-results']]
            ])
            archiveArtifacts artifacts: 'screenshots/**', allowEmptyArchive: true
            archiveArtifacts artifacts: 'logs/**', allowEmptyArchive: true
        }
        
        success {
            echo 'Tests passed successfully!'
        }
        
        failure {
            echo 'Tests failed. Check the artifacts for details.'
        }
    }
}
