name: Bird Survey CI

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

env:
  NODE_VERSION: "22"
  PYTHON_VERSION: "3.12"
  DATABASE_URL: postgresql://survey:survey@localhost:5432/bird_survey
  REDIS_URL: redis://localhost:6379/0
  TAXONOMY_FILE: data/taxonomy/ebird-clements-2026.csv

jobs:
  validate-and-test:
    runs-on: ubuntu-latest

    services:
      postgres:
        image: postgis/postgis:16-3.4
        env:
          POSTGRES_DB: bird_survey
          POSTGRES_USER: survey
          POSTGRES_PASSWORD: survey
        ports:
          - 5432:5432
        options: >-
          --health-cmd "pg_isready -U survey -d bird_survey"
          --health-interval 10s
          --health-timeout 5s
          --health-retries 6

      redis:
        image: redis:7-alpine
        ports:
          - 6379:6379
        options: >-
          --health-cmd "redis-cli ping"
          --health-interval 10s
          --health-timeout 5s
          --health-retries 6

    steps:
      - name: Check out repository
        uses: actions/checkout@v4

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: ${{ env.PYTHON_VERSION }}
          cache: pip

      - name: Set up Node
        uses: actions/setup-node@v4
        with:
          node-version: ${{ env.NODE_VERSION }}
          cache: npm
          cache-dependency-path: web/package-lock.json

      - name: Install API dependencies
        run: |
          python -m pip install --upgrade pip
          pip install -r api/requirements.txt -r api/requirements-dev.txt

      - name: Install web dependencies
        working-directory: web
        run: npm ci

      - name: Validate survey schemas and taxonomy
        run: |
          python tools/validate_observation_schema.py schemas/observation.schema.json
          python tools/validate_taxonomy.py "$TAXONOMY_FILE"

      - name: Run database migrations
        working-directory: api
        run: alembic upgrade head

      - name: Run API tests
        working-directory: api
        run: pytest tests --cov=birdsurvey --cov-report=xml

      - name: Run web lint and tests
        working-directory: web
        run: |
          npm run lint
          npm test -- --run

      - name: Build web app
        working-directory: web
        run: npm run build

      - name: Upload coverage report
        uses: actions/upload-artifact@v4
        with:
          name: api-coverage
          path: api/coverage.xml
          retention-days: 14