name: Build Obfuscated SDK

on:
  workflow_dispatch:
    inputs:
      task_id:
        description: '混淆任务ID'
        required: true
      callback_url:
        description: '回调URL'
        required: true
      sdk_region:
        description: 'SDK区域 (1=国内 2=海外)'
        required: true
        default: '2'

jobs:
  build:
    runs-on: macos-15
    timeout-minutes: 30

    steps:
      - name: Checkout obfuscated project
        uses: actions/checkout@v4

      - name: Select Xcode
        run: |
          echo "Available Xcode apps:"
          ls -1 /Applications | grep '^Xcode' || true

          for app in \
            /Applications/Xcode_16.4.app \
            /Applications/Xcode_16.3.app \
            /Applications/Xcode_16.2.app \
            /Applications/Xcode_16.1.app \
            /Applications/Xcode_16.0.app \
            /Applications/Xcode_16.app \
            /Applications/Xcode.app \
            /Applications/Xcode_15.4.app \
            /Applications/Xcode_15.2.app
          do
            if [ -d "$app" ]; then
              export DEVELOPER_DIR="$app/Contents/Developer"
              echo "DEVELOPER_DIR=$DEVELOPER_DIR" >> "$GITHUB_ENV"
              echo "Selected Xcode: $app"
              break
            fi
          done

          if [ -z "$DEVELOPER_DIR" ]; then
            echo "No usable Xcode found"
            exit 1
          fi

          xcodebuild -version
          xcodebuild -showsdks

      - name: Inspect workspace and schemes
        run: |
          pwd
          ls -la
          find . -path "*/xcshareddata/xcschemes/*.xcscheme" -print | sort || true
          xcodebuild -list -workspace XXGPlayKit.xcworkspace || true

      - name: Install CocoaPods (if needed)
        run: |
          if [ -f "XXGPlayKitOSDemo/Podfile" ]; then
            gem install cocoapods
          fi

      - name: Run build script
        run: |
          chmod +x scripts/build.sh 2>/dev/null || true
          bash scripts/build.sh

      - name: Upload build log on failure
        if: failure()
        uses: actions/upload-artifact@v4
        with:
          name: build-log-${{ github.event.inputs.task_id }}
          path: build/build.log
          if-no-files-found: ignore
          retention-days: 7

      - name: Show build log tail on failure
        if: failure()
        run: |
          echo "==== build/build.log tail ===="
          cat build/build.log || true

      - name: Find SDK output
        id: find_sdk
        run: |
          SDK_PATH=$(find .. -maxdepth 1 -type d -name "闲闲SDK-iOS-*" | head -1)
          if [ -z "$SDK_PATH" ]; then
            echo "SDK output not found"
            exit 1
          fi
          echo "sdk_path=$SDK_PATH" >> $GITHUB_OUTPUT
          SDK_NAME=$(basename "$SDK_PATH")
          echo "sdk_name=$SDK_NAME" >> $GITHUB_OUTPUT

      - name: Strip Pods from SDK output
        run: |
          SDK_PATH='${{ steps.find_sdk.outputs.sdk_path }}'
          if [ -d "$SDK_PATH/Pods" ]; then
            BEFORE=$(du -sh "$SDK_PATH" | awk '{print $1}')
            rm -rf "$SDK_PATH/Pods"
            AFTER=$(du -sh "$SDK_PATH" | awk '{print $1}')
            echo "Stripped Pods: $BEFORE -> $AFTER"
          else
            echo "No Pods directory in SDK output, skip"
          fi

      - name: Package SDK
        run: |
          # 最高压缩级别
          # 注意：必须 cd 到 SDK 父目录再 zip，否则条目会带 "../" 前缀，
          # macOS Finder 出于路径穿越保护会拒绝解压（提示"归档为空"）。
          SDK_PATH='${{ steps.find_sdk.outputs.sdk_path }}'
          SDK_PARENT=$(cd "$(dirname "$SDK_PATH")" && pwd)
          SDK_NAME=$(basename "$SDK_PATH")
          OUT_ZIP="$PWD/sdk-output.zip"
          (cd "$SDK_PARENT" && zip -9 -r "$OUT_ZIP" "$SDK_NAME")
          ls -lh sdk-output.zip
          unzip -l sdk-output.zip | head -5

      - name: Upload artifact for server pull
        uses: actions/upload-artifact@v4
        with:
          name: sdk-${{ github.event.inputs.task_id }}
          path: sdk-output.zip
          retention-days: 1
          if-no-files-found: error
          compression-level: 0

      - name: Callback success
        if: success()
        run: |
          # 把 run_id 一并回传，服务端拉 artifact
          curl -s -X POST "${{ github.event.inputs.callback_url }}" \
            -H "Content-Type: application/json" \
            -d "{\"task_id\":\"${{ github.event.inputs.task_id }}\",\"status\":\"build_success\",\"run_id\":\"${{ github.run_id }}\",\"artifact_name\":\"sdk-${{ github.event.inputs.task_id }}\"}"

      - name: Callback failure
        if: failure()
        run: |
          curl -s -X POST "${{ github.event.inputs.callback_url }}" \
            -H "Content-Type: application/json" \
            -d "{\"task_id\":\"${{ github.event.inputs.task_id }}\",\"status\":\"failed\",\"error\":\"GitHub Actions build failed\"}"