pipeline {
    agent any
    
    environment {
        IMAGE_NAME = 'awesome-index'
        DEPLOY_PATH = '/app/awesome'
        SSH_HOST = '114.134.187.170'
        SSH_USER = 'root'
    }
    
    stages {
        stage('Build') {
            steps {
                script {
                    echo "Building Docker image ${IMAGE_NAME}:latest"
                    sh "docker build -t ${IMAGE_NAME}:latest ."
                }
            }
        }
        
        stage('Deploy') {
            steps {
                withCredentials([usernamePassword(credentialsId: 'baihu-ssh', usernameVariable: 'SSH_USER', passwordVariable: 'SSH_PASS')]) {
                    script {
                        def remote = "root@${SSH_HOST}"
                        
                        // 创建部署目录
                        sh "sshpass -p '${SSH_PASS}' ssh -o StrictHostKeyChecking=no ${remote} 'mkdir -p ${DEPLOY_PATH}/data ${DEPLOY_PATH}/logs'"
                        
                        // 上传脚本（构建机 = 部署机，镜像已在服务器上，无需传输镜像）
                        sh "sshpass -p '${SSH_PASS}' scp -o StrictHostKeyChecking=no .env.example ${remote}:${DEPLOY_PATH}/.env.example"
                        sh "sshpass -p '${SSH_PASS}' scp -o StrictHostKeyChecking=no start.sh ${remote}:${DEPLOY_PATH}/"
                        
                        // 在服务器上重启容器
                        sh "sshpass -p '${SSH_PASS}' ssh -o StrictHostKeyChecking=no ${remote} 'cd ${DEPLOY_PATH} && chmod +x start.sh && bash start.sh'"
                    }
                }
            }
        }
        
        stage('Health Check') {
            steps {
                script {
                    sleep 10
                    def status = sh(
                        script: "curl -sf http://${SSH_HOST}:3000/healthz || echo 'FAILED'",
                        returnStdout: true
                    ).trim()
                    
                    if (status.contains('ok')) {
                        echo "Health check PASSED"
                    } else {
                        error "Health check FAILED"
                    }
                }
            }
        }
    }
    
    post {
        always {
            cleanWs()
        }
    }
}
