name: Build Windows Installer

on:
  push:
    tags: ['v*']
  workflow_dispatch:

permissions:
  contents: write

jobs:
  build:
    name: Windows Installer (Inno Setup)
    runs-on: windows-latest

    steps:
      - uses: actions/checkout@v4

      - name: Set up Python 3.12
        uses: actions/setup-python@v5
        with:
          python-version: "3.12"

      - name: Install build tools
        run: pip install hatchling hatch

      - name: Set up Flutter
        uses: subosito/flutter-action@v2
        with:
          channel: stable

      - name: Build Flutter Web UI
        run: |
          cd flutter_app
          flutter pub get
          flutter build web --release

      - name: Install Inno Setup
        run: choco install innosetup -y --no-progress

      - name: Build installer
        run: python installer/build_installer.py
        env:
          ISCC_PATH: "C:\\Program Files (x86)\\Inno Setup 6\\ISCC.exe"

      - name: Find installer EXE
        id: find_exe
        run: |
          $exe = Get-ChildItem installer/dist/*.exe -ErrorAction SilentlyContinue | Select-Object -First 1
          if ($exe) {
            echo "exe_path=$($exe.FullName)" >> $env:GITHUB_OUTPUT
            echo "exe_name=$($exe.Name)" >> $env:GITHUB_OUTPUT
            echo "found=true" >> $env:GITHUB_OUTPUT
          } else {
            echo "found=false" >> $env:GITHUB_OUTPUT
          }
        shell: pwsh

      - name: Upload to Release (tag push)
        if: steps.find_exe.outputs.found == 'true' && startsWith(github.ref, 'refs/tags/')
        uses: softprops/action-gh-release@v2
        with:
          files: ${{ steps.find_exe.outputs.exe_path }}
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Upload to latest Release (manual dispatch)
        if: steps.find_exe.outputs.found == 'true' && github.event_name == 'workflow_dispatch'
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          $tag = gh release list --limit 1 --json tagName -q '.[0].tagName'
          gh release delete-asset $tag ${{ steps.find_exe.outputs.exe_name }} --yes 2>$null
          gh release upload $tag ${{ steps.find_exe.outputs.exe_path }} --clobber
        shell: pwsh
