name: Build Windows

on:
  push:
  pull_request:

jobs:

  build-windows:

    runs-on: windows-2025

    steps:

    - name: Git Checkout
      uses: actions/checkout@v4
      with:
        submodules: recursive

    - name: Setup MSVC
      uses: ilammy/msvc-dev-cmd@v1
      with:
        arch: x86

    - name: Copy project files from scripts
      run: |
        copy .github\scripts\abcspace.sln .
        copy .github\scripts\abcexe.vcxproj .

    - name: Generate abclib.vcxproj from dsp
      shell: powershell
      run: |
        # Parse source files from abclib.dsp
        $dspContent = Get-Content "abclib.dsp" -Raw
        $sourceFiles = [regex]::Matches($dspContent, 'SOURCE=\.\\([^\r\n]+)') | ForEach-Object { $_.Groups[1].Value } | Sort-Object -Unique
        
        Write-Host "Found $($sourceFiles.Count) source files"
        
        # Build source file items
        $sourceItems = ""
        foreach ($src in $sourceFiles) {
            if ($src -match '\.c$') {
                $sourceItems += "    <ClCompile Include=`"$src`" />`r`n"
            } elseif ($src -match '\.(cpp|cc)$') {
                $sourceItems += "    <ClCompile Include=`"$src`" />`r`n"
            } elseif ($src -match '\.h$') {
                $sourceItems += "    <ClInclude Include=`"$src`" />`r`n"
            }
        }
        
        # Read template and replace placeholder
        $template = Get-Content ".github\scripts\abclib.vcxproj.template" -Raw
        $vcxproj = $template -replace '\{\{SOURCE_FILES\}\}', $sourceItems
        Set-Content "abclib.vcxproj" $vcxproj -NoNewline
        
        Write-Host "abclib.vcxproj generated successfully"

    - name: Build
      run: |
        msbuild abcspace.sln /m /nologo /v:m /p:Configuration=Release /p:Platform=Win32 /p:UseMultiToolTask=true
        if ($LASTEXITCODE -ne 0) { throw "Build failed with exit code $LASTEXITCODE" }

    - name: Test Executable
      run: |
        copy lib\x86\pthreadVC2.dll _TEST\
        .\_TEST\abc.exe -c "r i10.aig; b; ps; b; rw -l; rw -lz; b; rw -lz; b; ps; cec"
        if ($LASTEXITCODE -ne 0) { throw "Test failed with exit code $LASTEXITCODE" }

    - name: Stage Executable
      run: |
        mkdir staging
        copy _TEST\abc.exe staging\

    - name: Upload package artifact
      uses: actions/upload-artifact@v4
      with:
        name: package-windows
        path: staging/