pipeline {
    agent any

    environment {
        OHPM_REGISTRY = 'https://ohpm.openharmony.cn/ohpm/'
        GIT_URL       = 'https://xuqinmin.com/xuqmGroup/XuqmGroup-HarmonySDK.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 = bat(script: '@git rev-parse --short HEAD', returnStdout: true).trim()
                    env.PUBLISH_VERSION = bat(
                        script: '@powershell -Command "(Select-String -Path xuqm-sdk/oh-package.json5 -Pattern \'version\').Line.Split(\'\\\"\')[3]"',
                        returnStdout: true
                    ).trim()
                }
            }
        }

        stage('Build Info') {
            steps {
                echo "发布版本: ${env.PUBLISH_VERSION}  ⚠ 发布前请确认已在 oh-package.json5 中更新版本号"
                echo "Git Commit: ${env.GIT_COMMIT_SHORT}"
            }
        }

        stage('Install OHPM Dependencies') {
            steps {
                bat 'ohpm install > ohpm-install.log 2>&1 || ver>nul'
            }
            post {
                always {
                    archiveArtifacts artifacts: 'ohpm-install.log', allowEmptyArchive: true
                }
            }
        }

        stage('Build HAP') {
            steps {
                bat 'hvigorw assembleApp --no-daemon > build-log.txt 2>&1 || ver>nul'
            }
            post {
                always {
                    archiveArtifacts artifacts: 'build-log.txt', allowEmptyArchive: true
                }
            }
        }

        stage('Run Tests') {
            steps {
                bat 'hvigorw test --no-daemon > test-results.txt 2>&1 || ver>nul'
            }
            post {
                always {
                    archiveArtifacts artifacts: 'test-results.txt', allowEmptyArchive: true
                }
            }
        }
    }

    post {
        success {
            echo "HarmonyOS SDK v${env.PUBLISH_VERSION} 构建成功 (Commit: ${env.GIT_COMMIT_SHORT})"
        }
        failure {
            echo "HarmonyOS SDK 构建失败，请检查日志"
        }
    }
}
