name: Windows Build

on:
  push:
    branches:
      - master
  pull_request:
    branches:
      - master

jobs:
  windows_build:
    runs-on: windows-2022

    permissions:
      contents: read
      id-token: write
      attestations: write
      artifact-metadata: write

    strategy:
      matrix:
        platform: [x64]
        arch: [x64]
      fail-fast: false

    steps:
      - uses: actions/checkout@v5

      - uses: actions/setup-python@v6
        with:
          python-version: '3.14.3'
          architecture: ${{ matrix.arch }}

      - name: Install Dependencies
        run: |
          New-Item -Name "deps" -ItemType "Directory" -Force | Out-Null

          python -m pip install --upgrade pip
          python -m pip install cffi
          python -m pip install zstandard

          $ProgressPreference = 'SilentlyContinue'
          function Download-WithRetry {
            param(
              [string]$Url,
              [string]$OutFile,
              [int]$MaxAttempts = 5,
              [int]$InitialDelaySeconds = 2
            )
            for ($attempt = 1; $attempt -le $MaxAttempts; $attempt++) {
              try {
                Invoke-WebRequest -Uri $Url -OutFile $OutFile -ErrorAction Stop
                return
              }
              catch {
                if ($attempt -eq $MaxAttempts) {
                  throw
                }
                Start-Sleep -Seconds ($InitialDelaySeconds * [math]::Pow(2, $attempt - 1))
              }
            }
          }

          Download-WithRetry -Url https://github.com/jrsoftware/issrc/releases/download/is-6_7_1/innosetup-6.7.1.exe -OutFile deps\innosetup-unicode.exe
          & deps\innosetup-unicode.exe /VERYSILENT | Out-Null

          Download-WithRetry -Url https://github.com/ZoiteChat/gvsbuild/releases/download/zoitechat-2.18.1/GTK3_Gvsbuild_zoitechat-2.18.1_x64.zip -OutFile deps\gtk-${{ matrix.arch }}.zip
          Expand-Archive -LiteralPath deps\gtk-${{ matrix.arch }}.zip -DestinationPath C:\gtk-build\gtk\x64\release -Force

          Download-WithRetry -Url https://repo.msys2.org/mingw/x86_64/mingw-w64-x86_64-hicolor-icon-theme-0.18-1-any.pkg.tar.zst -OutFile deps\hicolor-icon-theme.pkg.tar.zst
          python -c "import tarfile,zstandard,pathlib;archive=pathlib.Path(r'deps\\hicolor-icon-theme.pkg.tar.zst');target=pathlib.Path(r'C:\\gtk-build\\gtk\\x64\\release');dctx=zstandard.ZstdDecompressor();f=archive.open('rb');reader=dctx.stream_reader(f);tf=tarfile.open(fileobj=reader,mode='r|');[tf.extract(m,path=target) for m in tf if m.name.startswith('mingw64/share/icons/hicolor/')];tf.close();reader.close();f.close()"

          Download-WithRetry -Url https://repo.msys2.org/mingw/x86_64/mingw-w64-x86_64-libarchive-3.8.6-1-any.pkg.tar.zst -OutFile deps\libarchive.pkg.tar.zst
          python -c "import tarfile,zstandard,pathlib;archive=pathlib.Path(r'deps\\libarchive.pkg.tar.zst');target=pathlib.Path(r'C:\\gtk-build\\gtk\\x64\\release');dctx=zstandard.ZstdDecompressor();f=archive.open('rb');reader=dctx.stream_reader(f);tf=tarfile.open(fileobj=reader,mode='r|');[tf.extract(m,path=target) for m in tf if m.name.startswith(('mingw64/include/archive','mingw64/lib/libarchive','mingw64/bin/libarchive'))];tf.close();reader.close();f.close()"

          if (Test-Path C:\gtk-build\gtk\x64\release\mingw64\share\icons\hicolor) {
            New-Item -Path C:\gtk-build\gtk\x64\release\share\icons -ItemType Directory -Force | Out-Null
            Copy-Item -Path C:\gtk-build\gtk\x64\release\mingw64\share\icons\hicolor -Destination C:\gtk-build\gtk\x64\release\share\icons\hicolor -Recurse -Force
          }
          if (Test-Path C:\gtk-build\gtk\x64\release\mingw64\include) {
            New-Item -Path C:\gtk-build\gtk\x64\release\include -ItemType Directory -Force | Out-Null
            Copy-Item -Path C:\gtk-build\gtk\x64\release\mingw64\include\archive* -Destination C:\gtk-build\gtk\x64\release\include -Recurse -Force
          }
          if (Test-Path C:\gtk-build\gtk\x64\release\mingw64\lib) {
            New-Item -Path C:\gtk-build\gtk\x64\release\lib -ItemType Directory -Force | Out-Null
            Copy-Item -Path C:\gtk-build\gtk\x64\release\mingw64\lib\libarchive* -Destination C:\gtk-build\gtk\x64\release\lib -Force
          }
          if (Test-Path C:\gtk-build\gtk\x64\release\mingw64\bin) {
            New-Item -Path C:\gtk-build\gtk\x64\release\bin -ItemType Directory -Force | Out-Null
            Copy-Item -Path C:\gtk-build\gtk\x64\release\mingw64\bin\libarchive*.dll -Destination C:\gtk-build\gtk\x64\release\bin -Force
          }
          if (Test-Path C:\gtk-build\gtk\x64\release\mingw64) {
            Remove-Item -Path C:\gtk-build\gtk\x64\release\mingw64 -Recurse -Force
          }

          Download-WithRetry -Url https://github.com/ZoiteChat/gvsbuild/releases/download/zoitechat-2.18.0-pre4/gendef20260315.7z -OutFile deps\gendef.7z
          & 7z.exe x deps\gendef.7z -oC:\gtk-build

          Download-WithRetry -Url https://github.com/ZoiteChat/gvsbuild/releases/download/zoitechat-2.18.0-pre4/WinSparkle-20260315.7z -OutFile deps\WinSparkle.7z
          & 7z.exe x deps\WinSparkle.7z -oC:\gtk-build\WinSparkle

          Download-WithRetry -Url https://github.com/ZoiteChat/gvsbuild/releases/download/zoitechat-2.18.0-pre4/perl-5.42.0.1-${{ matrix.arch }}.7z -OutFile deps\perl-${{ matrix.arch }}.7z
          & 7z.exe x deps\perl-${{ matrix.arch }}.7z -oC:\gtk-build\perl-5.42.0.1\${{ matrix.platform }}

          $pyRoot = $env:pythonLocation
          if (-not $pyRoot) { $pyRoot = & python -c "import sys; print(sys.prefix)" }

          foreach ($pyDir in @("C:\gtk-build\python-3.14.3", "C:\gtk-build\python-3.14")) {
            New-Item -Path $pyDir -ItemType Directory -Force | Out-Null
            $target = Join-Path $pyDir "${{ matrix.platform }}"
            if (Test-Path $target) { Remove-Item $target -Recurse -Force }
            New-Item -Path $pyDir -Name "${{ matrix.platform }}" -ItemType Junction -Value $pyRoot | Out-Null
          }

      - uses: actions/setup-python@v6
        with:
          python-version: '3.8.10'
          architecture: ${{ matrix.arch }}

      - name: Prepare Python 3.8
        run: |
          python -m pip install --upgrade pip
          python -m pip install cffi

          $pyRoot = $env:pythonLocation
          if (-not $pyRoot) { $pyRoot = & python -c "import sys; print(sys.prefix)" }

          foreach ($pyDir in @("C:\gtk-build\python-3.8.10", "C:\gtk-build\python-3.8")) {
            New-Item -Path $pyDir -ItemType Directory -Force | Out-Null
            $target = Join-Path $pyDir "${{ matrix.platform }}"
            if (Test-Path $target) { Remove-Item $target -Recurse -Force }
            New-Item -Path $pyDir -Name "${{ matrix.platform }}" -ItemType Junction -Value $pyRoot | Out-Null
          }

      - name: Build
        run: |
          call "C:\Program Files\Microsoft Visual Studio\2022\Enterprise\Common7\Tools\VsDevCmd.bat"

          set "PYTHON_DIR=C:\gtk-build\python-3.14.3\${{ matrix.platform }}"
          if not exist "%PYTHON_DIR%\libs\python314.lib" (
            echo Missing %PYTHON_DIR%\libs\python314.lib
            dir "%PYTHON_DIR%\libs"
            exit /b 1
          )

          set "PYTHON38_DIR=C:\gtk-build\python-3.8\${{ matrix.platform }}"
          if not exist "%PYTHON38_DIR%\libs\python38.lib" (
            echo Missing %PYTHON38_DIR%\libs\python38.lib
            dir "%PYTHON38_DIR%\libs"
            exit /b 1
          )
          if not exist "%PYTHON38_DIR%\Lib\site-packages\_cffi_backend.cp38*.pyd" (
            echo Missing %PYTHON38_DIR%\Lib\site-packages\_cffi_backend.cp38*.pyd
            exit /b 1
          )

          set "LIB=%PYTHON_DIR%\libs;%LIB%"
          set "INCLUDE=%PYTHON_DIR%\include;%INCLUDE%"

          powershell -NoProfile -ExecutionPolicy Bypass -Command "$archiveLib='C:\gtk-build\gtk\x64\release\lib\libarchive.lib'; if (-not (Test-Path $archiveLib)) { $archiveDll = Get-ChildItem 'C:\gtk-build\gtk\x64\release\bin\libarchive*.dll' | Select-Object -First 1; if ($archiveDll) { Push-Location 'C:\gtk-build\gtk\x64\release\lib'; & 'C:\gtk-build\gendef\gendef.exe' $archiveDll.FullName | Out-Null; $archiveDef = Get-ChildItem 'libarchive*.def' | Select-Object -First 1; if ($archiveDef) { & lib /def:$archiveDef.Name /machine:${{ matrix.platform }} /out:libarchive.lib | Out-Null }; Pop-Location } }"

          msbuild win32\zoitechat.sln /m /verbosity:minimal /p:Configuration=Release /p:Platform=${{ matrix.platform }}
          if errorlevel 1 exit /b 1

          if not exist "..\zoitechat-build\${{ matrix.platform }}\rel\plugins\hcpython38.dll" (
            echo hcpython38.dll was not built
            exit /b 1
          )
          if not exist "..\zoitechat-build\${{ matrix.platform }}\rel\_cffi_backend.cp38*.pyd" (
            echo _cffi_backend for Python 3.8 was not staged for the installer
            exit /b 1
          )
        shell: cmd

      - name: Preparing Artifacts
        run: |
          move ..\zoitechat-build\${{ matrix.platform }}\ZoiteChat-*.exe .\
          move ..\zoitechat-build .\
        shell: cmd

      - name: Upload Installer
        id: upload_installer
        uses: actions/upload-artifact@v6
        with:
          name: Installer ${{ matrix.arch }}
          path: ZoiteChat-*.exe

      - name: Attest Installer (Artifact Attestation)
        if: ${{ github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository }}
        uses: actions/attest-build-provenance@v3
        with:
          subject-name: Installer ${{ matrix.arch }}
          subject-digest: sha256:${{ steps.upload_installer.outputs.artifact-digest }}

      - name: Upload Build Files
        id: upload_buildfiles
        uses: actions/upload-artifact@v6
        with:
          name: Build Files ${{ matrix.arch }}
          path: zoitechat-build

      - name: Attest Build Files (Artifact Attestation)
        if: ${{ github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository }}
        uses: actions/attest-build-provenance@v3
        with:
          subject-name: Build Files ${{ matrix.arch }}
          subject-digest: sha256:${{ steps.upload_buildfiles.outputs.artifact-digest }}
