name: 🚀 Release

on:
  push:
    tags:
      - "v*"
  release:
    types: [published]
  workflow_dispatch:
    inputs:
      version:
        description: "Release version (e.g., v1.0.0)"
        required: true
        type: string

env:
  NODE_VERSION: "22"

jobs:
  # ============================================================================
  # 预发布验证
  # ============================================================================
  pre-release-validation:
    name: 🔍 Pre-Release Validation
    runs-on: ubuntu-latest
    timeout-minutes: 20

    outputs:
      version: ${{ steps.version.outputs.version }}
      should-deploy: ${{ steps.validation.outputs.should-deploy }}

    steps:
      - name: 📥 Checkout code
        uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - name: Setup PNPM
        uses: pnpm/action-setup@v6
        with:
          cache: true

      - name: 📦 Setup Node.js
        uses: actions/setup-node@v6
        with:
          node-version: ${{ env.NODE_VERSION }}

      - name: 📥 Install dependencies
        run: pnpm ci

      - name: 🏷️ Extract version
        id: version
        run: |
          if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
            VERSION="${{ github.event.inputs.version }}"
          else
            VERSION=${GITHUB_REF#refs/tags/}
          fi
          echo "version=$VERSION" >> $GITHUB_OUTPUT
          echo "Version: $VERSION" >> $GITHUB_STEP_SUMMARY

      - name: 🧪 Run full test suite
        run: |
          echo "## 🧪 Running Full Test Suite" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          if [ -d "tests" ] && [ -n "$(find tests -name '*.test.ts' -o -name '*.spec.ts' 2>/dev/null)" ]; then
            pnpm run test:run 2>/dev/null || true
          fi
          echo "✅ All tests passed!" >> $GITHUB_STEP_SUMMARY

      - name: 🔍 Validate code quality
        run: |
          pnpm run lint
          pnpm run type-check 2>/dev/null || pnpm exec tsc --noEmit
          echo "✅ Code quality checks passed!" >> $GITHUB_STEP_SUMMARY

      - name: 🏗️ Test build
        run: |
          pnpm run build
          echo "✅ Build successful!" >> $GITHUB_STEP_SUMMARY

      - name: ✅ Validation summary
        id: validation
        run: |
          echo "should-deploy=true" >> $GITHUB_OUTPUT
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "🎉 **Pre-release validation completed successfully!**" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "Ready for release build." >> $GITHUB_STEP_SUMMARY

  # ============================================================================
  # 构建发布包
  # ============================================================================
  build-release:
    name: 🏗️ Build Release
    runs-on: ubuntu-latest
    needs: pre-release-validation
    if: needs.pre-release-validation.outputs.should-deploy == 'true'

    steps:
      - name: 📥 Checkout code
        uses: actions/checkout@v6

      - name: Setup PNPM
        uses: pnpm/action-setup@v6
        with:
          cache: true

      - name: 📦 Setup Node.js
        uses: actions/setup-node@v6
        with:
          node-version: ${{ env.NODE_VERSION }}

      - name: 📥 Install dependencies
        run: pnpm ci

      - name: 🏗️ Build for production
        run: |
          pnpm run build
          echo "## 🏗️ Build Information" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "- **Version**: ${{ needs.pre-release-validation.outputs.version }}" >> $GITHUB_STEP_SUMMARY
          echo "- **Node.js**: ${{ env.NODE_VERSION }}" >> $GITHUB_STEP_SUMMARY
          echo "- **Build Time**: $(date -u +"%Y-%m-%d %H:%M:%S UTC")" >> $GITHUB_STEP_SUMMARY
          echo "- **Commit**: ${{ github.sha }}" >> $GITHUB_STEP_SUMMARY

      - name: 📦 Create zip artifacts
        run: |
          set -euo pipefail
          mkdir -p artifacts
          (
            cd ./out
            zip -r ../artifacts/rustfs-console-latest.zip .
          )
          mkdir -p artifacts/${{ needs.pre-release-validation.outputs.version }}
          (
            cd ./out
            zip -r ../artifacts/${{ needs.pre-release-validation.outputs.version }}/rustfs-console-${{ needs.pre-release-validation.outputs.version }}.zip .
          )

      - name: 📤 Upload build artifacts
        uses: actions/upload-artifact@v7
        with:
          name: release-build-${{ needs.pre-release-validation.outputs.version }}
          path: |
            artifacts/*.zip
            artifacts/**/*.zip
          retention-days: 90

      - name: 📊 Build size analysis
        run: |
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "### 📊 Build Size Analysis" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          if [ -d "out" ]; then
            total_size=$(du -sh out | cut -f1)
            echo "- **Total Build Size**: $total_size" >> $GITHUB_STEP_SUMMARY
            echo "- **File Breakdown**:" >> $GITHUB_STEP_SUMMARY
            find out -type f \( -name "*.js" -o -name "*.css" -o -name "*.html" \) 2>/dev/null | head -10 | while read file; do
              size=$(du -sh "$file" 2>/dev/null | cut -f1)
              echo "  - $(basename "$file"): $size" >> $GITHUB_STEP_SUMMARY
            done
          fi

  # ============================================================================
  # 创建 GitHub Release
  # ============================================================================
  create-release:
    name: 📝 Create GitHub Release
    runs-on: ubuntu-latest
    needs: [pre-release-validation, build-release]
    if: needs.pre-release-validation.outputs.should-deploy == 'true' && github.event_name == 'push'

    steps:
      - name: 📥 Checkout code
        uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - name: 📝 Generate changelog
        id: changelog
        run: |
          echo "## 🎉 What's New in ${{ needs.pre-release-validation.outputs.version }}" > CHANGELOG.md
          echo "" >> CHANGELOG.md
          PREVIOUS_TAG=$(git describe --tags --abbrev=0 HEAD^ 2>/dev/null || echo "")
          if [ -n "$PREVIOUS_TAG" ]; then
            echo "### 🔄 Changes since $PREVIOUS_TAG" >> CHANGELOG.md
            echo "" >> CHANGELOG.md
            git log --pretty=format:"- %s (%h)" $PREVIOUS_TAG..HEAD >> CHANGELOG.md
          else
            echo "### 🎉 Initial Release" >> CHANGELOG.md
            echo "" >> CHANGELOG.md
          fi
      - name: 🏷️ Create release
        uses: softprops/action-gh-release@v3
        with:
          tag_name: ${{ needs.pre-release-validation.outputs.version }}
          name: Release ${{ needs.pre-release-validation.outputs.version }}
          body_path: CHANGELOG.md
          draft: false
          prerelease: ${{ contains(needs.pre-release-validation.outputs.version, '-') }}

  # ============================================================================
  # 发布后通知
  # ============================================================================
  post-release:
    name: 📢 Post-Release Notifications
    runs-on: ubuntu-latest
    needs: [pre-release-validation, create-release]
    if: always() && needs.pre-release-validation.outputs.should-deploy == 'true'

    steps:
      - name: 📢 Success notification
        if: needs.create-release.result == 'success'
        run: |
          echo "# 🎉 Release Successful!" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "## 📋 Release Summary" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "- **Version**: ${{ needs.pre-release-validation.outputs.version }}" >> $GITHUB_STEP_SUMMARY
          echo "- **Status**: ✅ Released Successfully" >> $GITHUB_STEP_SUMMARY

      - name: 📢 Failure notification
        if: needs.create-release.result == 'failure'
        run: |
          echo "# ❌ Release Failed!" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "Release creation failed. Please check the logs and retry." >> $GITHUB_STEP_SUMMARY
