name: Code Quality Check

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

jobs:
  analyze:
    name: Flutter Analyze & Format Check
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Setup Flutter
        uses: subosito/flutter-action@v2
        with:
          flutter-version: '3.38.3'
          channel: 'stable'

      - name: Prepare local secrets for CI
        run: cp lib/secrets.local.dart.example lib/secrets.local.dart

      - name: Get dependencies
        run: flutter pub get

      - name: Verify formatting
        run: dart format --set-exit-if-changed .
        continue-on-error: true

      - name: Analyze code
        run: flutter analyze --no-fatal-infos --no-fatal-warnings

      - name: Check for secret files
        run: |
          if git ls-files --error-unmatch lib/secrets.local.dart 2>/dev/null; then
            echo "ERROR: secrets.local.dart is tracked by git! This file contains API keys and must not be committed."
            exit 1
          else
            echo "secrets.local.dart is properly excluded from git tracking"
          fi
          if grep -r "AIzaSy" lib/ --include="*.dart" 2>/dev/null; then
            echo "Possible API key found in source code!"
            exit 1
          else
            echo "No API keys found in source code"
          fi

      - name: Run tests (if exist)
        run: flutter test
        continue-on-error: true

      - name: Summary
        if: always()
        run: |
          echo "## 🎯 Quality Check Summary" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "- ✅ Code analyzed" >> $GITHUB_STEP_SUMMARY
          echo "- ✅ Format checked" >> $GITHUB_STEP_SUMMARY
          echo "- ✅ Security verified" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "🤖 Automated by GitHub Actions" >> $GITHUB_STEP_SUMMARY
