name: Build and Release

on:
  workflow_dispatch:
    inputs:
      version:
        description: 'Version number (e.g., 0.1.0)'
        required: true
        default: ''
      prerelease:
        description: 'Is this a pre-release?'
        required: true
        default: true
        type: boolean

jobs:
  create-release:
    runs-on: ubuntu-latest
    outputs:
      release_id: ${{ fromJSON(steps.create_release.outputs.result).id }}
      upload_url: ${{ fromJSON(steps.create_release.outputs.result).upload_url }}
      version: ${{ github.event.inputs.version }}

    steps:
      - name: Create or Get Release
        id: create_release
        uses: actions/github-script@v6
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}
          script: |
            const tag = `v${{ github.event.inputs.version }}`;
            const releaseName = `Timeline Studio v${{ github.event.inputs.version }}`;
            const releaseBody = `Timeline Studio v${{ github.event.inputs.version }}

            ## Статус сборки

            🔄 Файлы собираются... Ссылки для загрузки появятся после завершения сборки.

            ## Изменения

            - Новые возможности
            - Исправления ошибок
            - Улучшения производительности`;

            try {
              // Попробуем получить существующий релиз
              const existingRelease = await github.rest.repos.getReleaseByTag({
                owner: context.repo.owner,
                repo: context.repo.repo,
                tag: tag
              });

              console.log(`Release ${tag} already exists, using existing release`);
              return existingRelease.data;
            } catch (error) {
              if (error.status === 404) {
                // Релиз не существует, создаем новый
                console.log(`Creating new release ${tag}`);
                const newRelease = await github.rest.repos.createRelease({
                  owner: context.repo.owner,
                  repo: context.repo.repo,
                  tag_name: tag,
                  name: releaseName,
                  body: releaseBody,
                  draft: false,
                  prerelease: ${{ github.event.inputs.prerelease }}
                });

                return newRelease.data;
              } else {
                throw error;
              }
            }

  build-tauri:
    needs: create-release
    timeout-minutes: 120
    strategy:
      fail-fast: false
      matrix:
        platform: [macos-latest, ubuntu-latest, windows-latest]

    runs-on: ${{ matrix.platform }}
    steps:
      - name: Checkout repository
        uses: actions/checkout@v3

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

      - name: Install Rust (stable)
        uses: dtolnay/rust-toolchain@stable

      - name: Cache Rust
        uses: actions/cache@v3
        with:
          path: |
            ~/.cargo/bin/
            ~/.cargo/registry/index/
            ~/.cargo/registry/cache/
            ~/.cargo/git/db/
            src-tauri/target/
          key: ${{ matrix.platform }}-cargo-${{ hashFiles('**/Cargo.lock') }}

      - name: Install dependencies (macOS only)
        if: matrix.platform == 'macos-latest'
        run: |
          # Install dependencies
          brew install ffmpeg pkg-config onnxruntime
          
          # Install x86_64 version of FFmpeg if on ARM Mac
          if [[ "$(uname -m)" == "arm64" ]]; then
            arch -x86_64 /usr/local/bin/brew install ffmpeg || echo "x86_64 FFmpeg might already be installed"
          fi
          
          # Determine architecture
          ARCH=$(uname -m)
          if [[ "$ARCH" == "arm64" ]]; then
            HOMEBREW_PREFIX="/opt/homebrew"
          else
            HOMEBREW_PREFIX="/usr/local"
          fi
          
          # Set PKG_CONFIG_PATH for FFmpeg libraries
          echo "PKG_CONFIG_PATH=${HOMEBREW_PREFIX}/lib/pkgconfig:/usr/local/lib/pkgconfig:/opt/homebrew/lib/pkgconfig" >> $GITHUB_ENV
          
          # Set ONNX Runtime library path
          echo "ORT_DYLIB_PATH=${HOMEBREW_PREFIX}/lib/libonnxruntime.dylib" >> $GITHUB_ENV
          
          # Set pkg-config for cross compilation
          echo "PKG_CONFIG_ALLOW_CROSS=1" >> $GITHUB_ENV
          echo "PKG_CONFIG_SYSROOT_DIR=/" >> $GITHUB_ENV
          
          # For x86_64 target
          echo "PKG_CONFIG_PATH_x86_64_apple_darwin=/usr/local/lib/pkgconfig" >> $GITHUB_ENV
          echo "PKG_CONFIG_SYSROOT_DIR_x86_64_apple_darwin=/" >> $GITHUB_ENV
          
          # For aarch64 target
          echo "PKG_CONFIG_PATH_aarch64_apple_darwin=/opt/homebrew/lib/pkgconfig" >> $GITHUB_ENV
          echo "PKG_CONFIG_SYSROOT_DIR_aarch64_apple_darwin=/" >> $GITHUB_ENV
          
          # Verify FFmpeg installation
          pkg-config --modversion libavutil || echo "libavutil not found"
          pkg-config --modversion libavcodec || echo "libavcodec not found"
          pkg-config --modversion libavformat || echo "libavformat not found"

      - name: Cache ONNX Runtime (Windows only)
        if: matrix.platform == 'windows-latest'
        uses: actions/cache@v3
        with:
          path: C:\onnxruntime
          key: windows-onnxruntime-1.19.2

      - name: Setup MSVC (Windows only)
        if: matrix.platform == 'windows-latest'
        uses: ilammy/msvc-dev-cmd@v1
        with:
          arch: x64

      - name: Install dependencies (Windows only)
        if: matrix.platform == 'windows-latest'
        run: |
          # MSVC is already set up by ilammy/msvc-dev-cmd action
          
          # Install pkg-config for Windows
          choco install pkgconfiglite
          
          # Install vcpkg fresh (no caching to avoid issues)
          echo "Installing vcpkg..."
          git clone https://github.com/Microsoft/vcpkg.git C:\vcpkg
          cd C:\vcpkg
          .\bootstrap-vcpkg.bat
          .\vcpkg integrate install
          
          # Install FFmpeg with development libraries
          echo "Installing FFmpeg..."
          .\vcpkg install ffmpeg:x64-windows
          
          # Set Windows SDK environment variables to include system headers
          echo "Setting up Windows SDK environment..."
          
          # Find the latest Windows SDK version
          $WindowsSDKPath = "${env:ProgramFiles(x86)}\Windows Kits\10"
          if (Test-Path "$WindowsSDKPath\Include") {
            $WindowsSDKVersion = (Get-ChildItem "$WindowsSDKPath\Include" | Where-Object {$_.Name -match '^\d+\.\d+\.\d+\.\d+$'} | Sort-Object Name -Descending | Select-Object -First 1).Name
            echo "Found Windows SDK version: $WindowsSDKVersion"
            
            # Find Visual Studio installation path  
            $VSPath = & "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath
            if (-not $VSPath) {
              $VSPath = "${env:ProgramFiles}\Microsoft Visual Studio\2022\Enterprise"
              if (-not (Test-Path $VSPath)) {
                $VSPath = "${env:ProgramFiles}\Microsoft Visual Studio\2022\Community"
              }
            }
            echo "Visual Studio path: $VSPath"
            
            # Find MSVC version
            $MSVCPath = "$VSPath\VC\Tools\MSVC"
            if (Test-Path $MSVCPath) {
              $MSVCVersion = (Get-ChildItem $MSVCPath | Where-Object {$_.PSIsContainer} | Sort-Object Name -Descending | Select-Object -First 1).Name
              echo "MSVC version: $MSVCVersion"
              $MSVCIncludePath = "$MSVCPath\$MSVCVersion\include"
            } else {
              echo "WARNING: MSVC not found at expected path"
              $MSVCIncludePath = ""
            }
            
            # Set up proper Windows SDK paths (not WDF)
            $IncludePaths = @(
              "$WindowsSDKPath\Include\$WindowsSDKVersion\ucrt",
              "$WindowsSDKPath\Include\$WindowsSDKVersion\shared", 
              "$WindowsSDKPath\Include\$WindowsSDKVersion\um",
              "$WindowsSDKPath\Include\$WindowsSDKVersion\winrt",
              "C:\vcpkg\installed\x64-windows\include"
            )
            
            # Add MSVC include path if found
            if ($MSVCIncludePath -and (Test-Path $MSVCIncludePath)) {
              $IncludePaths = @($MSVCIncludePath) + $IncludePaths
              echo "Added MSVC include path: $MSVCIncludePath"
            }
            
            $LibPaths = @(
              "$WindowsSDKPath\Lib\$WindowsSDKVersion\ucrt\x64",
              "$WindowsSDKPath\Lib\$WindowsSDKVersion\um\x64",
              "C:\vcpkg\installed\x64-windows\lib"
            )
            
            # Add MSVC lib path if found
            if ($MSVCIncludePath) {
              $MSVCLibPath = "$MSVCPath\$MSVCVersion\lib\x64"
              if (Test-Path $MSVCLibPath) {
                $LibPaths = @($MSVCLibPath) + $LibPaths
                echo "Added MSVC lib path: $MSVCLibPath"
              }
            }
            
            echo "INCLUDE=$($IncludePaths -join ';')" >> $env:GITHUB_ENV
            echo "LIB=$($LibPaths -join ';')" >> $env:GITHUB_ENV
            
            # Also set for MSVC compiler
            echo "WindowsSdkDir=$WindowsSDKPath\" >> $env:GITHUB_ENV
            echo "WindowsSDKVersion=$WindowsSDKVersion\" >> $env:GITHUB_ENV
          } else {
            echo "Windows SDK not found, using basic paths"
            echo "INCLUDE=C:\vcpkg\installed\x64-windows\include" >> $env:GITHUB_ENV
            echo "LIB=C:\vcpkg\installed\x64-windows\lib" >> $env:GITHUB_ENV
          }
          
          # Set environment variables for FFmpeg
          echo "VCPKG_ROOT=C:\vcpkg" >> $env:GITHUB_ENV
          echo "PKG_CONFIG_PATH=C:\vcpkg\installed\x64-windows\lib\pkgconfig" >> $env:GITHUB_ENV
          echo "C:\vcpkg\installed\x64-windows\bin" >> $env:GITHUB_PATH
          
          # Add additional paths that ffmpeg-sys-next might look for
          echo "FFMPEG_DIR=C:\vcpkg\installed\x64-windows" >> $env:GITHUB_ENV
          echo "FFMPEG_INCLUDE_DIR=C:\vcpkg\installed\x64-windows\include" >> $env:GITHUB_ENV
          echo "FFMPEG_LIB_DIR=C:\vcpkg\installed\x64-windows\lib" >> $env:GITHUB_ENV
          
          # Set up bindgen to find Windows headers
          # The MSVC action already sets up correct paths, but we need to ensure bindgen uses them
          $bindgenArgs = ""
          
          # Add MSVC include path from environment
          if ($env:INCLUDE) {
            $includePaths = $env:INCLUDE -split ';'
            foreach ($path in $includePaths) {
              if ($path -and (Test-Path $path)) {
                $bindgenArgs += "-I`"$path`" "
              }
            }
          }
          
          # Also explicitly add vcpkg include
          $bindgenArgs += "-I`"C:\vcpkg\installed\x64-windows\include`""
          
          echo "BINDGEN_EXTRA_CLANG_ARGS=$bindgenArgs" >> $env:GITHUB_ENV
          echo "Set BINDGEN_EXTRA_CLANG_ARGS: $bindgenArgs"
          
          # Verify FFmpeg installation
          if (Test-Path "C:\vcpkg\installed\x64-windows\include\libavutil\avutil.h") {
            echo "✅ FFmpeg headers found"
          } else {
            echo "❌ FFmpeg headers not found!"
            if (Test-Path "C:\vcpkg\installed\x64-windows\include") {
              echo "Include directory exists, listing contents:"
              ls "C:\vcpkg\installed\x64-windows\include" | Select -First 20
            } else {
              echo "Include directory does not exist!"
              echo "Checking vcpkg installed directory:"
              if (Test-Path "C:\vcpkg\installed") {
                ls "C:\vcpkg\installed" | Select -First 10
              }
            }
          }
          
          # Check if ONNX Runtime exists from cache
          $ONNX_VERSION = "1.19.2"
          if (-Not (Test-Path "C:\onnxruntime")) {
            # Install ONNX Runtime
            Invoke-WebRequest -Uri "https://github.com/microsoft/onnxruntime/releases/download/v$ONNX_VERSION/onnxruntime-win-x64-$ONNX_VERSION.zip" -OutFile "onnxruntime.zip"
            Expand-Archive -Path "onnxruntime.zip" -DestinationPath "C:\onnxruntime"
          } else {
            echo "Using cached ONNX Runtime installation"
          }
          
          echo "C:\onnxruntime\onnxruntime-win-x64-$ONNX_VERSION\lib" >> $env:GITHUB_PATH
          echo "ORT_DYLIB_PATH=C:\onnxruntime\onnxruntime-win-x64-$ONNX_VERSION\lib\onnxruntime.dll" >> $env:GITHUB_ENV

      - name: Install dependencies (ubuntu only)
        if: matrix.platform == 'ubuntu-latest'
        run: |
          sudo apt-get update
          # Проверяем версию Ubuntu
          UBUNTU_VERSION=$(lsb_release -rs)
          echo "Ubuntu version: $UBUNTU_VERSION"

          if [[ "$UBUNTU_VERSION" == "24.04" ]]; then
            # Ubuntu 24.04 (Noble)
            sudo apt-get install -y build-essential curl libssl-dev libgtk-3-dev libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev patchelf ffmpeg libavcodec-dev libavformat-dev libavutil-dev libavfilter-dev libavdevice-dev libswscale-dev libswresample-dev pkg-config clang libclang-dev
          else
            # Ubuntu 22.04 (Jammy) и более старые versii
            sudo apt-get install -y build-essential curl libssl-dev libgtk-3-dev libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf ffmpeg libavcodec-dev libavformat-dev libavutil-dev libavfilter-dev libavdevice-dev libswscale-dev libswresample-dev pkg-config clang libclang-dev
          fi
          
          # Fix FFmpeg headers location for Ubuntu 24.04
          if [ ! -f "/usr/include/libswscale/swscale.h" ]; then
            echo "Fixing FFmpeg headers location..."
            SWSCALE_PATHS=$(find /usr -name "swscale.h" 2>/dev/null)
            MAIN_SWSCALE=$(echo "$SWSCALE_PATHS" | grep "libswscale/swscale.h" | head -1)
            
            if [ -n "$MAIN_SWSCALE" ]; then
              BASE_DIR=$(dirname $(dirname "$MAIN_SWSCALE"))
              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"
                fi
              done
            fi
          fi
          
          # Install ONNX Runtime for Ubuntu
          ONNX_VERSION="1.19.2"
          wget https://github.com/microsoft/onnxruntime/releases/download/v${ONNX_VERSION}/onnxruntime-linux-x64-${ONNX_VERSION}.tgz
          sudo tar -xzf onnxruntime-linux-x64-${ONNX_VERSION}.tgz -C /opt/
          sudo ln -sf /opt/onnxruntime-linux-x64-${ONNX_VERSION}/lib/libonnxruntime.so.${ONNX_VERSION} /usr/local/lib/libonnxruntime.so
          sudo ldconfig
          
          # Set ONNX Runtime environment variable
          echo "ORT_DYLIB_PATH=/usr/local/lib/libonnxruntime.so" >> $GITHUB_ENV

      - name: Install frontend dependencies
        run: |
          # Configure npm for timeouts
          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: Fix Windows dependencies and lightningcss
        if: matrix.platform == 'windows-latest'
        shell: pwsh
        run: |
          # First, try to install lightningcss directly as a primary dependency
          echo "Installing lightningcss for Windows..."
          npm install lightningcss@^1.30.1 --save-dev
          
          # Force reinstall of lightningcss Windows binary
          npm rebuild lightningcss-win32-x64-msvc --verbose
          
          # Check if lightningcss module exists and has the native binary
          $lightningcssPath = "node_modules/lightningcss"
          $binaryPath = "node_modules/lightningcss-win32-x64-msvc/lightningcss.win32-x64-msvc.node"
          
          if (Test-Path $lightningcssPath) {
            echo "✅ lightningcss module found"
          } else {
            echo "❌ lightningcss module not found, installing manually..."
            npm install lightningcss@^1.30.1 --force
          }
          
          if (Test-Path $binaryPath) {
            echo "✅ Native binary exists at: $binaryPath"
          } else {
            echo "❌ Native binary not found, attempting manual installation..."
            
            # Clean existing installation
            if (Test-Path "node_modules/lightningcss-win32-x64-msvc") {
              Remove-Item -Path "node_modules/lightningcss-win32-x64-msvc" -Recurse -Force
            }
            
            # Download and extract manually
            $version = "1.30.1"
            $url = "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-$version.tgz"
            echo "Downloading from: $url"
            
            try {
              Invoke-WebRequest -Uri $url -OutFile "lightningcss-win32.tgz" -UseBasicParsing
              
              # Create directory and extract
              New-Item -ItemType Directory -Force -Path "node_modules/lightningcss-win32-x64-msvc"
              tar -xzf lightningcss-win32.tgz
              
              # Copy package contents
              if (Test-Path "package") {
                Copy-Item -Path "package/*" -Destination "node_modules/lightningcss-win32-x64-msvc/" -Recurse -Force
                echo "✅ Manual installation completed"
                
                # Verify the binary exists now
                if (Test-Path "node_modules/lightningcss-win32-x64-msvc/lightningcss.win32-x64-msvc.node") {
                  echo "✅ Native binary verified after manual installation"
                } else {
                  echo "❌ Native binary still missing after manual installation"
                  echo "Contents of lightningcss-win32-x64-msvc directory:"
                  Get-ChildItem "node_modules/lightningcss-win32-x64-msvc" -Recurse | Select-Object Name, FullName | Format-Table
                }
              }
              
              # Cleanup
              Remove-Item -Path "package" -Recurse -Force -ErrorAction SilentlyContinue
              Remove-Item -Path "lightningcss-win32.tgz" -ErrorAction SilentlyContinue
              
            } catch {
              echo "❌ Failed to download lightningcss binary: $_"
              echo "Falling back to disabling lightningcss..."
              # Set environment variable to disable lightningcss features
              echo "DISABLE_LIGHTNINGCSS=true" >> $env:GITHUB_ENV
              echo "⚠️  Will continue build without lightningcss optimization"
            }
          }
          
          # Final verification
          echo "`n=== Final lightningcss verification ==="
          if (Test-Path "node_modules/lightningcss") {
            echo "✅ lightningcss module installed"
            $moduleInfo = Get-ChildItem "node_modules/lightningcss" | Select-Object Name | Format-Table -HideTableHeaders
            echo "Module contents: $moduleInfo"
          }
          
          if (Test-Path "node_modules/lightningcss-win32-x64-msvc/lightningcss.win32-x64-msvc.node") {
            echo "✅ Native binary ready for use"
          } else {
            echo "⚠️  Native binary not available, setting fallback environment"
            echo "DISABLE_LIGHTNINGCSS=true" >> $env:GITHUB_ENV
          }

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

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

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

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

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

      - name: Install Tauri CLI (Unix)
        if: runner.os != 'Windows'
        run: |
          # Проверяем, установлен ли уже Tauri CLI
          if ! command -v cargo-tauri &> /dev/null; then
            echo "Installing Tauri CLI..."
            cargo install tauri-cli --version "^2.0.0"
          else
            echo "Tauri CLI already installed"
          fi

          # Проверяем установку
          cargo-tauri --version

      - name: Install Tauri CLI (Windows)
        if: runner.os == 'Windows'
        run: |
          # Check if Tauri CLI is already installed
          $tauriInstalled = $false
          try {
            cargo-tauri --version
            $tauriInstalled = $true
            Write-Host "Tauri CLI already installed"
          } catch {
            Write-Host "Installing Tauri CLI..."
            cargo install tauri-cli --version "^2.0.0"
          }

          # Verify installation
          cargo-tauri --version

      # Skip all tests in release builds to avoid compilation issues
      # Tests are run in separate CI workflows

      # Исправляем имя продукта в tauri.conf.json перед сборкой
      - name: Fix product name (Unix)
        if: runner.os != 'Windows'
        run: |
          # Заменяем пробелы на дефисы в имени продукта
          if [[ "$RUNNER_OS" == "macOS" ]]; then
            # macOS требует указания расширения для опции -i
            sed -i '' 's/"productName": "Timeline Studio"/"productName": "timeline-studio"/g' src-tauri/tauri.conf.json
          else
            # Linux
            sed -i 's/"productName": "Timeline Studio"/"productName": "timeline-studio"/g' src-tauri/tauri.conf.json
          fi

      - name: Fix product name (Windows)
        if: runner.os == 'Windows'
        run: |
          # Заменяем пробелы на дефисы в имени продукта
          (Get-Content src-tauri/tauri.conf.json) -replace '"productName": "Timeline Studio"', '"productName": "timeline-studio"' | Set-Content src-tauri/tauri.conf.json

      - name: Debug FFmpeg installation (Windows)
        if: matrix.platform == 'windows-latest'
        run: |
          echo "=== FFmpeg Installation Debug ==="
          echo "FFMPEG_DIR: $env:FFMPEG_DIR"
          echo "FFMPEG_INCLUDE_DIR: $env:FFMPEG_INCLUDE_DIR"
          echo "FFMPEG_LIB_DIR: $env:FFMPEG_LIB_DIR"
          echo "PKG_CONFIG_PATH: $env:PKG_CONFIG_PATH"
          echo "INCLUDE: $env:INCLUDE"
          echo "LIB: $env:LIB"
          
          echo "`n=== Checking FFmpeg include files ==="
          if (Test-Path "C:\vcpkg\installed\x64-windows\include\libavutil\avutil.h") {
            echo "✅ avutil.h found"
          } else {
            echo "❌ avutil.h NOT found"
          }
          
          echo "`n=== Checking system headers (errno.h) ==="
          # Check for errno.h in Windows SDK
          $WindowsSDKPath = "${env:ProgramFiles(x86)}\Windows Kits\10"
          if (Test-Path $WindowsSDKPath) {
            $WindowsSDKVersion = (Get-ChildItem "$WindowsSDKPath\Include" | Where-Object {$_.Name -match '^\d+\.\d+\.\d+\.\d+$'} | Sort-Object Name -Descending | Select-Object -First 1).Name
            echo "Using Windows SDK version: $WindowsSDKVersion"
            
            $ErrornPath = "$WindowsSDKPath\Include\$WindowsSDKVersion\ucrt\errno.h"
            if (Test-Path $ErrornPath) {
              echo "✅ errno.h found at: $ErrornPath"
            } else {
              echo "❌ errno.h NOT found at expected path: $ErrornPath"
              echo "Available include directories:"
              ls "$WindowsSDKPath\Include\$WindowsSDKVersion" -ErrorAction SilentlyContinue | Select -First 10
              if (Test-Path "$WindowsSDKPath\Include\$WindowsSDKVersion\ucrt") {
                echo "Available ucrt headers:"
                ls "$WindowsSDKPath\Include\$WindowsSDKVersion\ucrt" -ErrorAction SilentlyContinue | Select -First 10
              }
            }
            
            # Check if WDF paths exist (these should NOT be used)
            $WDFPath = "$WindowsSDKPath\Include\wdf"
            if (Test-Path $WDFPath) {
              echo "⚠️ WARNING: WDF headers found at $WDFPath - these should not be used"
            }
          } else {
            echo "❌ Windows SDK not found at: $WindowsSDKPath"
          }
          
          echo "`n=== Checking lib files ==="
          if (Test-Path "C:\vcpkg\installed\x64-windows\lib") {
            ls "C:\vcpkg\installed\x64-windows\lib\*.lib" -ErrorAction SilentlyContinue | Select -First 10
          } else {
            echo "Lib directory does not exist!"
          }
          
          echo "`n=== pkg-config test ==="
          $env:PKG_CONFIG_PATH = "C:\vcpkg\installed\x64-windows\lib\pkgconfig"
          pkg-config --cflags libavutil 2>&1 || echo "pkg-config failed for libavutil"
          pkg-config --libs libavutil 2>&1 || echo "pkg-config failed for libavutil"

      - name: Install macOS targets
        if: matrix.platform == 'macos-latest'
        run: |
          rustup target add aarch64-apple-darwin
          rustup target add x86_64-apple-darwin

      - name: Clean target directory (macOS)
        if: matrix.platform == 'macos-latest'
        run: |
          cd src-tauri
          # Remove any existing test_specta binaries from previous builds
          find target -name "*test_specta*" -type f -delete 2>/dev/null || true
          find target -name "test_specta" -type f -delete 2>/dev/null || true
          # Remove bundle directory to ensure clean bundling
          rm -rf target/release/bundle target/universal-apple-darwin/release/bundle
          cd ..

      - name: Remove development binaries before build (macOS)
        if: matrix.platform == 'macos-latest'
        run: |
          cd src-tauri
          # Remove development-only binaries that shouldn't be bundled
          rm -f target/universal-apple-darwin/release/generate_types
          rm -f target/universal-apple-darwin/release/export_types
          rm -f target/x86_64-apple-darwin/release/generate_types
          rm -f target/x86_64-apple-darwin/release/export_types
          rm -f target/aarch64-apple-darwin/release/generate_types
          rm -f target/aarch64-apple-darwin/release/export_types
          cd ..

      - name: Build the app (macOS universal)
        if: matrix.platform == 'macos-latest'
        uses: tauri-apps/tauri-action@v0.5.0
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          PKG_CONFIG_PATH: /opt/homebrew/lib/pkgconfig:/usr/local/lib/pkgconfig
          ORT_DYLIB_PATH: /opt/homebrew/lib/libonnxruntime.dylib
          PKG_CONFIG_ALLOW_CROSS: 1
          PKG_CONFIG_SYSROOT_DIR: /
          PKG_CONFIG_PATH_x86_64_apple_darwin: /usr/local/lib/pkgconfig
          PKG_CONFIG_SYSROOT_DIR_x86_64_apple_darwin: /
          PKG_CONFIG_PATH_aarch64_apple_darwin: /opt/homebrew/lib/pkgconfig
          PKG_CONFIG_SYSROOT_DIR_aarch64_apple_darwin: /
          # FFmpeg paths for both architectures
          FFMPEG_DIR: /opt/homebrew/opt/ffmpeg
          FFMPEG_INCLUDE_DIR: /opt/homebrew/opt/ffmpeg/include
          FFMPEG_LIB_DIR: /opt/homebrew/opt/ffmpeg/lib
          # Additional FFmpeg paths for x86_64
          FFMPEG_DIR_x86_64_apple_darwin: /usr/local/opt/ffmpeg
          FFMPEG_INCLUDE_DIR_x86_64_apple_darwin: /usr/local/opt/ffmpeg/include
          FFMPEG_LIB_DIR_x86_64_apple_darwin: /usr/local/opt/ffmpeg/lib
          # Additional FFmpeg paths for aarch64
          FFMPEG_DIR_aarch64_apple_darwin: /opt/homebrew/opt/ffmpeg
          FFMPEG_INCLUDE_DIR_aarch64_apple_darwin: /opt/homebrew/opt/ffmpeg/include
          FFMPEG_LIB_DIR_aarch64_apple_darwin: /opt/homebrew/opt/ffmpeg/lib
          RUST_BACKTRACE: 1
          CARGO_PROFILE_RELEASE_BUILD_OVERRIDE_DEBUG: false
        with:
          releaseId: ${{ needs.create-release.outputs.release_id }}
          tagName: v${{ needs.create-release.outputs.version }}
          releaseName: "Timeline Studio v${{ needs.create-release.outputs.version }}"
          releaseBody: "See the assets to download this version and install."
          releaseDraft: false
          prerelease: ${{ github.event.inputs.prerelease }}
          args: --target universal-apple-darwin --ci
          includeDebug: false
          includeRelease: true
          includeUpdaterJson: true
          tauriScript: "cargo-tauri"

      - name: Build the app (Windows)
        if: matrix.platform == 'windows-latest'
        uses: tauri-apps/tauri-action@v0.5.0
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          VCPKG_ROOT: C:\vcpkg
          PKG_CONFIG_PATH: C:\vcpkg\installed\x64-windows\lib\pkgconfig
          FFMPEG_DIR: C:\vcpkg\installed\x64-windows
          FFMPEG_INCLUDE_DIR: C:\vcpkg\installed\x64-windows\include
          FFMPEG_LIB_DIR: C:\vcpkg\installed\x64-windows\lib
          ORT_DYLIB_PATH: C:\onnxruntime\onnxruntime-win-x64-1.19.2\lib\onnxruntime.dll
          RUST_BACKTRACE: 1
          CARGO_PROFILE_RELEASE_BUILD_OVERRIDE_DEBUG: false
          # Disable CSS minification to avoid lightningcss issues
          NODE_ENV: development
          # Conditionally disable lightningcss if binary is not available
          DISABLE_LIGHTNINGCSS: ${{ env.DISABLE_LIGHTNINGCSS }}
          # Windows SDK and system headers paths (required for errno.h and other system headers)
          # Note: These paths are set dynamically in the dependencies step above
        with:
          releaseId: ${{ needs.create-release.outputs.release_id }}
          tagName: v${{ needs.create-release.outputs.version }}
          releaseName: "Timeline Studio v${{ needs.create-release.outputs.version }}"
          releaseBody: "See the assets to download this version and install."
          releaseDraft: false
          prerelease: ${{ github.event.inputs.prerelease }}
          includeDebug: false
          includeRelease: true
          includeUpdaterJson: true
          tauriScript: "cargo-tauri"
          args: --ci

      - name: Build the app (Linux)
        if: matrix.platform == 'ubuntu-latest'
        uses: tauri-apps/tauri-action@v0.5.0
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          RUST_BACKTRACE: 1
          CARGO_PROFILE_RELEASE_BUILD_OVERRIDE_DEBUG: false
        with:
          releaseId: ${{ needs.create-release.outputs.release_id }}
          tagName: v${{ needs.create-release.outputs.version }}
          releaseName: "Timeline Studio v${{ needs.create-release.outputs.version }}"
          releaseBody: "See the assets to download this version and install."
          releaseDraft: false
          prerelease: ${{ github.event.inputs.prerelease }}
          includeDebug: false
          includeRelease: true
          includeUpdaterJson: true
          tauriScript: "cargo-tauri"
          args: --ci

  update-release-description:
    needs: [create-release, build-tauri]
    runs-on: ubuntu-latest
    steps:
      - name: Update Release Description
        uses: actions/github-script@v6
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}
          script: |
            const tag = `v${{ needs.create-release.outputs.version }}`;
            const releaseBody = `Timeline Studio v${{ needs.create-release.outputs.version }}

            ## Загрузки

            - [Windows (x64)](https://github.com/chatman-media/timeline-studio/releases/download/v${{ needs.create-release.outputs.version }}/timeline-studio-${{ needs.create-release.outputs.version }}-windows-x64.msi)
            - [macOS (Intel)](https://github.com/chatman-media/timeline-studio/releases/download/v${{ needs.create-release.outputs.version }}/timeline-studio-${{ needs.create-release.outputs.version }}-macos-x64.dmg)
            - [macOS (Apple Silicon)](https://github.com/chatman-media/timeline-studio/releases/download/v${{ needs.create-release.outputs.version }}/timeline-studio-${{ needs.create-release.outputs.version }}-macos-aarch64.dmg)
            - [Linux (AppImage)](https://github.com/chatman-media/timeline-studio/releases/download/v${{ needs.create-release.outputs.version }}/timeline-studio-${{ needs.create-release.outputs.version }}-linux-x86_64.AppImage)
            - [Linux (Debian/Ubuntu)](https://github.com/chatman-media/timeline-studio/releases/download/v${{ needs.create-release.outputs.version }}/timeline-studio-${{ needs.create-release.outputs.version }}-linux-amd64.deb)

            ## Изменения

            - Новые возможности
            - Исправления ошибок
            - Улучшения производительности`;

            await github.rest.repos.updateRelease({
              owner: context.repo.owner,
              repo: context.repo.repo,
              release_id: ${{ needs.create-release.outputs.release_id }},
              body: releaseBody
            });

  update-promo-page:
    needs: [create-release, build-tauri, update-release-description]
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v3

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

      - name: Install dependencies
        run: |
          cd promo
          npm install

      - name: Show version for debugging
        run: |
          VERSION="${{ needs.create-release.outputs.version }}"
          echo "Building promo page for version ${VERSION}"

      - name: Build promo page
        run: |
          cd promo
          npm run build

      - name: Deploy to GitHub Pages
        uses: JamesIves/github-pages-deploy-action@v4
        with:
          folder: promo/dist
          branch: gh-pages
          clean: false
          token: ${{ secrets.GITHUB_TOKEN }}
