pipeline {
    agent any

    parameters {
        // ── 版本升级策略 ─────────────────────────────────────────────────────
        choice(name: 'VERSION_BUMP', choices: ['patch', 'minor', 'major'],
               description: '版本升级策略: major(1.0.0→2.0.0), minor(1.0.0→1.1.0), patch(1.0.0→1.0.1)')
        booleanParam(name: 'CUSTOM_VERSION', defaultValue: false,
                     description: '勾选后使用下方自定义版本号（忽略VERSION_BUMP）')

        // ── 模块自定义版本号（仅CUSTOM_VERSION=true时生效）───────────────────
        string(name: 'CORE_VERSION',    defaultValue: '', description: 'XuqmCoreSDK 自定义版本号（仅CUSTOM_VERSION=true时生效）')
        string(name: 'IM_VERSION',      defaultValue: '', description: 'XuqmImSDK 自定义版本号')
        string(name: 'PUSH_VERSION',    defaultValue: '', description: 'XuqmPushSDK 自定义版本号')
        string(name: 'UPDATE_VERSION',  defaultValue: '', description: 'XuqmUpdateSDK 自定义版本号')
        string(name: 'LICENSE_VERSION', defaultValue: '', description: 'XuqmLicenseSDK 自定义版本号')
        string(name: 'FILE_VERSION',    defaultValue: '', description: 'XuqmFileSDK 自定义版本号')
        string(name: 'WEBVIEW_VERSION', defaultValue: '', description: 'XuqmWebViewSDK 自定义版本号')

        // ── 模块选择（勾选即发布）─────────────────────────────────────────
        booleanParam(name: 'MOD_CORE',    defaultValue: true, description: '发布 XuqmCoreSDK')
        booleanParam(name: 'MOD_IM',      defaultValue: true, description: '发布 XuqmImSDK')
        booleanParam(name: 'MOD_PUSH',    defaultValue: true, description: '发布 XuqmPushSDK')
        booleanParam(name: 'MOD_UPDATE',  defaultValue: true, description: '发布 XuqmUpdateSDK')
        booleanParam(name: 'MOD_LICENSE', defaultValue: true, description: '发布 XuqmLicenseSDK')
        booleanParam(name: 'MOD_FILE',    defaultValue: true, description: '发布 XuqmFileSDK')
        booleanParam(name: 'MOD_WEBVIEW', defaultValue: true, description: '发布 XuqmWebViewSDK')

        // ── 构建选项 ────────────────────────────────────────────────────────
        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()

                    // ── 根据复选框收集选中的模块 ──────────────────────────
                    def moduleChecks = [
                        'core':    params.MOD_CORE,
                        'im':      params.MOD_IM,
                        'push':    params.MOD_PUSH,
                        'update':  params.MOD_UPDATE,
                        'license': params.MOD_LICENSE,
                        'file':    params.MOD_FILE,
                        'webview': params.MOD_WEBVIEW,
                    ]
                    def requested = moduleChecks.findAll { k, v -> v }.collect { k, v -> k }
                    if (requested.isEmpty()) {
                        error "没有选择任何模块，请至少勾选一个"
                    }
                    env.SELECTED_MODULES = requested.join(',')
                    echo "Selected modules: ${env.SELECTED_MODULES}"

                    // ── 模块 → podspec/tag 映射 ────────────────────────────
                    def moduleMap = [
                        'core':    [podspec: 'XuqmCoreSDK',    tagPrefix: 'core'],
                        'im':      [podspec: 'XuqmImSDK',      tagPrefix: 'im'],
                        'push':    [podspec: 'XuqmPushSDK',    tagPrefix: 'push'],
                        'update':  [podspec: 'XuqmUpdateSDK',  tagPrefix: 'update'],
                        'license': [podspec: 'XuqmLicenseSDK', tagPrefix: 'license'],
                        'file':    [podspec: 'XuqmFileSDK',    tagPrefix: 'file'],
                        'webview': [podspec: 'XuqmWebViewSDK', tagPrefix: 'webview'],
                    ]
                    env.MODULE_MAP = groovy.json.JsonOutput.toJson(moduleMap)
                }
            }
        }

        stage('Resolve Versions') {
            steps {
                script {
                    def moduleMap = new groovy.json.JsonSlurper().parseText(env.MODULE_MAP)
                    def modules = env.SELECTED_MODULES.split(',')
                    def customVersions = [
                        'core':    params.CORE_VERSION?.trim(),
                        'im':      params.IM_VERSION?.trim(),
                        'push':    params.PUSH_VERSION?.trim(),
                        'update':  params.UPDATE_VERSION?.trim(),
                        'license': params.LICENSE_VERSION?.trim(),
                        'file':    params.FILE_VERSION?.trim(),
                        'webview': params.WEBVIEW_VERSION?.trim(),
                    ]

                    for (mod in modules) {
                        def podspecFile = "${moduleMap[mod].podspec}.podspec"
                        def currentVer = sh(
                            script: "grep \"s.version\" ${podspecFile} | head -1 | sed \"s/.*= *\\\"\\(.*\\)\\\".*/\\1/\"",
                            returnStdout: true
                        ).trim()

                        def newVer = ''
                        if (params.CUSTOM_VERSION && customVersions[mod]) {
                            // 使用自定义版本号
                            newVer = customVersions[mod]
                        } else if (!params.CUSTOM_VERSION) {
                            // 根据 VERSION_BUMP 策略自动升级版本号
                            def parts = currentVer.tokenize('.')
                            while (parts.size() < 3) { parts.add('0') }
                            switch (params.VERSION_BUMP) {
                                case 'major':
                                    parts[0] = (parts[0].toInteger() + 1).toString()
                                    parts[1] = '0'
                                    parts[2] = '0'
                                    break
                                case 'minor':
                                    parts[1] = (parts[1].toInteger() + 1).toString()
                                    parts[2] = '0'
                                    break
                                case 'patch':
                                default:
                                    parts[2] = (parts[2].toInteger() + 1).toString()
                                    break
                            }
                            newVer = parts.join('.')
                        }

                        if (newVer && newVer != currentVer) {
                            echo "Bumping ${moduleMap[mod].podspec}: ${currentVer} → ${newVer}"
                            sh "sed -i '' 's/s.version.*= .*/s.version          = \"${newVer}\"/' ${podspecFile}"
                            env["VERSION_${mod}"] = newVer
                        } else {
                            echo "Keeping ${moduleMap[mod].podspec} at ${currentVer}"
                            env["VERSION_${mod}"] = currentVer
                        }
                    }
                }
            }
        }

        stage('Build Info') {
            steps {
                script {
                    def modules = env.SELECTED_MODULES.split(',')
                    def moduleMap = new groovy.json.JsonSlurper().parseText(env.MODULE_MAP)
                    echo "Git Commit : ${env.GIT_COMMIT_SHORT}"
                    echo "Bump Strategy: ${params.CUSTOM_VERSION ? 'Custom' : params.VERSION_BUMP}"
                    echo "Modules (${modules.size()}):"
                    for (mod in modules) {
                        def ver = env["VERSION_${mod}"]
                        echo "  ${mod.padRight(10)} → ${moduleMap[mod].podspec} v${ver}"
                    }
                }
            }
        }

        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 {
                script {
                    def moduleMap = new groovy.json.JsonSlurper().parseText(env.MODULE_MAP)
                    def modules = env.SELECTED_MODULES.split(',')
                    // 按依赖顺序 lint：先 core，再其他模块
                    def ordered = ['core'] + modules.findAll { it != 'core' }
                    for (mod in ordered) {
                        def podspec = "${moduleMap[mod].podspec}.podspec"
                        if (fileExists(podspec)) {
                            echo "Linting ${podspec}..."
                            sh "pod spec lint ${podspec} --allow-warnings"
                        }
                    }
                }
            }
        }

        stage('Publish SPM (Git Tags)') {
            when { expression { return params.PUBLISH_SPM } }
            steps {
                withCredentials([usernamePassword(credentialsId: 'gitlab-credentials', passwordVariable: 'GIT_PASS', usernameVariable: 'GIT_USER')]) {
                    script {
                        def moduleMap = new groovy.json.JsonSlurper().parseText(env.MODULE_MAP)
                        def modules = env.SELECTED_MODULES.split(',')
                        def tagsToPush = []

                        for (mod in modules) {
                            def ver = env["VERSION_${mod}"]
                            if (ver) {
                                def tag = "${moduleMap[mod].tagPrefix}/${ver}"
                                tagsToPush.push(tag)
                            }
                        }

                        if (tagsToPush) {
                            sh """
                                git config user.email "jenkins@xuqm.com"
                                git config user.name "Jenkins CI"
                                git add *.podspec || true
                                git diff --cached --quiet || git commit -m "ci: bump versions [${env.SELECTED_MODULES}]"
                            """
                            for (tag in tagsToPush) {
                                sh "git tag -f '${tag}'"
                            }
                            sh """
                                git push https://${GIT_USER}:${GIT_PASS}@xuqinmin.com/xuqinmin12/XuqmGroup-iOSSDK.git HEAD:main --tags -f
                            """
                            echo "Published tags: ${tagsToPush.join(', ')}"
                        }
                    }
                }
            }
        }

        stage('Publish CocoaPods') {
            when { expression { return params.PUBLISH_PODS } }
            steps {
                script {
                    def moduleMap = new groovy.json.JsonSlurper().parseText(env.MODULE_MAP)
                    def modules = env.SELECTED_MODULES.split(',')
                    sh "pod repo add xuqm-specs ${SPEC_REPO} 2>/dev/null || true"
                    // 按依赖顺序发布：先 core，再其他模块
                    def ordered = ['core'] + modules.findAll { it != 'core' }
                    for (mod in ordered) {
                        def podspec = "${moduleMap[mod].podspec}.podspec"
                        if (fileExists(podspec)) {
                            echo "Publishing ${podspec}..."
                            sh "pod repo push xuqm-specs ${podspec} --allow-warnings"
                        }
                    }
                }
            }
        }
    }

    post {
        success {
            script {
                def modules = env.SELECTED_MODULES?.split(',') ?: []
                def moduleMap = new groovy.json.JsonSlurper().parseText(env.MODULE_MAP)
                def summary = modules.collect { "${it}=${env["VERSION_${it}"]}" }.join(', ')
                echo "iOS SDK published — ${summary} (Commit: ${env.GIT_COMMIT_SHORT})"
            }
        }
        failure {
            echo "iOS SDK build failed — please check the logs"
        }
    }
}
