pipeline {
    agent any

    environment {
        PROD_HOST   = '106.54.23.149'
        PROD_USER   = 'ubuntu'
        DEPLOY_DIR  = '/var/www/docs.xuqinmin.com/site'
    }

    stages {
        stage('Checkout') {
            steps {
                checkout scm
            }
        }

        stage('Build Docs') {
            steps {
                bat 'pip3 install mkdocs-material --quiet 2>nul || echo ok'
                bat 'mkdocs build --clean --site-dir site'
            }
        }

        stage('Deploy') {
            steps {
                withCredentials([sshUserPrivateKey(credentialsId: 'PROD_SSH_KEY', keyFileVariable: 'SSH_KEY')]) {
                    bat '''
                        ssh -i %SSH_KEY% -o StrictHostKeyChecking=no -o ConnectTimeout=30 %PROD_USER%@%PROD_HOST% "sudo rm -rf %DEPLOY_DIR%/*"
                        scp -i %SSH_KEY% -o StrictHostKeyChecking=no -o ConnectTimeout=30 -r site/* %PROD_USER%@%PROD_HOST%:%DEPLOY_DIR%/
                    '''
                }
            }
        }
    }

    post {
        success {
            echo 'Docs deployed: https://docs.xuqinmin.com/'
        }
        failure {
            echo 'Docs deployment failed!'
        }
    }
}
