name: Build

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

jobs:
  build:
    name: Build project
    runs-on: ubuntu-22.04

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

      - name: Install system dependencies
        run: |
          sudo apt-get update
          
          # Check what Ubuntu version we're on
          echo "Ubuntu version:"
          lsb_release -a
          
          # Install essential build tools and C/C++ headers first
          sudo apt-get install -y build-essential gcc g++ make cmake
          # Install Clang and LLVM for bindgen
          sudo apt-get install -y clang libclang-dev llvm-dev
          # Try to install specific clang version if available
          sudo apt-get install -y libclang-14-dev || sudo apt-get install -y libclang-13-dev || sudo apt-get install -y libclang-12-dev || true
          # Install standard library headers
          sudo apt-get install -y libc6-dev linux-libc-dev
          # Install FFmpeg and development libraries
          sudo apt-get install -y ffmpeg libavcodec-dev libavformat-dev libavutil-dev libavfilter-dev libavdevice-dev libswscale-dev libswresample-dev pkg-config
          # GTK and GLib dependencies for Tauri
          sudo apt-get install -y libgtk-3-dev libwebkit2gtk-4.1-dev libglib2.0-dev libgdk-pixbuf2.0-dev libpango1.0-dev libatk1.0-dev libcairo-gobject2 libgtk-3-0 libgdk-pixbuf2.0-0
          
          # Debug: Check what GLib version is available
          echo "Available GLib packages:"
          apt-cache policy libglib2.0-dev | head -10
          
          # Check GLib version
          echo "Checking GLib version..."
          pkg-config --modversion glib-2.0 || echo "glib-2.0 not found"
          
          # If GLib is too old, we need to use a PPA or build from source
          # For Ubuntu, we can try to install from a newer release
          if ! pkg-config --atleast-version=2.70 glib-2.0 2>/dev/null; then
            echo "GLib version is too old, trying to install newer version..."
            # Ubuntu 22.04 should have GLib 2.72, make sure it's properly installed
            sudo apt-get update
            sudo apt-get install -y libglib2.0-dev libglib2.0-0 || true
            
            # Check again
            pkg-config --modversion glib-2.0 || echo "Still no glib-2.0 found"
          fi
          
          # Export PKG_CONFIG_PATH early
          echo "PKG_CONFIG_PATH=/usr/lib/x86_64-linux-gnu/pkgconfig:/usr/lib/pkgconfig:/usr/share/pkgconfig" >> $GITHUB_ENV
          export PKG_CONFIG_PATH=/usr/lib/x86_64-linux-gnu/pkgconfig:/usr/lib/pkgconfig:/usr/share/pkgconfig
          
          # Find and set up libclang for bindgen
          echo "=== Finding libclang ==="
          # Find libclang.so
          LIBCLANG_PATH=$(find /usr -name "libclang.so*" -type f 2>/dev/null | grep -E "libclang.so|libclang-[0-9]+.so" | head -1)
          if [ -n "$LIBCLANG_PATH" ]; then
            LIBCLANG_DIR=$(dirname "$LIBCLANG_PATH")
            echo "Found libclang at: $LIBCLANG_PATH"
            echo "Setting LIBCLANG_PATH=$LIBCLANG_DIR"
            echo "LIBCLANG_PATH=$LIBCLANG_DIR" >> $GITHUB_ENV
          else
            echo "WARNING: libclang.so not found, trying default paths"
            # Try common paths
            for path in /usr/lib/llvm-*/lib /usr/lib/x86_64-linux-gnu /usr/lib64 /usr/lib; do
              if [ -d "$path" ] && ls "$path"/libclang*.so* 2>/dev/null | grep -q .; then
                echo "Found libclang in: $path"
                echo "LIBCLANG_PATH=$path" >> $GITHUB_ENV
                break
              fi
            done
          fi
          
          # Set up bindgen clang args
          echo "BINDGEN_EXTRA_CLANG_ARGS=-I/usr/include -I/usr/include/x86_64-linux-gnu" >> $GITHUB_ENV

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'

      - name: Setup Rust
        uses: dtolnay/rust-toolchain@stable

      - name: Cache Rust dependencies
        uses: Swatinem/rust-cache@v2
        with:
          workspaces: src-tauri
          cache-on-failure: false
          key: ${{ runner.os }}-rust-${{ hashFiles('**/Cargo.lock') }}

      - name: Clean install dependencies
        run: |
          npm config set fetch-timeout 300000
          npm config set fetch-retries 5
          # Clean cache first
          npm cache clean --force
          # Try to install with retries
          npm ci --prefer-offline --no-audit --no-fund || \
          npm ci --no-audit --no-fund --omit=optional || \
          npm install --no-audit --no-fund --omit=optional

      - name: Set PKG_CONFIG_PATH for GLib
        run: |
          echo "PKG_CONFIG_PATH=/usr/lib/x86_64-linux-gnu/pkgconfig:/usr/lib/pkgconfig:/usr/share/pkgconfig" >> $GITHUB_ENV
          
          # Verify GLib version
          echo "Checking GLib version after setting PKG_CONFIG_PATH..."
          pkg-config --modversion glib-2.0 || echo "glib-2.0 still not found"
          
          # List available .pc files
          echo "Available pkg-config files:"
          ls -la /usr/lib/x86_64-linux-gnu/pkgconfig/glib*.pc || echo "No glib pc files in x86_64-linux-gnu"
          ls -la /usr/lib/pkgconfig/glib*.pc || echo "No glib pc files in lib/pkgconfig"
          ls -la /usr/share/pkgconfig/glib*.pc || echo "No glib pc files in share/pkgconfig"

      - name: Create dist directory
        run: mkdir -p dist

      - name: Verify Cargo configuration
        run: |
          cd src-tauri
          echo "=== Cargo.toml content ==="
          cat Cargo.toml | grep -A 10 -B 2 "tauri"
          echo ""
          echo "=== Checking if Cargo.lock exists ==="
          ls -la Cargo.lock || echo "Cargo.lock not found"
          echo ""
          echo "=== Tauri in Cargo.lock ==="
          grep -A 5 'name = "tauri"' Cargo.lock || echo "Tauri not found in Cargo.lock"

      - name: Build Rust dependencies
        env:
          PKG_CONFIG_PATH: /usr/lib/x86_64-linux-gnu/pkgconfig:/usr/lib/pkgconfig:/usr/share/pkgconfig
          RUST_BACKTRACE: 1
          CARGO_NET_GIT_FETCH_WITH_CLI: true
        run: |
          cd src-tauri
          
          # Show current directory and files
          echo "=== Current directory ==="
          pwd
          echo "=== Files in directory ==="
          ls -la
          
          # Update dependencies to ensure everything is fetched
          cargo update
          
          # Show what features will be used
          echo "=== Building with features ==="
          cargo tree -e features | grep -E "tauri|timeline-studio" | head -20 || echo "Failed to show features"
          
          # First check dependencies with default features (includes custom-protocol)
          echo "=== Running cargo check ==="
          cargo check --release --verbose
          
          # Then build with default features
          echo "=== Running cargo build ==="
          cargo build --release --verbose

      - name: Generate TypeScript bindings
        run: |
          cd src-tauri
          cargo run --bin generate_types

      - name: Build Next.js app
        run: npm run build

      - name: Run tests
        run: npm run test
