# Publish to Chocolatey Community Repository
#
# PREREQUISITES:
# 1. Create a Chocolatey account at https://community.chocolatey.org/account/Register
# 2. Get your API key from https://community.chocolatey.org/account
# 3. Add the API key as repository secret: CHOCOLATEY_API_KEY
#
# Reference: https://docs.chocolatey.org/en-us/create/create-packages-quick-start

name: Publish to Chocolatey

on:
  workflow_run:
    workflows: ["Upload releases"]
    types: [completed]
  workflow_dispatch:
    inputs:
      release_tag:
        description: 'Release tag to publish (e.g., v0.96.1)'
        required: true
        type: string

jobs:
  publish:
    runs-on: windows-latest
    if: >-
      github.event_name == 'workflow_dispatch' ||
      github.event.workflow_run.conclusion == 'success'
    steps:
      - name: Checkout repository
        uses: actions/checkout@v6

      - name: Get version from tag
        id: version
        shell: bash
        run: |
          TAG="${{ github.event.inputs.release_tag || github.event.workflow_run.head_branch }}"
          # Strip 'v' prefix if present
          VERSION="${TAG#v}"
          echo "version=$VERSION" >> $GITHUB_OUTPUT
          echo "tag=$TAG" >> $GITHUB_OUTPUT

      - name: Download MSI from release
        shell: pwsh
        run: |
          $version = "${{ steps.version.outputs.version }}"
          $tag = "${{ steps.version.outputs.tag }}"
          $msiUrl = "https://github.com/CCExtractor/ccextractor/releases/download/$tag/CCExtractor.$version.msi"

          Write-Host "Downloading MSI from: $msiUrl"
          Invoke-WebRequest -Uri $msiUrl -OutFile "CCExtractor.msi"

          # Calculate SHA256 checksum
          $hash = (Get-FileHash -Path "CCExtractor.msi" -Algorithm SHA256).Hash
          Write-Host "SHA256: $hash"
          echo "MSI_CHECKSUM=$hash" >> $env:GITHUB_ENV

      - name: Update nuspec version
        shell: pwsh
        run: |
          $version = "${{ steps.version.outputs.version }}"
          $nuspecPath = "packaging/chocolatey/ccextractor.nuspec"

          $content = Get-Content $nuspecPath -Raw
          $content = $content -replace '<version>.*</version>', "<version>$version</version>"
          Set-Content -Path $nuspecPath -Value $content

          Write-Host "Updated nuspec to version $version"

      - name: Update install script
        shell: pwsh
        run: |
          $version = "${{ steps.version.outputs.version }}"
          $tag = "${{ steps.version.outputs.tag }}"
          $checksum = $env:MSI_CHECKSUM
          $installScript = "packaging/chocolatey/tools/chocolateyInstall.ps1"

          $content = Get-Content $installScript -Raw

          # Update URL
          $newUrl = "https://github.com/CCExtractor/ccextractor/releases/download/$tag/CCExtractor.$version.msi"
          $content = $content -replace "url64bit\s*=\s*'[^']*'", "url64bit       = '$newUrl'"

          # Update checksum
          $content = $content -replace "checksum64\s*=\s*'[^']*'", "checksum64     = '$checksum'"

          Set-Content -Path $installScript -Value $content

          Write-Host "Updated install script with URL and checksum"

      - name: Build Chocolatey package
        shell: pwsh
        run: |
          cd packaging/chocolatey
          choco pack ccextractor.nuspec

          # List the generated package
          Get-ChildItem *.nupkg

      - name: Test package locally
        shell: pwsh
        run: |
          cd packaging/chocolatey
          $nupkg = Get-ChildItem *.nupkg | Select-Object -First 1
          Write-Host "Testing package: $($nupkg.Name)"

          # Install from local package
          choco install ccextractor --source="'.;https://community.chocolatey.org/api/v2/'" --yes --force

          # Verify installation
          $ccx = Get-Command ccextractor -ErrorAction SilentlyContinue
          if ($ccx) {
            Write-Host "CCExtractor found at: $($ccx.Source)"
            & ccextractor --version
          } else {
            Write-Host "CCExtractor not found in PATH, checking Program Files..."
            $exePath = Join-Path $env:ProgramFiles "CCExtractor\ccextractor.exe"
            if (Test-Path $exePath) {
              & $exePath --version
            }
          }

      - name: Push to Chocolatey
        shell: pwsh
        env:
          CHOCOLATEY_API_KEY: ${{ secrets.CHOCOLATEY_API_KEY }}
        run: |
          cd packaging/chocolatey
          $nupkg = Get-ChildItem *.nupkg | Select-Object -First 1

          Write-Host "Pushing $($nupkg.Name) to Chocolatey..."
          choco push $nupkg.Name --source="https://push.chocolatey.org/" --api-key="$env:CHOCOLATEY_API_KEY"

          Write-Host "Package submitted to Chocolatey! It may take some time to be moderated and published."

      - name: Upload package artifact
        uses: actions/upload-artifact@v7
        with:
          name: chocolatey-package
          path: packaging/chocolatey/*.nupkg
