name: Build and Upload Release (Windows EXE from Ubuntu)

on:
  release:
    types: [published]
  workflow_dispatch: {}

jobs:
  build-windows-exe:
    name: Build Windows EXE (PyInstaller via Docker on Ubuntu)
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Build EXE with PyInstaller (Windows target via Docker)
        run: |
          docker run --rm -v "$PWD":/src cdrx/pyinstaller-windows:python3 \
            "/bin/sh -lc 'set -e
            if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
            pyinstaller --noconfirm --onefile --windowed sealoader_gui.py --name SeaLoader --add-data \"SeaLoader.png;.\" --icon SeaLoader.ico'"

      - name: Prepare artifact
        run: |
          mkdir -p dist_upload
          if [ -f dist/windows/SeaLoader.exe ]; then
            cp dist/windows/SeaLoader.exe dist_upload/SeaLoader.exe
          elif [ -f dist/SeaLoader.exe ]; then
            cp dist/SeaLoader.exe dist_upload/SeaLoader.exe
          else
            echo "SeaLoader.exe not found" && ls -R dist || true && exit 1
          fi
          [ -f README.md ] && cp README.md dist_upload/ || true
          [ -f LICENSE ] && cp LICENSE dist_upload/ || true
          zip -r9 SeaLoader_Windows_x64.zip dist_upload

      - name: Upload asset to Release
        if: ${{ github.event_name == 'release' && github.event.action == 'published' }}
        env:
          TOKEN: ${{ secrets.GITHUB_TOKEN }}
          REPO: ${{ github.repository }}
          RELEASE_ID: ${{ github.event.release.id }}
          SERVER_URL: ${{ github.server_url }}
        run: |
          set -e
          UPLOAD_URL="$SERVER_URL/api/v1/repos/$REPO/releases/$RELEASE_ID/assets?name=SeaLoader_Windows_x64.zip"
          echo "Uploading asset to $UPLOAD_URL"
          curl -fSL -X POST -H "Authorization: token $TOKEN" -H "Content-Type: application/zip" \
            --data-binary @SeaLoader_Windows_x64.zip "$UPLOAD_URL"

      - name: Upload artifact (CI logs)
        uses: actions/upload-artifact@v4
        with:
          name: SeaLoader_Windows_x64
          path: |
            SeaLoader_Windows_x64.zip
            dist/windows/SeaLoader.exe

