pipeline {
    agent any

    parameters {
        string(name: 'VERSION', defaultValue: '', description: '发布版本号（留空自动递增）')
        booleanParam(name: 'RUN_TESTS', defaultValue: true, description: '是否运行单元测试')
        booleanParam(name: 'PUBLISH_SPM', defaultValue: true, description: '发布 SPM 版本（打 Git Tag）')
        booleanParam(name: 'PUBLISH_PODS', defaultValue: false, description: '发布到 CocoaPods 私有 Spec Repo')
    }

    environment {
        GIT_URL       = 'https://xuqinmin.com/xuqinmin12/XuqmGroup-iOSSDK.git'
        SPEC_REPO     = 'https://xuqinmin.com/xuqinmin12/xuqm-specs.git'
    }

    options {
        timeout(time: 30, unit: 'MINUTES')
        buildDiscarder(logRotator(numToKeepStr: '20'))
        disableConcurrentBuilds()
    }

    stages {
        stage('Checkout') {
            steps {
                checkout([
                  $class: 'GitSCM',
                  branches: [[name: 'main']],
                  extensions: [[$class: 'CleanBeforeCheckout']],
                  userRemoteConfigs: scm.userRemoteConfigs
                ])
                script {
                    env.GIT_COMMIT_SHORT = sh(script: 'git rev-parse --short HEAD', returnStdout: true).trim()
                    if (params.VERSION?.trim()) {
                        env.PUBLISH_VERSION = params.VERSION.trim()
                        sh "sed -i '' 's/s.version.*= .*/s.version          = \"${env.PUBLISH_VERSION}\"/' XuqmSDK.podspec"
                    } else {
                        env.PUBLISH_VERSION = sh(script: 'grep "s.version" XuqmSDK.podspec | head -1 | sed "s/.*= *\\"\\(.*\\)\\".*/\\1/"', returnStdout: true).trim()
                    }
                }
            }
        }

        stage('Build Info') {
            steps {
                script {
                    echo "🚀 构建分支: ${params.BRANCH}"
                    echo "🏷️  发布版本: ${env.PUBLISH_VERSION}"
                    echo "🔨 Git Commit: ${env.GIT_COMMIT_SHORT}"
                    echo "⚠️  注意：此任务应在 Jenkins2 (https://xuqinmin12.eicp.vip/) 上执行"
                }
            }
        }

        stage('Swift Build') {
            steps {
                sh 'swift build'
            }
        }

        stage('Unit Tests') {
            when { expression { return params.RUN_TESTS } }
            steps {
                sh 'swift test 2>&1 | tee test-results.txt'
            }
            post {
                always {
                    archiveArtifacts artifacts: 'test-results.txt', allowEmptyArchive: true
                }
            }
        }

        stage('Pod Spec Lint') {
            when { expression { return params.PUBLISH_PODS } }
            steps {
                sh 'pod spec lint XuqmSDK.podspec --allow-warnings'
            }
        }

        stage('Publish SPM (Git Tag)') {
            when {
                expression { return params.PUBLISH_SPM }
            }
            steps {
                withCredentials([usernamePassword(credentialsId: 'gitlab-credentials', passwordVariable: 'GIT_PASS', usernameVariable: 'GIT_USER')]) {
                    sh """
                        git config user.email "jenkins@xuqm.com"
                        git config user.name "Jenkins CI"
                        git add XuqmSDK.podspec || true
                        git diff --cached --quiet || git commit -m "ci: bump version to ${env.PUBLISH_VERSION}"
                        git tag -f "${env.PUBLISH_VERSION}"
                        git push https://${GIT_USER}:${GIT_PASS}@xuqinmin.com/xuqinmin12/XuqmGroup-iOSSDK.git HEAD:main --tags
                    """
                }
            }
        }

        stage('Publish CocoaPods') {
            when {
                expression { return params.PUBLISH_PODS }
            }
            steps {
                sh """
                    pod repo add xuqm-specs ${SPEC_REPO} 2>/dev/null || true
                    pod repo push xuqm-specs XuqmSDK.podspec --allow-warnings
                """
            }
        }
    }

    post {
        success {
            script {
                echo "✅ iOS SDK v${env.PUBLISH_VERSION} 构建成功 (Commit: ${env.GIT_COMMIT_SHORT})"
                if (params.PUBLISH_SPM) {
                    echo "📦 SPM 版本已发布: ${env.PUBLISH_VERSION}"
                }
                if (params.PUBLISH_PODS) {
                    echo "📦 CocoaPods 版本已发布到私有 Spec Repo"
                }
            }
        }
        failure {
            echo "❌ iOS SDK 构建失败，请检查日志"
        }
    }
}
