# Runs all checks: JS/TS linting and Rust linting

name: Check All

on:
  push:
    branches:
      - main
  pull_request:

jobs:
  check-js:
    name: Check JavaScript/TypeScript
    timeout-minutes: 90
    strategy:
      fail-fast: false
      matrix:
        os: [ubuntu-22.04, windows-latest]

    runs-on: ${{ matrix.os }}

    steps:
      - name: Disable git core.autocrlf on Windows
        if: matrix.os == 'windows-latest'
        run: git config --global core.autocrlf false

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

      - name: Set up Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20.10.0'
          cache: "npm"

      - name: Install dependencies on Unix
        if: runner.os != 'Windows'
        run: |
          npm config set fetch-timeout 300000
          npm config set fetch-retries 5
          # 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: Install dependencies on Windows
        if: runner.os == 'Windows'
        shell: pwsh
        run: ./scripts/windows-npm-install.ps1

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

      - name: Install Linux dependencies for Tauri bindings
        if: runner.os != 'Windows'
        run: |
          sudo apt-get update
          sudo apt-get install -y libgtk-3-dev libwebkit2gtk-4.1-dev libglib2.0-dev
          # Install FFmpeg dependencies
          sudo apt-get install -y ffmpeg libavcodec-dev libavformat-dev libavutil-dev libavfilter-dev libavdevice-dev libswscale-dev libswresample-dev pkg-config

      - name: Set FFmpeg environment
        if: runner.os != 'Windows'
        run: |
          echo "PKG_CONFIG_PATH=/usr/lib/x86_64-linux-gnu/pkgconfig:/usr/lib/pkgconfig:/usr/share/pkgconfig" >> $GITHUB_ENV

      - name: Install Windows dependencies for Tauri bindings
        if: runner.os == 'Windows'
        shell: pwsh
        run: |
          # Install pkg-config
          choco install pkgconfiglite -y
          
          # Create FFmpeg directory
          New-Item -ItemType Directory -Force -Path C:\ffmpeg
          
          # Download pre-built FFmpeg shared libraries
          $ffmpegUrl = "https://github.com/GyanD/codexffmpeg/releases/download/7.1/ffmpeg-7.1-full_build-shared.7z"
          Write-Host "Downloading FFmpeg from $ffmpegUrl"
          Invoke-WebRequest -Uri $ffmpegUrl -OutFile ffmpeg.7z
          
          # Extract FFmpeg
          Write-Host "Extracting FFmpeg..."
          7z x ffmpeg.7z -oC:\
          $extractedDir = Get-ChildItem -Path C:\ -Directory | Where-Object { $_.Name -like "ffmpeg-*" } | Select-Object -First 1
          Write-Host "Found extracted directory: $($extractedDir.FullName)"
          
          # Copy contents to C:\ffmpeg (use Copy instead of Move for reliability)
          Write-Host "Copying FFmpeg files to C:\ffmpeg..."
          Copy-Item -Path "$($extractedDir.FullName)\*" -Destination C:\ffmpeg -Recurse -Force
          
          # Verify FFmpeg installation
          Write-Host "Verifying FFmpeg installation..."
          $requiredDirs = @("bin", "include", "lib")
          foreach ($dir in $requiredDirs) {
            if (Test-Path "C:\ffmpeg\$dir") {
              Write-Host "✓ Found C:\ffmpeg\$dir"
            } else {
              Write-Error "✗ Missing C:\ffmpeg\$dir"
            }
          }
          
          # List library files
          Write-Host "FFmpeg libraries found:"
          Get-ChildItem -Path "C:\ffmpeg\lib" -Filter "*.lib" | ForEach-Object { Write-Host "  - $($_.Name)" }
          
          # Set environment variables using NO_PKG_CONFIG approach
          Write-Host "Setting environment variables..."
          echo "FFMPEG_DIR=C:\ffmpeg" >> $env:GITHUB_ENV
          echo "FFMPEG_INCLUDE_DIR=C:\ffmpeg\include" >> $env:GITHUB_ENV
          echo "FFMPEG_LIB_DIR=C:\ffmpeg\lib" >> $env:GITHUB_ENV
          echo "FFMPEG_NO_PKG_CONFIG=1" >> $env:GITHUB_ENV
          echo "RUSTFLAGS=-C link-arg=/LIBPATH:C:\ffmpeg\lib" >> $env:GITHUB_ENV
          echo "C:\ffmpeg\bin" >> $env:GITHUB_PATH
          
          # Also set for current shell
          $env:FFMPEG_DIR = "C:\ffmpeg"
          $env:FFMPEG_INCLUDE_DIR = "C:\ffmpeg\include"
          $env:FFMPEG_LIB_DIR = "C:\ffmpeg\lib"
          $env:FFMPEG_NO_PKG_CONFIG = "1"
          $env:RUSTFLAGS = "-C link-arg=/LIBPATH:C:\ffmpeg\lib"
          $env:PATH = "C:\ffmpeg\bin;$env:PATH"

      - name: Setup Rust environment on Windows
        if: runner.os == 'Windows'
        shell: pwsh
        run: |
          Write-Host "Running setup-rust-env-windows.ps1..."
          ./scripts/setup-rust-env-windows.ps1 -FFmpegDir C:\ffmpeg
          
      - name: Create dist directory
        run: mkdir -p dist

      - name: Build Rust dependencies on Unix
        if: runner.os != 'Windows'
        env:
          PKG_CONFIG_PATH: /usr/lib/x86_64-linux-gnu/pkgconfig:/usr/lib/pkgconfig:/usr/share/pkgconfig
        run: |
          cd src-tauri
          cargo build --release

      - name: Generate TypeScript bindings on Unix
        if: runner.os != 'Windows'
        env:
          PKG_CONFIG_PATH: /usr/lib/x86_64-linux-gnu/pkgconfig:/usr/lib/pkgconfig:/usr/share/pkgconfig
        run: |
          cd src-tauri
          cargo run --bin generate_types

      - name: Build Rust dependencies on Windows
        if: runner.os == 'Windows'
        shell: pwsh
        env:
          FFMPEG_DIR: C:\ffmpeg
          FFMPEG_INCLUDE_DIR: C:\ffmpeg\include
          FFMPEG_LIB_DIR: C:\ffmpeg\lib
          FFMPEG_NO_PKG_CONFIG: 1
          RUSTFLAGS: -C link-arg=/LIBPATH:C:\ffmpeg\lib
        run: |
          cd src-tauri
          cargo build --release

      - name: Generate TypeScript bindings on Windows
        if: runner.os == 'Windows'
        shell: pwsh
        env:
          FFMPEG_DIR: C:\ffmpeg
          FFMPEG_INCLUDE_DIR: C:\ffmpeg\include
          FFMPEG_LIB_DIR: C:\ffmpeg\lib
          FFMPEG_NO_PKG_CONFIG: 1
          RUSTFLAGS: -C link-arg=/LIBPATH:C:\ffmpeg\lib
        run: |
          cd src-tauri
          cargo run --bin generate_types

      - name: Run lint step
        env:
          NODE_OPTIONS: '--max-old-space-size=4096'
        run: npm run lint:ci

  check-rust:
    name: Check Rust
    timeout-minutes: 10
    strategy:
      fail-fast: false
      matrix:
        os: [ubuntu-22.04]

    runs-on: ${{ matrix.os }}

    steps:
      - name: Disable git core.autocrlf on Windows
        if: matrix.os == 'windows-latest'
        run: git config --global core.autocrlf false

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

      - name: Install Rust toolchain
        uses: dtolnay/rust-toolchain@stable
        with:
          components: rustfmt, clippy

      - name: Install Linux dependencies
        run: |
          sudo apt-get update
          sudo apt install libwebkit2gtk-4.1-dev build-essential curl wget file libxdo-dev libssl-dev libayatana-appindicator3-dev librsvg2-dev ffmpeg libavcodec-dev libavformat-dev libavutil-dev libavfilter-dev libavdevice-dev libswscale-dev libswresample-dev pkg-config
          
      - name: Setup FFmpeg environment
        run: |
          echo "=== FFmpeg Header Location Fix ==="
          
          # Check if headers are in expected location
          if [ ! -f "/usr/include/libswscale/swscale.h" ]; then
            echo "Headers not found in /usr/include, searching..."
            
            # Find actual location
            SWSCALE_PATHS=$(find /usr -name "swscale.h" 2>/dev/null)
            echo "Found swscale.h at: $SWSCALE_PATHS"
            
            # Find main header location
            MAIN_SWSCALE=$(echo "$SWSCALE_PATHS" | grep "libswscale/swscale.h" | head -1)
            
            if [ -n "$MAIN_SWSCALE" ]; then
              BASE_DIR=$(dirname $(dirname "$MAIN_SWSCALE"))
              echo "Found FFmpeg headers in: $BASE_DIR"
              
              # Create symlinks
              FFMPEG_LIBS=("libavcodec" "libavformat" "libavutil" "libswscale" "libavfilter" "libavdevice" "libswresample")
              for lib in "${FFMPEG_LIBS[@]}"; do
                if [ -d "$BASE_DIR/$lib" ] && [ ! -L "/usr/include/$lib" ]; then
                  sudo ln -sfn "$BASE_DIR/$lib" "/usr/include/$lib"
                  echo "✅ Created symlink: /usr/include/$lib -> $BASE_DIR/$lib"
                fi
              done
            fi
          fi
          
          # Set PKG_CONFIG_PATH
          echo "PKG_CONFIG_PATH=/usr/lib/x86_64-linux-gnu/pkgconfig:/usr/lib/pkgconfig:/usr/share/pkgconfig" >> $GITHUB_ENV

      - name: Create empty 'dist' directory
        run: mkdir dist

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

      - name: Install dependencies from lockfile
        run: |
          npm config set fetch-timeout 300000
          npm config set fetch-retries 5
          # 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: Run rustfmt check
        run: npm run format:rust:check

      - name: Run clippy check and deny warnings
        run: npm run lint:rust

  check-tests:
    name: Run Tests
    timeout-minutes: 30
    strategy:
      fail-fast: false
      matrix:
        os: [ubuntu-22.04]

    runs-on: ${{ matrix.os }}

    steps:
      - name: Disable git core.autocrlf on Windows
        if: matrix.os == 'windows-latest'
        run: git config --global core.autocrlf false

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

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

      - name: Install dependencies
        run: |
          rm -rf node_modules
          npm config set fetch-timeout 300000
          npm config set fetch-retries 5
          # Try to install with retries
          npm install --no-audit --no-fund || \
          npm install --no-audit --no-fund --omit=optional

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

      - name: Install Linux dependencies for Tauri bindings
        run: |
          sudo apt-get update
          sudo apt-get install -y libgtk-3-dev libwebkit2gtk-4.1-dev libglib2.0-dev
          # Install FFmpeg dependencies
          sudo apt-get install -y ffmpeg libavcodec-dev libavformat-dev libavutil-dev libavfilter-dev libavdevice-dev libswscale-dev libswresample-dev pkg-config

      - name: Set FFmpeg environment
        run: |
          echo "PKG_CONFIG_PATH=/usr/lib/x86_64-linux-gnu/pkgconfig:/usr/lib/pkgconfig:/usr/share/pkgconfig" >> $GITHUB_ENV

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

      - name: Build Rust dependencies on Unix
        if: runner.os != 'Windows'
        env:
          PKG_CONFIG_PATH: /usr/lib/x86_64-linux-gnu/pkgconfig:/usr/lib/pkgconfig:/usr/share/pkgconfig
        run: |
          cd src-tauri
          cargo build --release

      - name: Generate TypeScript bindings on Unix
        if: runner.os != 'Windows'
        env:
          PKG_CONFIG_PATH: /usr/lib/x86_64-linux-gnu/pkgconfig:/usr/lib/pkgconfig:/usr/share/pkgconfig
        run: |
          cd src-tauri
          cargo run --bin generate_types

      - name: Build Rust dependencies on Windows
        if: runner.os == 'Windows'
        shell: pwsh
        env:
          FFMPEG_DIR: C:\ffmpeg
          FFMPEG_INCLUDE_DIR: C:\ffmpeg\include
          FFMPEG_LIB_DIR: C:\ffmpeg\lib
          FFMPEG_NO_PKG_CONFIG: 1
          RUSTFLAGS: -C link-arg=/LIBPATH:C:\ffmpeg\lib
        run: |
          cd src-tauri
          cargo build --release

      - name: Generate TypeScript bindings on Windows
        if: runner.os == 'Windows'
        shell: pwsh
        env:
          FFMPEG_DIR: C:\ffmpeg
          FFMPEG_INCLUDE_DIR: C:\ffmpeg\include
          FFMPEG_LIB_DIR: C:\ffmpeg\lib
          FFMPEG_NO_PKG_CONFIG: 1
          RUSTFLAGS: -C link-arg=/LIBPATH:C:\ffmpeg\lib
        run: |
          cd src-tauri
          cargo run --bin generate_types

      - name: Run tests
        run: npm test
