pipeline {
    agent any

    options {
        buildDiscarder(logRotator(numToKeepStr: '5'))
    }

    environment {
        DEV_DIR = "/home/testyourapp-marcobe-backend/htdocs/marcobe-backend.testyourapp.online/marco-python-backend"
        PROD_DIR= "/var/www/html/marco-python-backend"
        PYTHON  = "/usr/bin/python3.12"
    }

    stages {

        stage('Clone Repo') {
            steps {
                git branch: "${env.BRANCH_NAME}",
                    credentialsId: 'gitlab-server',
                    url: 'https://gitlab.latitudetechnolabs.com/marco/marco-python-backend.git'
            }
        }

        stage('Build') {
            when {
                expression { env.BRANCH_NAME == 'dev' }
            }
            steps {
                sshagent(credentials: ['marcobe-site-ssh']) {

                    sh """
                    rsync -avz --delete \
                      --exclude='.env' \
                      --exclude='venv/' \
                      --exclude='__pycache__/' \
                      --exclude='.git/' \
                      -e "ssh -p 22 -oStrictHostKeyChecking=no" \
                      ./ testyourapp-marcobe-backend@138.201.136.139:${DEV_DIR}/
                    """

                    sh """
                    ssh -p 22 -oStrictHostKeyChecking=no testyourapp-marcobe-backend@138.201.136.139 '
                        cd ${DEV_DIR}
                        ${PYTHON} -m venv venv || true
                        source venv/bin/activate
                        pip install --upgrade pip
                        pip install -r requirements.txt
                        pip install gunicorn
                    '
                    """
                }
            }
        }

        stage('Deploy') {
            when {
                expression { env.BRANCH_NAME == 'dev' }
            }
            steps {
                sshagent(credentials: ['marcobe-site-ssh']) {
                    sh """
                    ssh -p 22 -oStrictHostKeyChecking=no testyourapp-marcobe-backend@138.201.136.139 '
                        sudo systemctl restart marcobe-backend.service
                    '
                    """
                }
            }
        }

        stage('PROD • Build & Setup Venv') {
            when {
                expression { env.BRANCH_NAME == 'prod' }
            }
            agent { label 'marco' }

            steps {
                script {
                    sh 'pwd'

                    // Rsync files (clean + fast)
                    sh """
                        rsync -au --exclude='venv/' --exclude='.env' ./ ${PROD_DIR}/
                    """

                    sh """
                        if [ ! -d "${PROD_DIR}/venv" ]; then
                            python3 -m venv ${PROD_DIR}/venv
                        fi

                        ${PROD_DIR}/venv/bin/pip install -r ${PROD_DIR}/requirements.txt
                        sudo chown -R marco:marco ${PROD_DIR}/
                    """

                    // Restart service
                    sh "sudo systemctl restart marcobe-backend"
                }
            }
        }

    }

    post {
        success {
            echo "✅ DEV deployment succeeded - BUILD: ${env.BUILD_NUMBER}"
        }
        failure {
            echo "❌ DEV deployment failed - BUILD: ${env.BUILD_NUMBER}"
        }
        always {
            cleanWs deleteDirs: true, notFailBuild: true
        }
    }
}