pipeline {
    agent any
    environment {
        PATH = "/var/jenkins_home/bin:${env.PATH}"
    }
    stages {
        stage('Clone') {
            steps {
                echo '✅ Code cloné depuis Gitea'
            }
        }
        stage('SonarQube Analysis') {
            steps {
                withSonarQubeEnv('sonarqube') {
                    withEnv(["PATH+SONAR=${tool 'sonar-scanner'}/bin"]) {
                        sh '''
                            sonar-scanner \
                              -Dsonar.projectKey=datalab-lite \
                              -Dsonar.projectName="Datalab Lite" \
                              -Dsonar.sources=. \
                              -Dsonar.inclusions="**/*.py" \
                              -Dsonar.python.version=3.11
                        '''
                    }
                }
            }
        }
        stage('Quality Gate') {
            steps {
                waitForQualityGate abortPipeline: false
            }
        }
        stage('Deploy') {
            steps {
                sh '''
                    kubectl create configmap datalab-lite-code \
                        --from-file=main.py=main.py \
                        --from-file=k8s.py=k8s.py \
                        --from-file=minio_client.py=minio_client.py \
                        -n datalab-lite \
                        --dry-run=client -o yaml | kubectl apply -f -

                    kubectl create configmap datalab-lite-templates \
                        --from-file=index.html=templates/index.html \
                        -n datalab-lite \
                        --dry-run=client -o yaml | kubectl apply -f -

                    kubectl rollout restart deployment datalab-lite -n datalab-lite
                    echo "✅ Datalab Lite déployé"
                '''
            }
        }
    }
    post {
        success { echo '✅ Pipeline terminé avec succès !' }
        failure { echo '❌ Pipeline échoué !' }
    }
}
