name: CI

on:
  push:
    branches: ["main"]
    tags: ["v*.*.*"]
  pull_request:
    branches: ["main"]

jobs:
  lint:
    name: Lint
    runs-on: ubuntu-latest
    permissions:
      contents: read

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

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

      - name: Install dependencies
        run: pip install flake8

      - name: Lint with flake8
        run: |
          # Stop the build on syntax errors or undefined names
          flake8 musicround/ --count --select=E9,F63,F7,F82 --show-source --statistics
          # Warn on style issues (exit-zero means the step won't fail on style warnings)
          flake8 musicround/ --count --exit-zero --statistics

  test:
    name: Test
    runs-on: ubuntu-latest
    permissions:
      contents: read
      actions: write

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

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

      - name: Install system dependencies
        run: |
          sudo apt-get update
          sudo apt-get install -y ffmpeg

      - name: Install Python dependencies
        run: pip install -r requirements.txt

      - name: Run tests with coverage
        env:
          FLASK_ENV: testing
          SECRET_KEY: ci-test-secret-key
          AUTOMATION_TOKEN: ci-test-automation-token
        run: |
          pytest tests/ -v --cov=musicround --cov-report=xml --cov-report=term-missing

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

  docker-build:
    name: Docker Build (validation)
    runs-on: ubuntu-latest
    needs: [lint, test]
    permissions:
      contents: read

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

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Build Docker image
        uses: docker/build-push-action@v6
        with:
          context: .
          push: false
          tags: quizzicalbeats:ci
          cache-from: type=gha
          cache-to: type=gha,mode=max
