name: Deploy Sphinx Documentation

on:
  pull_request:
    types: [closed]
    branches: [master]

jobs:
  deploy:
    if: github.event.pull_request.merged == true && github.base_ref == 'master'
    runs-on: linux
    
    steps:
      # 第一步：更新主工作树
      - name: Update main worktree
        run: |
          echo "=== Updating main worktree ==="
          cd /home/ly0kos/work/test_env
          
          git fetch --all --prune
          git checkout master
          git pull origin master
          
          echo "✓ Main worktree updated"

      # 第二步：复用共享虚拟环境
      - name: Reuse shared virtual environment
        run: |
          echo "=== Using shared virtual environment ==="
          cd /home/ly0kos/work/test_env
          source .venv-shared/bin/activate
          
          # 检查主分支的requirements.txt是否有更新
          if [ -f "requirements.txt" ]; then
            REQ_MOD_TIME=$(stat -c %Y requirements.txt 2>/dev/null || echo 0)
            VENV_MOD_TIME=$(cat .venv-shared/last_update.txt 2>/dev/null || echo 0)
            
            if [ $REQ_MOD_TIME -gt $VENV_MOD_TIME ]; then
              echo "Master branch requirements updated, installing new dependencies..."
              pip install -r requirements.txt --no-cache-dir
              echo $REQ_MOD_TIME > .venv-shared/last_update.txt
            fi
          fi

      # 第三步：从主工作树构建文档
      - name: Build documentation from master
        run: |
          echo "=== Building production documentation ==="
          cd /home/ly0kos/work/test_env
          source .venv-shared/bin/activate
          
          rm -rf build/
          sphinx-build -b html source build -v -j 4
          echo "✓ Production build completed"

      # 第四步：部署到Web服务器
      - name: Deploy to web server
        run: |
          echo "=== Deploying to production ==="
          cd /home/ly0kos/work/test_env
          
          rm -rf /var/www/docs_dev/*
          cp -r build/* /var/www/docs_dev/
          
          echo "✓ Documentation deployed"

      # 第五步：清理PR工作树
      - name: Cleanup PR worktree
        run: |
          echo "=== Cleaning up PR worktree ==="
          cd /home/ly0kos/work/test_env
          
          WORKTREE_DIR="/home/ly0kos/work/test_env/worktrees/${{ github.head_ref }}"
          if [ -d "$WORKTREE_DIR" ]; then
            git worktree remove "$WORKTREE_DIR" --force
            echo "✓ Removed worktree for ${{ github.head_ref }}"
          fi
          
          # 清理预览文件
          PREVIEW_DIR="/home/ly0kos/work/test_env/pr-builds/${{ github.head_ref }}"
          if [ -d "$PREVIEW_DIR" ]; then
            rm -rf "$PREVIEW_DIR"
            echo "✓ Removed preview for ${{ github.head_ref }}"
          fi

      # 第六步：验证部署
      - name: Verify deployment
        run: |
          echo "Production deployment completed!"
          ls -la /var/www/docs_dev/ | head -10