node {
    try {

        stage('checkout project') {
            checkout scm
        }

        stage('check env') {
            sh 'python3 --version'
            sh 'python3 -m pip --version'
            sh 'docker --version'
        }

        stage('install dependencies') {
            sh 'python3 -m pip install -r requirements.txt --quiet --break-system-packages'
        }

        stage('run api tests') {
            sh 'python3 -m pytest test_api.py -v --tb=short'
        }
        stage('copy models to volume') {
            sh '''
                mkdir -p /opt/crm-ai/models
                mkdir -p /opt/crm-ai/data
                cp -r models/* /opt/crm-ai/models/
                if [ -d data ] && [ "$(ls -A data)" ]; then
                    cp -r data/* /opt/crm-ai/data/
                fi
                echo "✅ Modèles copiés"
                ls -la /opt/crm-ai/models/
            '''
        }
        stage('build docker image') {
            sh 'docker build -t crm-ai-api:latest .'
        }

        stage('verify image') {
            sh 'docker images | grep crm-ai-api'
        }

        stage('inspect image') {
            sh 'docker inspect crm-ai-api:latest --format "Size: {{.Size}} bytes"'
        }

        stage('stop old container') {
            sh '''
                docker stop crm-ai-api 2>/dev/null || echo "Aucun conteneur a arreter"
                docker rm   crm-ai-api 2>/dev/null || echo "Aucun conteneur a supprimer"
            '''
        }

        // ── .env injecté depuis Jenkins Credentials ─────────────────────
        stage('run container') {
            withCredentials([file(credentialsId: 'crm-ai-env-file', variable: 'ENV_FILE')]) {
                sh '''
                    docker run -d \
                        --name crm-ai-api \
                        --restart always \
                        -p 5000:5000 \
                        --env-file $ENV_FILE \
                        -v /opt/crm-ai/models:/app/models:ro \
                        -v /opt/crm-ai/data:/app/data:ro \
                        --memory="2g" \
                        --cpus="1.5" \
                        crm-ai-api:latest
                '''
            }
        }

        stage('enable auto-restart') {
            sh 'docker update --restart always crm-ai-api'
        }

        stage('verify container') {
            sh 'docker ps | grep crm-ai-api'
            sh 'sleep 30'
            sh 'curl -f http://localhost:5000/api/health'
        }

    } catch (e) {
        sh 'docker logs crm-ai-api --tail=50 2>/dev/null || echo "Pas de logs disponibles"'
        throw e
    }
}