pipeline {
    agent any
    environment {
        APP    = '/opt/guardia/app'
        VENV   = '/opt/guardia/venv'
        NOTIFY = "${ITSM_BASE_URL}/api/messenger/webhook"
    }
    options {
        buildDiscarder(logRotator(numToKeepStr: '5'))
        timeout(time: 15, unit: 'MINUTES')
        timestamps()
    }
    stages {
        stage('Checkout') { steps { checkout scm } }
        stage('Install') {
            steps { sh "${VENV}/bin/pip install -r requirements.txt -q" }
        }
        stage('Test') {
            when { expression { fileExists('tests/') } }
            steps {
                sh "${VENV}/bin/pytest tests/ -q --tb=short --junitxml=test-results.xml || true"
                junit allowEmptyResults: true, testResults: 'test-results.xml'
            }
        }
        stage('Deploy') {
            when { expression { env.GIT_BRANCH ==~ /.*main/ || env.BRANCH_NAME == 'main' } }
            steps {
                sh """
                    rsync -a --exclude=__pycache__ --exclude=.git \
                          --exclude=rpa_rules.json --exclude='*.pyc' \
                          . ${APP}/
                    systemctl restart guardia
                    sleep 4
                    systemctl is-active guardia || exit 1
                """
            }
        }
    }
    post {
        success { sh "curl -sf -X POST ${NOTIFY} -H 'Content-Type:application/json' -d '{\"event\":\"build_result\",\"room\":\"ops\",\"success\":true,\"result_summary\":\"✅ guardia-itsm 배포 완료 #${BUILD_NUMBER}\"}' 2>/dev/null || true" }
        failure { sh "curl -sf -X POST ${NOTIFY} -H 'Content-Type:application/json' -d '{\"event\":\"build_result\",\"room\":\"ops\",\"success\":false,\"result_summary\":\"❌ guardia-itsm 빌드 실패 #${BUILD_NUMBER}\"}' 2>/dev/null || true" }
    }
}