name: 'Build and Release'

on:
  workflow_dispatch:
    inputs:
      version:
        description: 'Version to release (e.g., v1.0.0). Leave empty for auto-version based on conventional commits.'
        required: false
        type: string
      skip_version_check:
        description: 'Skip automatic version detection and use manual version'
        required: false
        type: boolean
        default: false

permissions: write-all
env:
  CARGO_INCREMENTAL: 0
  RUST_BACKTRACE: short
  TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}
  TAURI_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}
  # macOS signing and notarization
  APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
  APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
  APPLE_ID: ${{ secrets.APPLE_ID }}
  APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }}
  APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
  APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
  PERSONAL_GITHUB_TOKEN: ${{ secrets.PERSONAL_GITHUB_TOKEN }}
concurrency:
  group: "${{ github.workflow }} - ${{ github.head_ref || github.ref }}"
  cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}

jobs:
  check-commits:
    name: Check Commits and Determine Version
    runs-on: ubuntu-latest
    if: github.event_name == 'workflow_dispatch' && (inputs.version == '' || inputs.skip_version_check == false)
    outputs:
      should-release: ${{ steps.check.outputs.should-release }}
      version-type: ${{ steps.check.outputs.version-type }}
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Check for conventional commits
        id: check
        run: |
          # Get commits since last tag
          LAST_TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo "")
          
          if [ -z "$LAST_TAG" ]; then
            echo "No previous tag found, will create initial release"
            echo "should-release=true" >> $GITHUB_OUTPUT
            echo "version-type=minor" >> $GITHUB_OUTPUT
            exit 0
          fi
          
          COMMITS=$(git log $LAST_TAG..HEAD --oneline)
          
          if echo "$COMMITS" | grep -qE "^[a-f0-9]+ (feat|fix|BREAKING CHANGE)"; then
            echo "Found commits that warrant a release"
            echo "should-release=true" >> $GITHUB_OUTPUT
            
            # Determine version bump type
            if echo "$COMMITS" | grep -q "BREAKING CHANGE"; then
              echo "version-type=major" >> $GITHUB_OUTPUT
            elif echo "$COMMITS" | grep -q "feat"; then
              echo "version-type=minor" >> $GITHUB_OUTPUT
            else
              echo "version-type=patch" >> $GITHUB_OUTPUT
            fi
          else
            echo "No commits found that warrant a release"
            echo "should-release=false" >> $GITHUB_OUTPUT
          fi

  auto-version:
    name: Calculate and Update Version
    needs: check-commits
    runs-on: ubuntu-latest
    if: |
      always() && 
      (needs.check-commits.result == 'skipped' || 
       (needs.check-commits.result == 'success' && needs.check-commits.outputs.should-release == 'true'))
    outputs:
      version: ${{ steps.version.outputs.version }}
      tag: ${{ steps.version.outputs.tag }}
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          token: ${{ secrets.GITHUB_TOKEN }}

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 'lts/*'

      - name: Calculate new version
        id: version
        run: |
          # If manual version is provided, use it
          if [ "${{ github.event_name }}" = "workflow_dispatch" ] && [ -n "${{ inputs.version }}" ]; then
            MANUAL_VERSION="${{ inputs.version }}"
            # Remove 'v' prefix if present
            NEW_VERSION="${MANUAL_VERSION#v}"
            echo "Using manual version: $NEW_VERSION"
            echo "version=$NEW_VERSION" >> $GITHUB_OUTPUT
            echo "tag=v$NEW_VERSION" >> $GITHUB_OUTPUT
            exit 0
          fi

          # If triggered by workflow_call, use the provided version
          if [ "${{ github.event_name }}" = "workflow_call" ]; then
            CALL_VERSION="${{ inputs.version }}"
            NEW_VERSION="${CALL_VERSION#v}"
            echo "Using workflow_call version: $NEW_VERSION"
            echo "version=$NEW_VERSION" >> $GITHUB_OUTPUT
            echo "tag=v$NEW_VERSION" >> $GITHUB_OUTPUT
            exit 0
          fi

          # Auto-calculate version based on commits
          CURRENT_VERSION=$(node -p "require('./package.json').version")
          echo "Current version: $CURRENT_VERSION"
          
          # Parse version
          IFS='.' read -ra VERSION_PARTS <<< "$CURRENT_VERSION"
          MAJOR=${VERSION_PARTS[0]}
          MINOR=${VERSION_PARTS[1]}
          PATCH=${VERSION_PARTS[2]}
          
          # Bump version based on commit type
          case "${{ needs.check-commits.outputs.version-type }}" in
            major)
              MAJOR=$((MAJOR + 1))
              MINOR=0
              PATCH=0
              ;;
            minor)
              MINOR=$((MINOR + 1))
              PATCH=0
              ;;
            patch)
              PATCH=$((PATCH + 1))
              ;;
          esac
          
          NEW_VERSION="$MAJOR.$MINOR.$PATCH"
          echo "New version: $NEW_VERSION"
          echo "version=$NEW_VERSION" >> $GITHUB_OUTPUT
          echo "tag=v$NEW_VERSION" >> $GITHUB_OUTPUT

      - name: Update version in files
        if: github.event_name == 'workflow_dispatch' && inputs.version == ''
        run: |
          # Update package.json
          yarn version --new-version ${{ steps.version.outputs.version }} --no-git-tag-version
          
          # Update Cargo.toml
          sed -i 's/^version = "[^"]*"/version = "${{ steps.version.outputs.version }}"/' src-tauri/Cargo.toml
          
          # Update tauri.conf.json
          sed -i 's/"version": "[^"]*"/"version": "${{ steps.version.outputs.version }}"/' src-tauri/tauri.conf.json

      - name: Commit version bump
        if: github.event_name == 'workflow_dispatch' && inputs.version == ''
        run: |
          git config --local user.email "action@github.com"
          git config --local user.name "GitHub Action"
          git add package.json src-tauri/Cargo.toml src-tauri/tauri.conf.json
          git commit -m "chore: bump version to ${{ steps.version.outputs.version }} [skip ci]"
          git push

      - name: Create and push tag
        if: github.event_name == 'workflow_dispatch' && inputs.version == ''
        run: |
          git tag ${{ steps.version.outputs.tag }}
          git push origin ${{ steps.version.outputs.tag }}

  check_tag_version:
    name: Check Tag and All Version Files Consistency
    needs: auto-version
    runs-on: ubuntu-latest
    if: github.event_name != 'workflow_dispatch' || inputs.version != ''
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Ensure jq and grep are installed
        run: sudo apt-get update && sudo apt-get install -y jq

      - name: Validate tag matches versions in package.json, Cargo.toml, tauri.conf.json
        run: |
          # Get the tag to validate
          if [ "${{ github.event_name }}" = "workflow_dispatch" ] && [ -n "${{ inputs.version }}" ]; then
            TAG_REF="${{ inputs.version }}"
          elif [ "${{ github.event_name }}" = "workflow_call" ]; then
            TAG_REF="${{ inputs.version }}"
          else
            TAG_REF="${GITHUB_REF##*/}"   # e.g., v1.2.3
          fi
          
          TAG_VERSION="${TAG_REF#v}"    # Remove "v" prefix for direct comparison

          echo "Tag to validate: $TAG_REF"

          # Get version from package.json
          PKG_VERSION=$(jq -r .version package.json)
          echo "package.json version: $PKG_VERSION"

          # Get version from tauri.conf.json
          TAURI_VERSION=$(jq -r .package.version src-tauri/tauri.conf.json)
          echo "tauri.conf.json version: $TAURI_VERSION"

          # Get version from Cargo.toml using grep/sed
          CARGO_VERSION=$(grep '^version' src-tauri/Cargo.toml | head -n1 | sed 's/version = "\(.*\)"/\1/')
          echo "Cargo.toml version: $CARGO_VERSION"

          # Check all match
          if [[ "$TAG_VERSION" != "$PKG_VERSION" ]]; then
            echo "❌ Tag version ($TAG_VERSION) does not match package.json version ($PKG_VERSION)."
            exit 1
          fi

          if [[ "$TAG_VERSION" != "$TAURI_VERSION" ]]; then
            echo "❌ Tag version ($TAG_VERSION) does not match tauri.conf.json version ($TAURI_VERSION)."
            exit 1
          fi

          if [[ "$TAG_VERSION" != "$CARGO_VERSION" ]]; then
            echo "❌ Tag version ($TAG_VERSION) does not match Cargo.toml version ($CARGO_VERSION)."
            exit 1
          fi

          echo "✅ Tag version matches all version files."

  changelog:
    name: Generate Changelog
    needs: [auto-version, check_tag_version]
    if: always() && (needs.auto-version.result == 'success' && (needs.check_tag_version.result == 'success' || needs.check_tag_version.result == 'skipped'))
    runs-on: ubuntu-latest
    outputs:
      changelog: ${{ steps.changelog.outputs.changelog }}
      tag: ${{ steps.tag.outputs.tag }}
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Get tag
        id: tag
        run: |
          if [ -n "${{ needs.auto-version.outputs.tag }}" ]; then
            echo "tag=${{ needs.auto-version.outputs.tag }}" >> $GITHUB_OUTPUT
          elif [ "${{ github.event_name }}" = "workflow_dispatch" ] && [ -n "${{ inputs.version }}" ]; then
            echo "tag=${{ inputs.version }}" >> $GITHUB_OUTPUT
          elif [ "${{ github.event_name }}" = "workflow_call" ]; then
            echo "tag=${{ inputs.version }}" >> $GITHUB_OUTPUT
          else
            echo "tag=${GITHUB_REF#refs/tags/}" >> $GITHUB_OUTPUT
          fi

      - name: Generate changelog
        id: changelog
        run: |
          # Get the previous tag
          PREVIOUS_TAG=$(git tag --sort=-version:refname | grep -v "^${{ steps.tag.outputs.tag }}$" | head -n 1)
          
          if [ -z "$PREVIOUS_TAG" ]; then
            echo "No previous tag found, generating changelog from first commit"
            COMMITS=$(git log --pretty=format:"- %s (%h)" --reverse)
          else
            echo "Generating changelog from $PREVIOUS_TAG to ${{ steps.tag.outputs.tag }}"
            COMMITS=$(git log --pretty=format:"- %s (%h)" $PREVIOUS_TAG..${{ steps.tag.outputs.tag }})
          fi
          
          # Create changelog
          CHANGELOG="## What's Changed"$'\n\n'"$COMMITS"
          
          # Save to file and output
          echo "$CHANGELOG" > changelog.md
          echo "changelog<<EOF" >> $GITHUB_OUTPUT
          echo "$CHANGELOG" >> $GITHUB_OUTPUT
          echo "EOF" >> $GITHUB_OUTPUT

      - name: Upload changelog
        uses: actions/upload-artifact@v4
        with:
          name: changelog
          path: changelog.md

  build:
    needs: [changelog, auto-version]
    if: always() && needs.changelog.result == 'success'
    strategy:
      fail-fast: false
      matrix:
        include:
          - os: windows-latest
            target: x86_64-pc-windows-msvc
          - os: windows-latest
            target: aarch64-pc-windows-msvc
          - os: macos-latest
            target: aarch64-apple-darwin
          - os: macos-latest
            target: x86_64-apple-darwin
          - os: ubuntu-22.04
            target: x86_64-unknown-linux-gnu

    runs-on: ${{ matrix.os }}
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
      
      - name: Install Rust
        uses: dtolnay/rust-toolchain@nightly

      - name: Add Rust Target
        run: rustup target add ${{ matrix.target }}
      
      - name: Rust Cache
        uses: Swatinem/rust-cache@v2
        with:
          workspaces: src-tauri
          save-if: false

      - name: Install dependencies (ubuntu only)
        if: matrix.os == 'ubuntu-22.04'
        run: |
          sudo apt-get update
          sudo apt-get install -y libxslt1.1 libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev patchelf
        
      - name: Install Node
        uses: actions/setup-node@v4
        with:
          node-version: "22"
      
      - name: Run install
        uses: borales/actions-yarn@v5
        with:
          cmd: install
      - name:  install and check
        run: |
          yarn install
          yarn run prebuild:dev --target=${{ matrix.target }}

      - name: Update version for build (Windows)
        if: needs.auto-version.outputs.version && runner.os == 'Windows'
        shell: pwsh
        run: |
          # Update package.json
          yarn version --new-version ${{ needs.auto-version.outputs.version }} --no-git-tag-version
          
          # Update Cargo.toml
          (Get-Content src-tauri/Cargo.toml) -replace '^version = ".*"', 'version = "${{ needs.auto-version.outputs.version }}"' | Set-Content src-tauri/Cargo.toml
          
          # Update tauri.conf.json
          (Get-Content src-tauri/tauri.conf.json) -replace '"version": ".*"', '"version": "${{ needs.auto-version.outputs.version }}"' | Set-Content src-tauri/tauri.conf.json

      - name: Update version for build (macOS)
        if: needs.auto-version.outputs.version && runner.os == 'macOS'
        shell: bash
        run: |
          # Update package.json
          yarn version --new-version ${{ needs.auto-version.outputs.version }} --no-git-tag-version
          
          # Update Cargo.toml
          sed -i '' 's/^version = "[^"]*"/version = "${{ needs.auto-version.outputs.version }}"/' src-tauri/Cargo.toml
          
          # Update tauri.conf.json
          sed -i '' 's/"version": "[^"]*"/"version": "${{ needs.auto-version.outputs.version }}"/' src-tauri/tauri.conf.json

      - name: Update version for build (Linux)
        if: needs.auto-version.outputs.version && runner.os == 'Linux'
        shell: bash
        run: |
          # Update package.json
          yarn version --new-version ${{ needs.auto-version.outputs.version }} --no-git-tag-version
          
          # Update Cargo.toml
          sed -i 's/^version = "[^"]*"/version = "${{ needs.auto-version.outputs.version }}"/' src-tauri/Cargo.toml
          
          # Update tauri.conf.json
          sed -i 's/"version": "[^"]*"/"version": "${{ needs.auto-version.outputs.version }}"/' src-tauri/tauri.conf.json
          
      - name: Import Apple Developer Certificate (macOS only)
        if: matrix.os == 'macos-latest'
        uses: apple-actions/import-codesign-certs@v5
        with:
          p12-file-base64: ${{ secrets.APPLE_CERTIFICATE }}
          p12-password: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}

      - name: import windows certificate
        if: matrix.os == 'windows-latest'
        env:
          WINDOWS_CERTIFICATE: ${{ secrets.WINDOWS_CERTIFICATE }}
          WINDOWS_CERTIFICATE_PASSWORD: ${{ secrets.WINDOWS_CERTIFICATE_PASSWORD }}
        run: |
          New-Item -ItemType directory -Path certificate
          Set-Content -Path certificate/tempCert.txt -Value $env:WINDOWS_CERTIFICATE
          certutil -decode certificate/tempCert.txt certificate/certificate.pfx
          Remove-Item -path certificate -include tempCert.txt
          Import-PfxCertificate -FilePath certificate/certificate.pfx -CertStoreLocation Cert:\CurrentUser\My -Password (ConvertTo-SecureString -String $env:WINDOWS_CERTIFICATE_PASSWORD -Force -AsPlainText)

      - name: Build the app
        uses: tauri-apps/tauri-action@v0
        env:
          NODE_OPTIONS: "--max_old_space_size=4096"
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}
          TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}
          # macOS signing and notarization environment variables
          APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
          APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
          APPLE_ID: ${{ secrets.APPLE_ID }}
          APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
          APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
          # Enable signing and notarization for macOS
          APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }}
          WINDOWS_CERTIFICATE: ${{ secrets.WINDOWS_CERTIFICATE }}
          WINDOWS_CERTIFICATE_PASSWORD: ${{ secrets.WINDOWS_CERTIFICATE_PASSWORD }}
        with:
          tagName: ${{ needs.changelog.outputs.tag }}
          releaseName: 'OpenList Desktop ${{ needs.changelog.outputs.tag }}'
          releaseBody: ${{ needs.changelog.outputs.changelog }}
          releaseDraft: false
          prerelease: false
          args: --target ${{ matrix.target }}
  
  release-for-linux-arm:
    name: Release Build for Linux ARM
    needs: [changelog, auto-version]
    if: always() && needs.changelog.result == 'success'
    strategy:
      fail-fast: false
      matrix:
        include:
          - os: ubuntu-22.04
            target: aarch64-unknown-linux-gnu
            arch: arm64
          - os: ubuntu-22.04
            target: armv7-unknown-linux-gnueabihf
            arch: armhf
    runs-on: ${{ matrix.os }}
    steps:
      - name: Checkout Repository
        uses: actions/checkout@v4

      - name: Install Rust
        uses: dtolnay/rust-toolchain@nightly

      - name: Add Rust Target
        run: rustup target add ${{ matrix.target }}

      - name: Rust Cache
        uses: Swatinem/rust-cache@v2
        with:
          workspaces: src-tauri
          save-if: false

      - name: Install Node
        uses: actions/setup-node@v4
        with:
          node-version: "22"

      - name: Run install
        uses: borales/actions-yarn@v5
        with:
          cmd: install

      - name:  install and check
        run: |
          yarn install
          yarn run prebuild:dev --target=${{ matrix.target }}

      - name: Update version for build
        if: needs.auto-version.outputs.version
        run: |
          # Update package.json
          yarn version --new-version ${{ needs.auto-version.outputs.version }} --no-git-tag-version
          
          # Update Cargo.toml
          sed -i 's/^version = "[^"]*"/version = "${{ needs.auto-version.outputs.version }}"/' src-tauri/Cargo.toml
          
          # Update tauri.conf.json
          sed -i 's/"version": "[^"]*"/"version": "${{ needs.auto-version.outputs.version }}"/' src-tauri/tauri.conf.json

      - name: "Setup for linux"
        run: |-
          sudo ls -lR /etc/apt/

          cat > /tmp/sources.list << EOF
          deb [arch=amd64,i386] http://archive.ubuntu.com/ubuntu jammy main multiverse universe restricted
          deb [arch=amd64,i386] http://archive.ubuntu.com/ubuntu jammy-security main multiverse universe restricted
          deb [arch=amd64,i386] http://archive.ubuntu.com/ubuntu jammy-updates main multiverse universe restricted
          deb [arch=amd64,i386] http://archive.ubuntu.com/ubuntu jammy-backports main multiverse universe restricted

          deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy main multiverse universe restricted
          deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy-security main multiverse universe restricted
          deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy-updates main multiverse universe restricted
          deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy-backports main multiverse universe restricted
          EOF

          sudo mv /etc/apt/sources.list /etc/apt/sources.list.default
          sudo mv /tmp/sources.list /etc/apt/sources.list

          sudo dpkg --add-architecture ${{ matrix.arch }}
          sudo apt update

          sudo apt install -y \
            libxslt1.1:${{ matrix.arch }} \
            libwebkit2gtk-4.1-dev:${{ matrix.arch }} \
            libayatana-appindicator3-dev:${{ matrix.arch }} \
            libssl-dev:${{ matrix.arch }} \
            patchelf:${{ matrix.arch }} \
            librsvg2-dev:${{ matrix.arch }}

      - name: "Install aarch64 tools"
        if: matrix.target == 'aarch64-unknown-linux-gnu'
        run: |
          sudo apt install -y \
            gcc-aarch64-linux-gnu \
            g++-aarch64-linux-gnu

      - name: "Install armv7 tools"
        if: matrix.target == 'armv7-unknown-linux-gnueabihf'
        run: |
          sudo apt install -y \
            gcc-arm-linux-gnueabihf \
            g++-arm-linux-gnueabihf

      - name: Build for Linux
        run: |
          export PKG_CONFIG_ALLOW_CROSS=1
          if [ "${{ matrix.target }}" == "aarch64-unknown-linux-gnu" ]; then
            export PKG_CONFIG_PATH=/usr/lib/aarch64-linux-gnu/pkgconfig/:$PKG_CONFIG_PATH
            export PKG_CONFIG_SYSROOT_DIR=/usr/aarch64-linux-gnu/
          elif [ "${{ matrix.target }}" == "armv7-unknown-linux-gnueabihf" ]; then
            export PKG_CONFIG_PATH=/usr/lib/arm-linux-gnueabihf/pkgconfig/:$PKG_CONFIG_PATH
            export PKG_CONFIG_SYSROOT_DIR=/usr/arm-linux-gnueabihf/
          fi
          yarn build --target ${{ matrix.target }}
        env:
          NODE_OPTIONS: "--max_old_space_size=4096"
          TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}
          TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}

      - name: Get Version
        run: |
          sudo apt-get update
          sudo apt-get install jq
          echo "VERSION=$(cat package.json | jq '.version' | tr -d '"')" >> $GITHUB_ENV
          echo "BUILDTIME=$(TZ=Asia/Shanghai date)" >> $GITHUB_ENV

      - name: Upload ARM artifacts
        uses: actions/upload-artifact@v4
        with:
          name: linux-${{ matrix.target }}-artifacts
          path: |
            src-tauri/target/${{ matrix.target }}/release/bundle/deb/*.deb
            src-tauri/target/${{ matrix.target }}/release/bundle/rpm/*.rpm

  publish:
    name: Publish Release
    needs: [changelog, build, release-for-linux-arm, auto-version]
    runs-on: ubuntu-latest
    if: always() && needs.build.result == 'success' && needs.changelog.result == 'success'
    steps:
      - name: Checkout
        uses: actions/checkout@v4
      
      - name: Download changelog
        uses: actions/download-artifact@v4
        with:
          name: changelog

      - name: Download ARM artifacts
        uses: actions/download-artifact@v4
        with:
          pattern: linux-*-artifacts
          merge-multiple: true
          path: arm-artifacts

      - name: Update release with ARM artifacts
        uses: softprops/action-gh-release@v2
        with:
          tag_name: ${{ needs.changelog.outputs.tag }}
          name: 'OpenList Desktop ${{ needs.changelog.outputs.tag }}'
          body_path: changelog.md
          draft: false
          prerelease: false
          files: |
            arm-artifacts/**/*.deb
            arm-artifacts/**/*.rpm
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

  winget-submit:
    name: Submit to WinGet
    needs: [publish, changelog, auto-version]
    runs-on: windows-latest
    if: always() && needs.publish.result == 'success'
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Get release version
        id: version
        run: |
          $version = "${{ needs.auto-version.outputs.version }}"
          echo "version=$version" >> $env:GITHUB_OUTPUT

      - name: Download WinGet Create CLI
        run: |
          Write-Host "Downloading wingetcreate CLI..."
          $url = "https://aka.ms/wingetcreate/latest"
          Invoke-WebRequest -Uri $url -OutFile "wingetcreate.exe"
          Write-Host "Downloaded wingetcreate.exe"

      - name: Update WinGet package manifest
        env:
          GITHUB_TOKEN: ${{ secrets.PERSONAL_GITHUB_TOKEN }}
        run: |
          $version = "${{ steps.version.outputs.version }}"
          # URLs for both x64 and arm64 installers
          $x64InstallerUrl = "https://github.com/${{ github.repository }}/releases/download/v$version/OpenList.Desktop_$version`_x64-setup.exe"
          $arm64InstallerUrl = "https://github.com/${{ github.repository }}/releases/download/v$version/OpenList.Desktop_$version`_arm64-setup.exe"
          
          Write-Host "Updating WinGet package for version: $version"
          Write-Host "x64 Installer URL: $x64InstallerUrl"
          Write-Host "arm64 Installer URL: $arm64InstallerUrl"
          
          Write-Host "Attempting to update existing package..."
          ./wingetcreate.exe update OpenListTeam.OpenListDesktop `
            --version $version `
            --urls $x64InstallerUrl $arm64InstallerUrl `
            --token $env:GITHUB_TOKEN `
            --submit
          
          if ($LASTEXITCODE -ne 0) {
            Write-Host "First submit, will do manually..."
          } else {
            Write-Host "Successfully updated existing WinGet package"
          }
