name: Nightly Build (Linux)

on:
  schedule:
    # 01:00 MSK = 22:00 UTC предыдущего дня
    - cron: '0 22 * * *'
  workflow_dispatch:
    inputs:
      force_build:
        description: 'Force build even without recent changes'
        type: boolean
        default: false

env:
  PROJECT_NAME: Game_2
  BUILD_CONFIG: Shipping
  ENGINE_DIR: /opt/unreal-engine
  RETENTION_DAYS: 7

jobs:
  check-changes:
    runs-on: ubuntu-latest
    outputs:
      should_build: ${{ steps.check.outputs.should_build }}
      commit_count: ${{ steps.check.outputs.commit_count }}
      last_commit: ${{ steps.check.outputs.last_commit }}
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 2

      - name: Check for changes in last 24 hours
        id: check
        run: |
          FORCE="${{ github.event.inputs.force_build }}"
          
          if [ "$FORCE" = "true" ]; then
            echo "should_build=true" >> $GITHUB_OUTPUT
            echo "commit_count=forced" >> $GITHUB_OUTPUT
            echo "last_commit=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT
            echo "🔧 Force build requested"
            exit 0
          fi
          
          CHANGES=$(git log --since="24 hours ago" --oneline 2>/dev/null | wc -l)
          LAST_COMMIT=$(git rev-parse --short HEAD)
          
          if [ "$CHANGES" -gt 0 ]; then
            echo "should_build=true" >> $GITHUB_OUTPUT
            echo "commit_count=$CHANGES" >> $GITHUB_OUTPUT
            echo "last_commit=$LAST_COMMIT" >> $GITHUB_OUTPUT
            echo "✅ Found $CHANGES commits in last 24h"
          else
            echo "should_build=false" >> $GITHUB_OUTPUT
            echo "commit_count=0" >> $GITHUB_OUTPUT
            echo "last_commit=$LAST_COMMIT" >> $GITHUB_OUTPUT
            echo "⏭️ No recent changes, skipping build"
          fi

  build-linux:
    needs: check-changes
    if: needs.check-changes.outputs.should_build == 'true'
    runs-on: ubuntu-latest
    timeout-minutes: 180
    container:
      image: node:20-bookworm
      options: -v /mnt/0948cd7e-e5a9-4d99-9bcc-459c8361e842/docker-container/Gitea/runner-programm/unreal-engine/UE-5.8.1:/opt/unreal-engine:ro --user root

    steps:
      # ✅ УСТАНОВКА GIT-LFS ДО CHECKOUT
      - name: Install git-lfs
        run: apt-get update && apt-get install -y git-lfs && git lfs install

      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          lfs: true

      - name: Pull LFS files
        run: |
          git lfs pull
          echo "📦 LFS files pulled"

      - name: Verify UE5 engine mount
        run: |
          if [ ! -f "$ENGINE_DIR/Engine/Build/BatchFiles/Linux/Build.sh" ]; then
            echo "::error::UE5 Build.sh not found at $ENGINE_DIR"
            echo "::error::Check docker-compose volume mount for /opt/unreal-engine"
            exit 1
          fi
          
          # Проверка версии движка
          VERSION_FILE="$ENGINE_DIR/Engine/Source/Runtime/Launch/Resources/Version.h"
          if [ -f "$VERSION_FILE" ]; then
            ENGINE_VER=$(grep "ENGINE_MAJOR_VERSION\|ENGINE_MINOR_VERSION\|ENGINE_PATCH_VERSION" "$VERSION_FILE" | head -3 | tr '\n' '.' | sed 's/[^0-9.]//g')
            echo "🎮 UE5 Version: $ENGINE_VER"
          fi
          
          echo "✅ UE5 engine verified at $ENGINE_DIR"

      - name: Clean previous build artifacts
        run: |
          rm -rf Binaries/Linux Intermediate/Build/Linux
          echo "🧹 Previous artifacts cleaned"

      - name: Build Linux ${{ env.BUILD_CONFIG }}
        run: |
          SHORT_SHA="${{ github.sha }}"
          ARCHIVE_NAME="${PROJECT_NAME}-Linux-${SHORT_SHA::7}.tar.gz"
          
          echo "🔨 Starting build: $PROJECT_NAME Linux $BUILD_CONFIG"
          echo "📁 Project: $(pwd)/${PROJECT_NAME}.uproject"
          echo "📦 Output: $ARCHIVE_NAME"
          
          "$ENGINE_DIR/Engine/Build/BatchFiles/Linux/Build.sh" \
            "${PROJECT_NAME}" \
            Linux \
            "${BUILD_CONFIG}" \
            -Project="$(pwd)/${PROJECT_NAME}.uproject" \
            -NoP4 \
            -UTF8Output \
            -Clean \
            -SkipVulkanDeviceExtensions=VK_KHR_swapchain_mutable_format
          
          # Архивация билда
          if [ -d "Binaries/Linux" ]; then
            tar -czf "$ARCHIVE_NAME" \
              -C Binaries/Linux \
              . \
              ../../Content/Paks/* 2>/dev/null || true
            
            SIZE=$(du -h "$ARCHIVE_NAME" | cut -f1)
            echo "📦 Archive created: $ARCHIVE_NAME ($SIZE)"
            echo "ARCHIVE_NAME=$ARCHIVE_NAME" >> $GITHUB_ENV
          else
            echo "::error::Build output directory not found"
            exit 1
          fi

      - name: Upload Linux artifact
        uses: actions/upload-artifact@v4
        with:
          name: linux-build
          path: ${{ env.ARCHIVE_NAME }}
          retention-days: ${{ env.RETENTION_DAYS }}
          compression-level: 6

  release:
    needs: [check-changes, build-linux]
    if: always() && needs.build-linux.result == 'success'
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - name: Download build artifact
        uses: actions/download-artifact@v4
        with:
          name: linux-build

      - name: Generate release metadata
        id: meta
        run: |
          DATE=$(date +'%Y%m%d')
          SHA_SHORT="${{ github.sha }}"
          TAG="nightly-${DATE}-${SHA_SHORT::7}"
          
          echo "tag=$TAG" >> $GITHUB_OUTPUT
          echo "date=$DATE" >> $GITHUB_OUTPUT
          echo "sha_short=${SHA_SHORT::7}" >> $GITHUB_OUTPUT
          
          # Список файлов для загрузки
          FILES=$(ls *.tar.gz 2>/dev/null | tr '\n' '\n')
          echo "files<<EOF" >> $GITHUB_OUTPUT
          echo "$FILES" >> $GITHUB_OUTPUT
          echo "EOF" >> $GITHUB_OUTPUT

      - name: Create Nightly Release
        uses: softprops/action-gh-release@v2
        with:
          tag_name: ${{ steps.meta.outputs.tag }}
          name: "🌙 Nightly ${{ steps.meta.outputs.date }} (${{ steps.meta.outputs.sha_short }})"
          body: |
            ## 🌙 Nightly Build — Linux
            
            | Property | Value |
            |----------|-------|
            | **Platform** | Linux (x64) |
            | **Config** | ${{ env.BUILD_CONFIG }} |
            | **Commit** | `${{ github.sha }}` |
            | **Date** | ${{ steps.meta.outputs.date }} |
            | **Changes** | ${{ needs.check-changes.outputs.commit_count }} commits |
            
            ### 📥 Downloads
            - 🐧 **Linux:** `${{ env.PROJECT_NAME }}-Linux-${{ steps.meta.outputs.sha_short }}.tar.gz`
            
            ---
            > ⚠️ Auto-generated nightly build. May be unstable.
            > Built with UE5 from `/opt/unreal-engine` via Docker volume mount.
          draft: false
          prerelease: true
          files: ${{ steps.meta.outputs.files }}
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}