name: Android APK 构建

# 触发条件：
# 1. 推送到 main 分支：自动构建并更新 preview 滚动版本
# 2. 推送 v* 格式 tag：构建正式版本
# 3. 手动触发：指定 tag 发布
on:
  push:
    branches: [ main ]
    tags: [ 'v*' ]
  workflow_dispatch:
    inputs:
      release_tag:
        description: '发布标签 (如 v1.0)'
        required: true
        default: 'v1.0'

permissions:
  contents: write

jobs:
  build-and-release:
    name: Build & Release EmbyX APKs
    runs-on: ubuntu-latest
    steps:
      # 手动 clone，避免从 github.com 下载 actions/checkout 超时
      - name: Checkout
        run: |
          git init
          git remote add origin \
            http://oauth2:${{ secrets.GITHUB_TOKEN }}@192.168.1.66:3000/adminym/embyx.git
          git fetch --depth=1 origin ${{ github.sha }}
          git checkout FETCH_HEAD

      - name: Setup JDK 21 & Python3
        run: |
          apt-get update -qq
          apt-get install -y wget gnupg python3
          wget -qO- https://packages.adoptium.net/artifactory/api/gpg/key/public \
            | gpg --dearmor > /usr/share/keyrings/adoptium.gpg
          echo "deb [signed-by=/usr/share/keyrings/adoptium.gpg] \
            https://packages.adoptium.net/artifactory/deb bullseye main" \
            > /etc/apt/sources.list.d/adoptium.list
          apt-get update -qq
          apt-get install -y temurin-21-jdk
          java -version

      - name: Setup Node.js 22
        run: |
          npm install -g n
          N_NODE_MIRROR=https://npmmirror.com/mirrors/node n 22
          hash -r
          node --version

      # ── 构建中文版 APK ──────────────────────────────────────────────────────
      - name: Build zh APK
        run: |
          cat > capacitor.config.json << 'EOF'
          {
            "appId": "juneix.embyx",
            "appName": "EmbyX",
            "webDir": "zh",
            "backgroundColor": "#000000",
            "server": {
              "androidScheme": "http",
              "cleartext": true
            },
            "plugins": {
              "SplashScreen": {
                "launchAutoHide": true,
                "backgroundColor": "#000000",
                "androidScaleType": "CENTER",
                "showSpinner": false
              }
            }
          }
          EOF
          npm install
          npx cap add android
          npx cap sync android
          python3 .github/patch_android.py --lang zh
          cd android
          chmod +x gradlew
          ./gradlew assembleDebug
          mv app/build/outputs/apk/debug/app-debug.apk ../EmbyX-zh.apk
          cd ..

      # ── 构建英文版 APK（复用已下载的 Gradle 缓存）──────────────────────────
      - name: Build en APK
        run: |
          rm -rf android
          cat > capacitor.config.json << 'EOF'
          {
            "appId": "juneix.embyx",
            "appName": "EmbyX",
            "webDir": "en",
            "backgroundColor": "#000000",
            "server": {
              "androidScheme": "http",
              "cleartext": true
            },
            "plugins": {
              "SplashScreen": {
                "launchAutoHide": true,
                "backgroundColor": "#000000",
                "androidScaleType": "CENTER",
                "showSpinner": false
              }
            }
          }
          EOF
          npm install
          npx cap add android
          npx cap sync android
          python3 .github/patch_android.py --lang en
          cd android
          chmod +x gradlew
          ./gradlew assembleDebug
          mv app/build/outputs/apk/debug/app-debug.apk ../EmbyX-en.apk
          cd ..

      # ── 发布到 Gitea Release（全程用本地 API，不访问 GitHub）───────────────
      - name: Create Release
        run: |
          if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
            TAG="${{ inputs.release_tag }}"
            RNAME="${{ inputs.release_tag }}"
            PRE=false
          elif [ "${{ github.ref_name }}" = "main" ]; then
            TAG="preview"
            RNAME="EmbyX Preview"
            PRE=true
          else
            TAG="${{ github.ref_name }}"
            RNAME="${{ github.ref_name }}"
            PRE=false
          fi

          API="http://192.168.1.66:3000/api/v1/repos/adminym/embyx"
          AUTH="Authorization: token ${{ secrets.GITHUB_TOKEN }}"

          # 删除旧的同名 release（用于 preview 滚动更新）
          OLD_ID=$(curl -sf "$API/releases/tags/$TAG" -H "$AUTH" \
            | python3 -c "import sys,json; print(json.load(sys.stdin).get('id',''))" \
            2>/dev/null || echo "")
          if [ -n "$OLD_ID" ] && [ "$OLD_ID" != "None" ]; then
            curl -sf -X DELETE "$API/releases/$OLD_ID" -H "$AUTH" || true
            curl -sf -X DELETE "$API/tags/$TAG" -H "$AUTH" || true
          fi

          # 创建新 release
          RID=$(curl -sf -X POST "$API/releases" \
            -H "$AUTH" -H "Content-Type: application/json" \
            -d "{\"tag_name\":\"$TAG\",\"name\":\"$RNAME\",\"prerelease\":$PRE,\"draft\":false}" \
            | python3 -c "import sys,json; print(json.load(sys.stdin)['id'])")

          echo "Release ID: $RID"

          # 上传中文版 APK
          curl -sf -X POST "$API/releases/$RID/assets?name=EmbyX-zh.apk" \
            -H "$AUTH" -F "attachment=@EmbyX-zh.apk"

          # 上传英文版 APK
          curl -sf -X POST "$API/releases/$RID/assets?name=EmbyX-en.apk" \
            -H "$AUTH" -F "attachment=@EmbyX-en.apk"

          echo "发布完成: http://192.168.1.66:3000/adminym/embyx/releases/tag/$TAG"
