pipeline {
    agent any

    parameters {
        choice(name: 'env', choices: ['dev', 'test', 'prod'], description: '部署环境')
        string(name: 'NAMESPACE', defaultValue: 'hfln-dev', description: 'K8s 命名空间')
    }

    environment {
        PROJECT_NAME    = 'new-portal-frontend'
        BUILD_DIR       = 'dist'
        NODE_ENV        = 'production'
        HARBOR_HOST     = '8.130.28.21:81'
        KUBECONFIG_PATH = '/root/.kube/config'
        HARBOR_USER     = 'admin'
        HARBOR_PASS     = 'Hfln@1024'
        HARBOR_RETENTION_ID = '1'
    }

    stages {
        stage('🧬 初始化环境') {
            steps {
                script {
                    env.HARBOR_PROJECT = params.env
                    env.IMAGE_TAG = "${HARBOR_HOST}/${env.HARBOR_PROJECT}/${PROJECT_NAME}:${BUILD_NUMBER}"
                    echo ">>> 环境：${params.env}, Harbor项目：${env.HARBOR_PROJECT}, K8s命名空间：${params.NAMESPACE}"
                }
            }
        }

        stage('📥 拉取代码') {
            steps {
                checkout scm
                echo "✅ 代码拉取成功"
            }
        }

        stage('🔧 构建 Docker 镜像') {
            steps {
                script {
                    sh """
                        docker login -u ${HARBOR_USER} -p ${HARBOR_PASS} ${HARBOR_HOST}
                        docker build --build-arg ENV=${params.env} -t ${IMAGE_TAG} .
                    """
                    echo "✅ 镜像构建成功：${IMAGE_TAG}"
                }
            }
        }

        stage('🚀 推送镜像到 Harbor') {
            steps {
                script {
                    sh """
                        docker push ${IMAGE_TAG}
                        docker rmi ${IMAGE_TAG}
                    """
                    echo "✅ 镜像推送并本地清理完成"
                }
            }
        }

        stage('📦 Kubernetes 部署') {
            steps {
                script {
                    sh """
                        export KUBECONFIG=${KUBECONFIG_PATH}
                        kubectl -n ${params.NAMESPACE} set image deployment/${PROJECT_NAME} ${PROJECT_NAME}=${IMAGE_TAG}
                    """
                    echo "✅ 已更新部署镜像至 K8s"
                }
            }
        }

        stage('🧹 清理本地旧镜像（保留最新3个）') {
            steps {
                script {
                    def baseImage = "${HARBOR_HOST}/${env.HARBOR_PROJECT}/${PROJECT_NAME}"
                    sh """
                        docker images ${baseImage} --format "{{.Repository}}:{{.Tag}}" \\
                        | grep -v latest \\
                        | sort -r -t ':' -k2 \\
                        | tail -n +4 \\
                        | xargs -r docker rmi || true
                    """
                    echo "✅ 本地旧镜像清理完成"
                }
            }
        }

        stage('🧹 清理悬空镜像 <none>') {
            steps {
                script {
                    sh """
                        docker images -f "dangling=true" -q | xargs -r docker rmi || true
                    """
                    echo "✅ 悬空镜像（<none>）清理完成"
                }
            }
        }

        stage('🧹 触发 Harbor 镜像保留策略') {
            steps {
                script {
                    sh """
                        curl -u ${HARBOR_USER}:${HARBOR_PASS} -X POST \\
                        "http://${HARBOR_HOST}/api/v2.0/retentions/${HARBOR_RETENTION_ID}/executions"
                    """
                    echo "✅ Harbor 镜像保留策略已触发"
                }
            }
        }
    }

    post {
        success {
            echo "✅ 构建 & 部署成功 🎉"
        }
        failure {
            echo "❌ 构建或部署失败，请检查日志"
        }
        always {
            cleanWs()
        }
    }
}