name: Code Quality

on:
  push:
    branches: [ main, develop ]
  pull_request:
    branches: [ main ]

permissions:
  contents: read

jobs:
  lint:
    name: Lint & Format
    runs-on: ubuntu-latest

    steps:
    - name: Checkout repository
      uses: actions/checkout@v6

    - name: Set up Python
      uses: actions/setup-python@v6
      with:
        python-version: "3.10"

    - name: Cache pip dependencies
      uses: actions/cache@v5
      with:
        path: ~/.cache/pip
        key: ${{ runner.os }}-pip-lint-${{ hashFiles('**/pyproject.toml') }}
        restore-keys: |
          ${{ runner.os }}-pip-lint-

    - name: Install lint dependencies
      run: |
        python -m pip install --upgrade pip
        pip install ruff mypy

    - name: Run Ruff (linter)
      run: |
        echo "=== Running Ruff Linter ==="
        ruff check . --statistics || {
          echo "::error::Ruff linter found issues. Run: ruff check . --fix"
          exit 1
        }

    - name: Run Ruff (formatter)
      run: |
        echo "=== Running Ruff Formatter ==="
        ruff format --check . || {
          echo "::error::Ruff formatter found issues. Run: ruff format ."
          exit 1
        }

    - name: Run MyPy (type checker)
      run: |
        echo "=== Running MyPy Type Checker ==="
        mypy rdagent/ \
          --ignore-missing-imports \
          --no-strict-optional \
          --follow-imports=skip \
          --warn-return-any || {
          echo "::warning::MyPy found type issues (non-blocking)"
          # Non-blocking: MyPy warnings don't fail the build
          exit 0
        }

    - name: Check for trailing whitespace
      run: |
        echo "=== Checking for trailing whitespace ==="
        if grep -rIn '[[:space:]]$' --include='*.py' --include='*.md' --include='*.rst' . | grep -v '.git'; then
          echo "::error::Found trailing whitespace. Please remove it."
          exit 1
        fi
        echo "✓ No trailing whitespace found"

    - name: Check for merge conflicts
      run: |
        echo "=== Checking for merge conflict markers ==="
        if grep -rn '<<<<<<< HEAD\|=======\|>>>>>>>' --include='*.py' --include='*.md' . | grep -v '.git'; then
          echo "::error::Found merge conflict markers. Please resolve them."
          exit 1
        fi
        echo "✓ No merge conflict markers found"
