name: Nightly Build

on:
  workflow_dispatch:
  schedule:
    - cron: '0 17 * * *' # 1:00 BJ Time

permissions:
  contents: write
  actions: write # Required for deleting artifacts

jobs:
  cleanup-artifacts:
    runs-on: ubuntu-latest
    steps:
      - name: Delete old artifacts
        env:
          GH_TOKEN: ${{ github.token }}
          REPO: ${{ github.repository }}
        run: |
          # Calculate the date 14 days ago
          cutoff_date=$(date -d "14 days ago" +%Y-%m-%d)

          # List and delete artifacts older than cutoff date
          gh api repos/$REPO/actions/artifacts --paginate | \
          jq -r '.artifacts[] | select(.name | startswith("cherry-studio-nightly-")) | select(.created_at < "'$cutoff_date'") | .id' | \
          while read artifact_id; do
            echo "Deleting artifact $artifact_id"
            gh api repos/$REPO/actions/artifacts/$artifact_id -X DELETE
          done

  check-repository:
    runs-on: ubuntu-latest
    outputs:
      should_run: ${{ github.repository == 'CherryHQ/cherry-studio' }}
    steps:
      - name: Check if running in main repository
        run: |
          echo "Running in repository: ${{ github.repository }}"
          echo "Should run: ${{ github.repository == 'CherryHQ/cherry-studio' }}"

  nightly-build:
    needs: check-repository
    if: needs.check-repository.outputs.should_run == 'true'
    runs-on: ${{ matrix.os }}

    strategy:
      matrix:
        os: [macos-latest, windows-latest, ubuntu-latest]
      fail-fast: false

    steps:
      - name: Check out Git repository
        uses: actions/checkout@v5
        with:
          ref: main

      - name: Install Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 20

      - name: macos-latest dependencies fix
        if: matrix.os == 'macos-latest'
        run: |
          brew install python-setuptools

      - name: Install corepack
        run: corepack enable && corepack prepare yarn@4.6.0 --activate

      - name: Get yarn cache directory path
        id: yarn-cache-dir-path
        run: echo "dir=$(yarn config get cacheFolder)" >> $GITHUB_OUTPUT

      - name: Cache yarn dependencies
        uses: actions/cache@v4
        with:
          path: |
            ${{ steps.yarn-cache-dir-path.outputs.dir }}
            node_modules
          key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
          restore-keys: |
            ${{ runner.os }}-yarn-

      - name: Install Dependencies
        run: yarn install

      - name: Generate date tag
        id: date
        run: echo "date=$(date +'%Y%m%d')" >> $GITHUB_OUTPUT
        shell: bash

      - name: Build Linux
        if: matrix.os == 'ubuntu-latest'
        run: |
          sudo apt-get install -y rpm
          yarn build:linux
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          NODE_OPTIONS: --max-old-space-size=8192
          MAIN_VITE_CHERRYIN_CLIENT_SECRET: ${{ secrets.MAIN_VITE_CHERRYIN_CLIENT_SECRET }}
          MAIN_VITE_MINERU_API_KEY: ${{ vars.MAIN_VITE_MINERU_API_KEY }}
          RENDERER_VITE_AIHUBMIX_SECRET: ${{ vars.RENDERER_VITE_AIHUBMIX_SECRET }}
          RENDERER_VITE_PPIO_APP_SECRET: ${{ vars.RENDERER_VITE_PPIO_APP_SECRET }}

      - name: Build Mac
        if: matrix.os == 'macos-latest'
        run: |
          yarn build:mac
        env:
          CSC_LINK: ${{ secrets.CSC_LINK }}
          CSC_KEY_PASSWORD: ${{ secrets.CSC_KEY_PASSWORD }}
          APPLE_ID: ${{ vars.APPLE_ID }}
          APPLE_APP_SPECIFIC_PASSWORD: ${{ vars.APPLE_APP_SPECIFIC_PASSWORD }}
          APPLE_TEAM_ID: ${{ vars.APPLE_TEAM_ID }}
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          NODE_OPTIONS: --max-old-space-size=8192
          MAIN_VITE_CHERRYIN_CLIENT_SECRET: ${{ secrets.MAIN_VITE_CHERRYIN_CLIENT_SECRET }}
          MAIN_VITE_MINERU_API_KEY: ${{ vars.MAIN_VITE_MINERU_API_KEY }}
          RENDERER_VITE_AIHUBMIX_SECRET: ${{ vars.RENDERER_VITE_AIHUBMIX_SECRET }}
          RENDERER_VITE_PPIO_APP_SECRET: ${{ vars.RENDERER_VITE_PPIO_APP_SECRET }}

      - name: Build Windows
        if: matrix.os == 'windows-latest'
        run: |
          yarn build:win
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          NODE_OPTIONS: --max-old-space-size=8192
          MAIN_VITE_CHERRYIN_CLIENT_SECRET: ${{ secrets.MAIN_VITE_CHERRYIN_CLIENT_SECRET }}
          MAIN_VITE_MINERU_API_KEY: ${{ vars.MAIN_VITE_MINERU_API_KEY }}
          RENDERER_VITE_AIHUBMIX_SECRET: ${{ vars.RENDERER_VITE_AIHUBMIX_SECRET }}
          RENDERER_VITE_PPIO_APP_SECRET: ${{ vars.RENDERER_VITE_PPIO_APP_SECRET }}

      - name: Rename artifacts with nightly format
        shell: bash
        run: |
          mkdir -p renamed-artifacts
          DATE=${{ steps.date.outputs.date }}

          # Windows artifacts - based on actual file naming pattern
          if [ "${{ matrix.os }}" == "windows-latest" ]; then
            # Setup installer
            find dist -name "*-x64-setup.exe" -exec cp {} renamed-artifacts/cherry-studio-nightly-${DATE}-x64-setup.exe \;
            find dist -name "*-arm64-setup.exe" -exec cp {} renamed-artifacts/cherry-studio-nightly-${DATE}-arm64-setup.exe \;

            # Portable exe
            find dist -name "*-x64-portable.exe" -exec cp {} renamed-artifacts/cherry-studio-nightly-${DATE}-x64-portable.exe \;
            find dist -name "*-arm64-portable.exe" -exec cp {} renamed-artifacts/cherry-studio-nightly-${DATE}-arm64-portable.exe \;
          fi

          # macOS artifacts
          if [ "${{ matrix.os }}" == "macos-latest" ]; then
            find dist -name "*-arm64.dmg" -exec cp {} renamed-artifacts/cherry-studio-nightly-${DATE}-arm64.dmg \;
            find dist -name "*-x64.dmg" -exec cp {} renamed-artifacts/cherry-studio-nightly-${DATE}-x64.dmg \;
          fi

          # Linux artifacts
          if [ "${{ matrix.os }}" == "ubuntu-latest" ]; then
            find dist -name "*-x86_64.AppImage" -exec cp {} renamed-artifacts/cherry-studio-nightly-${DATE}-x86_64.AppImage \;
            find dist -name "*-arm64.AppImage" -exec cp {} renamed-artifacts/cherry-studio-nightly-${DATE}-arm64.AppImage \;
          fi

          # Copy update files
          cp dist/latest*.yml renamed-artifacts/ || true

      # Generate SHA256 checksums (Windows)
      - name: Generate SHA256 checksums (Windows)
        if: runner.os == 'Windows'
        shell: pwsh
        run: |
          cd renamed-artifacts
          echo "# SHA256 checksums for Windows - $(Get-Date -Format 'yyyy-MM-dd')" > SHA256SUMS.txt
          Get-ChildItem -File | Where-Object { $_.Name -ne 'SHA256SUMS.txt' } | ForEach-Object {
            $file = $_.Name
            $hash = (Get-FileHash -Algorithm SHA256 $file).Hash.ToLower()
            Add-Content -Path SHA256SUMS.txt -Value "$hash  $file"
          }
          cat SHA256SUMS.txt

      # Generate SHA256 checksums (macOS/Linux)
      - name: Generate SHA256 checksums (macOS/Linux)
        if: runner.os != 'Windows'
        shell: bash
        run: |
          cd renamed-artifacts
          echo "# SHA256 checksums for ${{ runner.os }} - $(date +'%Y-%m-%d')" > SHA256SUMS.txt
          if command -v shasum &>/dev/null; then
            # macOS
            shasum -a 256 * 2>/dev/null | grep -v SHA256SUMS.txt >> SHA256SUMS.txt || echo "No files to hash" >> SHA256SUMS.txt
          else
            # Linux
            sha256sum * 2>/dev/null | grep -v SHA256SUMS.txt >> SHA256SUMS.txt || echo "No files to hash" >> SHA256SUMS.txt
          fi
          cat SHA256SUMS.txt

      - name: List files to be uploaded
        shell: bash
        run: |
          echo "准备上传的文件:"
          if [ -x "$(command -v tree)" ]; then
            tree renamed-artifacts
          elif [ "$RUNNER_OS" == "Windows" ]; then
            dir renamed-artifacts
          else
            ls -la renamed-artifacts
          fi
          echo "总计: $(find renamed-artifacts -type f | wc -l) 个文件"

      - name: Upload artifacts
        uses: actions/upload-artifact@v4
        with:
          name: cherry-studio-nightly-${{ steps.date.outputs.date }}-${{ matrix.os }}
          path: renamed-artifacts/*
          retention-days: 3 # 保留3天
          compression-level: 8

  Build-Summary:
    needs: nightly-build
    if: always()
    runs-on: ubuntu-latest
    steps:
      - name: Get date tag
        id: date
        run: echo "date=$(date +'%Y%m%d')" >> $GITHUB_OUTPUT
        shell: bash

      - name: Download all artifacts
        uses: actions/download-artifact@v5
        with:
          path: all-artifacts
          merge-multiple: false
        continue-on-error: true

      - name: Create summary report
        run: |
          echo "## ⚠️ 警告：这是每日构建版本" >> $GITHUB_STEP_SUMMARY
          echo "此版本为自动构建的不稳定版本，仅供测试使用。不建议在生产环境中使用。" >> $GITHUB_STEP_SUMMARY
          echo "安装此版本前请务必备份数据，并做好数据迁移准备。" >> $GITHUB_STEP_SUMMARY
          echo "构建日期：$(date +'%Y-%m-%d')" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY

          echo "## 📦 安装包校验和" >> $GITHUB_STEP_SUMMARY
          echo "请在下载后验证文件完整性。提供 SHA256 校验和。" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY

          # Check each platform's artifacts and show checksums if available

          # Windows
          WIN_ARTIFACT_DIR="all-artifacts/cherry-studio-nightly-${{ steps.date.outputs.date }}-windows-latest"
          if [ -d "$WIN_ARTIFACT_DIR" ] && [ -f "$WIN_ARTIFACT_DIR/SHA256SUMS.txt" ]; then
            echo "### Windows 安装包" >> $GITHUB_STEP_SUMMARY
            echo '```' >> $GITHUB_STEP_SUMMARY
            cat "$WIN_ARTIFACT_DIR/SHA256SUMS.txt" >> $GITHUB_STEP_SUMMARY
            echo '```' >> $GITHUB_STEP_SUMMARY
            echo "" >> $GITHUB_STEP_SUMMARY
          else
            echo "### Windows 安装包" >> $GITHUB_STEP_SUMMARY
            echo "❌ Windows 构建未成功完成或未生成校验和。" >> $GITHUB_STEP_SUMMARY
            echo "" >> $GITHUB_STEP_SUMMARY
          fi

          # macOS
          MAC_ARTIFACT_DIR="all-artifacts/cherry-studio-nightly-${{ steps.date.outputs.date }}-macos-latest"
          if [ -d "$MAC_ARTIFACT_DIR" ] && [ -f "$MAC_ARTIFACT_DIR/SHA256SUMS.txt" ]; then
            echo "### macOS 安装包" >> $GITHUB_STEP_SUMMARY
            echo '```' >> $GITHUB_STEP_SUMMARY
            cat "$MAC_ARTIFACT_DIR/SHA256SUMS.txt" >> $GITHUB_STEP_SUMMARY
            echo '```' >> $GITHUB_STEP_SUMMARY
            echo "" >> $GITHUB_STEP_SUMMARY
          else
            echo "### macOS 安装包" >> $GITHUB_STEP_SUMMARY
            echo "❌ macOS 构建未成功完成或未生成校验和。" >> $GITHUB_STEP_SUMMARY
            echo "" >> $GITHUB_STEP_SUMMARY
          fi

          # Linux
          LINUX_ARTIFACT_DIR="all-artifacts/cherry-studio-nightly-${{ steps.date.outputs.date }}-ubuntu-latest"
          if [ -d "$LINUX_ARTIFACT_DIR" ] && [ -f "$LINUX_ARTIFACT_DIR/SHA256SUMS.txt" ]; then
            echo "### Linux 安装包" >> $GITHUB_STEP_SUMMARY
            echo '```' >> $GITHUB_STEP_SUMMARY
            cat "$LINUX_ARTIFACT_DIR/SHA256SUMS.txt" >> $GITHUB_STEP_SUMMARY
            echo '```' >> $GITHUB_STEP_SUMMARY
            echo "" >> $GITHUB_STEP_SUMMARY
          else
            echo "### Linux 安装包" >> $GITHUB_STEP_SUMMARY
            echo "❌ Linux 构建未成功完成或未生成校验和。" >> $GITHUB_STEP_SUMMARY
            echo "" >> $GITHUB_STEP_SUMMARY
          fi

          echo "## ⚠️ Warning: This is a nightly build version" >> $GITHUB_STEP_SUMMARY
          echo "This version is an unstable version built automatically and is only for testing. It is not recommended to use it in a production environment." >> $GITHUB_STEP_SUMMARY
          echo "Please backup your data before installing this version and prepare for data migration." >> $GITHUB_STEP_SUMMARY
          echo "Build date: $(date +'%Y-%m-%d')" >> $GITHUB_STEP_SUMMARY
