name: Build and Test

on:
  push:
    branches:
      - main
      - develop
  pull_request:
  workflow_dispatch:

concurrency:
  group: game-ci-${{ github.ref }}
  cancel-in-progress: true

env:
  GODOT_VERSION: "4.3"
  PROJECT_PATH: "./game"

jobs:
  test:
    name: Test and Validate
    runs-on: ubuntu-latest
    timeout-minutes: 20

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

      - name: Restore import cache
        uses: actions/cache@v4
        with:
          path: ${{ env.PROJECT_PATH }}/.godot/imported
          key: godot-imports-${{ runner.os }}-${{ hashFiles('game/**/*.import') }}
          restore-keys: |
            godot-imports-${{ runner.os }}-

      - name: Install Godot
        uses: chickensoft-games/setup-godot@v2
        with:
          version: ${{ env.GODOT_VERSION }}
          use-dotnet: false
          include-templates: true

      - name: Import project assets
        run: godot --headless --path "$PROJECT_PATH" --import

      - name: Run unit tests
        run: >
          godot --headless
          --path "$PROJECT_PATH"
          -s addons/gut/gut_cmdln.gd
          -gdir=res://tests
          -gexit

      - name: Validate project startup
        run: timeout 30s godot --headless --path "$PROJECT_PATH" --quit-after 5

  export:
    name: Export ${{ matrix.preset }}
    needs: test
    runs-on: ubuntu-latest
    timeout-minutes: 30

    strategy:
      fail-fast: false
      matrix:
        include:
          - preset: Windows Desktop
            artifact: windows
            output: build/windows/starfall.exe
          - preset: Linux
            artifact: linux
            output: build/linux/starfall.x86_64
          - preset: Web
            artifact: web
            output: build/web/index.html

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

      - name: Install Godot
        uses: chickensoft-games/setup-godot@v2
        with:
          version: ${{ env.GODOT_VERSION }}
          use-dotnet: false
          include-templates: true

      - name: Create export directory
        run: mkdir -p "$(dirname '${{ matrix.output }}')"

      - name: Export release build
        run: >
          godot --headless
          --path "$PROJECT_PATH"
          --export-release "${{ matrix.preset }}"
          "../${{ matrix.output }}"

      - name: Upload build artifact
        uses: actions/upload-artifact@v4
        with:
          name: starfall-${{ matrix.artifact }}-${{ github.sha }}
          path: build/${{ matrix.artifact }}
          if-no-files-found: error
          retention-days: 14