name: Infrastructure Validation

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

jobs:
  # Job 1: Test Docker builds
  test-docker:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v3

      - name: Build Docker images
        run: |
          docker compose build --no-cache

      - name: Verify containers start
        run: |
          docker compose up -d

          # Wait for health checks
          timeout 60s bash -c 'until docker compose ps | grep -q "healthy"; do sleep 5; done' || true

      - name: Test frontend endpoint
        run: |
          timeout 30s bash -c 'until curl -f http://localhost/; do sleep 2; done'

      - name: Test backend endpoint
        run: |
          timeout 30s bash -c 'until curl -f http://localhost:8000/health; do sleep 2; done'

      - name: Show logs on failure
        if: failure()
        run: |
          docker compose logs --tail=100

      - name: Cleanup
        if: always()
        run: |
          docker compose down -v

  # Job 2: Run all tests
  test-suite:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v3

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

      - name: Install dependencies
        run: |
          pip install pytest pytest-cov pytest-asyncio

      - name: Run ALL tests (including integration)
        run: |
          # CRITICAL: Do NOT skip slow tests
          pytest -v --tb=short

      - name: Check coverage
        run: |
          # Require 80% coverage minimum
          pytest --cov=. --cov-fail-under=80 --cov-report=term-missing

  # Job 3: Validate configurations
  validate-configs:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v3

      - name: Validate docker-compose syntax
        run: |
          docker compose config > /dev/null

      - name: Check for file-existence-only tests
        run: |
          # Verify we don't have bad test patterns
          if grep -r "assert Path.*\.exists()" tests/; then
            echo "❌ Found file-existence-only tests"
            echo "Tests must verify real functionality with subprocess.run()"
            grep -r "assert Path.*\.exists()" tests/
            exit 1
          fi

      - name: Verify no @pytest.mark.slow on critical tests
        run: |
          # Check integration tests aren't marked as slow
          if grep -r "@pytest.mark.slow" tests/test_*integration*.py; then
            echo "❌ Integration tests marked as @pytest.mark.slow"
            echo "Integration tests MUST run in CI"
            exit 1
          fi
