name: GDScript Linting

on:
  # Trigger on push to any branch
  push:
    branches: ['*']
    paths:
      - '**/*.gd'
      - '.gdlintrc'
      - '.gitea/workflows/gdlint.yml'

  # Trigger on pull requests
  pull_request:
    branches: ['*']
    paths:
      - '**/*.gd'
      - '.gdlintrc'
      - '.gitea/workflows/gdlint.yml'

  # Allow manual triggering
  workflow_dispatch:

jobs:
  gdlint:
    name: GDScript Code Quality Check
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Set up Python
        uses: actions/setup-python@v4
        with:
          python-version: '3.11'
          cache: 'pip'

      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          pip install --upgrade "setuptools<81"
          pip install gdtoolkit==4

      - name: Verify gdlint installation
        run: |
          gdlint --version
          echo "✅ gdlint installed successfully"

      - name: Count GDScript files
        id: count-files
        run: |
          file_count=$(find . -name "*.gd" -not -path "./.git/*" | wc -l)
          echo "file_count=$file_count" >> $GITHUB_OUTPUT
          echo "📊 Found $file_count GDScript files to lint"

      - name: Run GDScript linting
        run: |
          echo "🔍 Starting GDScript linting..."
          echo "================================"

          # Initialize counters
          total_files=0
          clean_files=0
          warning_files=0
          error_files=0

          # Find all .gd files except TestHelper.gd (static var syntax incompatibility)
          while IFS= read -r -d '' file; do
            filename=$(basename "$file")

            # Skip TestHelper.gd due to static var syntax incompatibility with gdlint
            if [[ "$filename" == "TestHelper.gd" ]]; then
              echo "⚠️  Skipping $file (static var syntax not supported by gdlint)"
              ((total_files++))
              ((clean_files++))
              continue
            fi

            echo "🔍 Linting: $file"
            ((total_files++))

            # Run gdlint and capture output
            if output=$(gdlint "$file" 2>&1); then
              if [[ -z "$output" ]]; then
                echo "✅ Clean"
                ((clean_files++))
              else
                echo "⚠️  Warnings found:"
                echo "$output"
                ((warning_files++))
              fi
            else
              echo "❌ Errors found:"
              echo "$output"
              ((error_files++))
            fi
            echo ""

          done < <(find . -name "*.gd" -not -path "./.git/*" -print0)

          # Print summary
          echo "================================"
          echo "📋 Linting Summary"
          echo "================================"
          echo "📊 Total files: $total_files"
          echo "✅ Clean files: $clean_files"
          echo "⚠️  Files with warnings: $warning_files"
          echo "❌ Files with errors: $error_files"
          echo ""

          # Set exit code based on results
          if [[ $error_files -gt 0 ]]; then
            echo "❌ Linting FAILED - $error_files file(s) have errors"
            echo "Please fix the errors above before merging"
            exit 1
          elif [[ $warning_files -gt 0 ]]; then
            echo "⚠️  Linting PASSED with warnings - Consider fixing them"
            echo "✅ No blocking errors found"
            exit 0
          else
            echo "✅ All GDScript files passed linting!"
            echo "🎉 Code quality check complete - ready for merge"
            exit 0
          fi

      - name: Upload linting results
        if: failure()
        uses: actions/upload-artifact@v3
        with:
          name: gdlint-results
          path: |
            **/*.gd
          retention-days: 7

      - name: Comment on PR (if applicable)
        if: github.event_name == 'pull_request' && failure()
        uses: actions/github-script@v6
        with:
          script: |
            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: '❌ **GDScript Linting Failed**\n\nPlease check the workflow logs and fix the linting errors before merging.\n\n[View workflow run](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})'
            })