# GitHub Actions workflow for Ruff code formatting and linting
# 自动运行 Ruff 格式检查和修复
#
# 触发条件：
# 1. Push 到 main 分支时：自动格式化并提交

name: Ruff Format Check

on:
  push:
    branches:
      - main
    paths:
      - '**.py'
      - 'pyproject.toml'
      - 'Makefile'
      - '.github/workflows/ruff.yml'

# 设置写入权限，允许自动提交格式化代码
permissions:
  contents: write

jobs:
  ruff:
    name: Ruff Format & Lint
    runs-on: ubuntu-latest

    steps:
      # 1. 检出代码
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          token: ${{ secrets.GITHUB_TOKEN }}

      # 2. 安装 uv（项目使用 uv 作为包管理器）
      - name: Install uv
        uses: astral-sh/setup-uv@v4
        with:
          version: "0.7.2"

      # 3. 设置 Python 环境
      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.12'

      # 4. 安装 ruff 依赖（根据项目配置，ruff 在 dev 依赖组中）
      - name: Install dependencies
        run: |
          uv sync --group dev

      # 5. 运行 Ruff 格式检查（与项目的 make lint 命令一致）
      - name: Run Ruff format check
        id: ruff-format
        run: |
          set +e  # 不立即退出失败

          echo "Running ruff check (uv run python -m ruff check .)..."
          uv run python -m ruff check .
          ruff_check_result=$?

          echo "Running ruff format diff check (uv run python -m ruff format src --diff)..."
          uv run python -m ruff format src --diff
          ruff_format_result=$?

          echo "Running import sorting check (uv run python -m ruff check --select I src)..."
          uv run python -m ruff check --select I src
          ruff_import_result=$?

          # 检查是否有任何错误
          if [ $ruff_check_result -eq 0 ] && [ $ruff_format_result -eq 0 ] && [ $ruff_import_result -eq 0 ]; then
            echo "ruff_format_passed=true" >> $GITHUB_OUTPUT
            echo "✅ Ruff format check passed"
          else
            echo "ruff_format_passed=false" >> $GITHUB_OUTPUT
            echo "❌ Ruff format check failed"
            echo "::warning::Ruff format check found issues that should be addressed"

            # 汇总错误信息
            echo "## Ruff Format Issues Summary" > $GITHUB_STEP_SUMMARY
            echo "" >> $GITHUB_STEP_SUMMARY
            echo "The following formatting issues were found:" >> $GITHUB_STEP_SUMMARY
            echo "" >> $GITHUB_STEP_SUMMARY

            # 运行 ruff check 以获取详细错误信息
            echo "### Detailed Issues:" >> $GITHUB_STEP_SUMMARY
            uv run python -m ruff check . --output-format=github >> $GITHUB_STEP_SUMMARY 2>&1 || true

            echo "" >> $GITHUB_STEP_SUMMARY
            echo "To fix these issues locally, run:" >> $GITHUB_STEP_SUMMARY
            echo "\`\`\`bash" >> $GITHUB_STEP_SUMMARY
            echo "make format" >> $GITHUB_STEP_SUMMARY
            echo "\`\`\`" >> $GITHUB_STEP_SUMMARY
          fi

      # 6. 针对不同事件类型执行不同操作
      - name: Process Ruff Results
        if: ${{ github.event_name == 'push' }}
        env:
          GIT_AUTHOR_NAME: "GitHub Actions"
          GIT_AUTHOR_EMAIL: "actions@github.com"
          GIT_COMMITTER_NAME: "GitHub Actions"
          GIT_COMMITTER_EMAIL: "actions@github.com"
        run: |
          echo "Processing push event to main branch..."

          # 检查当前是否有未提交的修改
          if ! git diff --exit-code --quiet; then
            echo "⚠️  Warning: There are uncommitted changes before formatting"
            echo "The formatting process might need to handle this specially."
          fi

          # 先检查是否有格式问题
          echo "Checking for formatting issues..."
          set +e
          uv run python -m ruff check . --quiet
          has_ruff_issues=$?
          set -e

          if [ $has_ruff_issues -eq 0 ]; then
            echo "✅ No formatting issues found"
            exit 0
          fi

          echo "Formatting issues detected, running automatic fixes..."

          # 自动应用格式修复（与项目的 make format 命令一致）
          echo "Running uv run ruff format ."
          uv run ruff format .

          echo "Running uv run ruff check . --fix"
          uv run ruff check . --fix

          echo "Running uv run python -m ruff check --select I src --fix"
          uv run python -m ruff check --select I src --fix

          # 检查是否有格式变更
          echo "Checking for formatting changes..."
          if git diff --exit-code --quiet; then
            echo "✅ No formatting changes needed"
          else
            echo "📝 Formatting changes detected"
            echo "Changed files:"
            git diff --name-only

            # 添加所有变更并提交
            git add .
            git commit -m "style: auto-format with ruff [skip ci]"

            echo "📤 Pushing formatting changes..."
            git push
            echo "✅ Formatting changes committed and pushed"
          fi
