name: Build Windows


on:
  push:
    branches: [ master, main ]
  pull_request:
    branches: [ master, main ]
  workflow_dispatch:

env:
  GODOT_VERSION: 4.4.1
  EXPORT_NAME: PNGTuber-Plus

jobs:
  export-windows:
    name: Windows Export
    runs-on: self-hosted
    if: contains(github.event.head_commit.message, '!build')
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          lfs: true
      
      - name: Debug Environment
        run: |
          Write-Host "Current directory: $(Get-Location)"
          Write-Host "Godot executable exists: $(Test-Path 'D:\Godot\Godot_v4.4.1-stable_win64.exe')"
          Write-Host "Export name: $env:EXPORT_NAME"
          Write-Host "Project file exists: $(Test-Path 'project.godot')"
          Get-ChildItem -Path . -Filter "*.cfg" | Select-Object Name

      - name: Verify Export Templates
        run: |
          $templateDir = "C:\WINDOWS\ServiceProfiles\NetworkService\AppData\Roaming\Godot\export_templates\4.4.1.stable"
          Write-Host "Checking for export templates at: $templateDir"
          
          if (Test-Path $templateDir) {
            Write-Host "Export templates found. Contents:"
            Get-ChildItem -Path $templateDir | Where-Object {$_.Name -like "*windows*"} | Select-Object Name, Length | Format-Table
            
            # Verify the specific Windows templates we need
            $debugTemplate = Join-Path $templateDir "windows_debug_x86_64.exe"
            $releaseTemplate = Join-Path $templateDir "windows_release_x86_64.exe"
            
            if ((Test-Path $debugTemplate) -and (Test-Path $releaseTemplate)) {
              Write-Host "✅ Required Windows templates found"
            } else {
              Write-Host "❌ Required Windows templates missing"
              exit 1
            }
          } else {
            Write-Host "❌ Export template directory not found!"
            exit 1
          }
          
          # Check if rcedit is available (it's already in the project)
          Write-Host "Checking for rcedit..."
          if (Test-Path "rcedit-x64.exe") {
            Write-Host "✅ rcedit found in project directory"
          } else {
            Write-Host "rcedit not found - downloading..."
            Invoke-WebRequest -Uri "https://github.com/electron/rcedit/releases/latest/download/rcedit-x64.exe" -OutFile "rcedit-x64.exe"
            Write-Host "✅ rcedit downloaded"
          }

      - name: Windows Build
        run: .\build-windows-ci.bat
        shell: cmd

      - name: Check Build Output
        run: |
          Write-Host "Build directory contents:"
          if (Test-Path "build\windows") {
            Get-ChildItem -Path "build\windows" -Recurse | Select-Object Name, Length
          } else {
            Write-Host "Build directory does not exist!"
          }
          
          if (Test-Path "build\windows\PNGTuber-Plus.exe") {
            Write-Host "Build SUCCESS: PNGTuber-Plus.exe created"
            $fileSize = (Get-Item "build\windows\PNGTuber-Plus.exe").Length
            Write-Host "File size: $fileSize bytes"
          } else {
            Write-Host "Build FAILED: PNGTuber-Plus.exe not found"
            exit 1
          }
      
      - name: Upload Windows Build
        uses: actions/upload-artifact@v4
        with:
          name: windows-build
          path: build/windows/
          retention-days: 14

  release:
    name: Create Release
    needs: export-windows
    runs-on: self-hosted
    if: github.ref == 'refs/heads/master' && github.event_name == 'push' && success()
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
      
      - name: Generate Release Info
        id: release_info
        run: |
          # Get current date and time
          $date = Get-Date -Format "yyyy.MM.dd"
          $time = Get-Date -Format "HHmm"
          
          # Get short commit hash (first 7 characters)
          $shortSha = "${{ github.sha }}".Substring(0, 7)
          
          # Get commit count since last tag (for build number)
          $buildNumber = & git rev-list --count HEAD
          
          # Create version-like tag and release name
          $tag = "v$date-build$buildNumber"
          $releaseName = "PNGTuber+ v$date Build $buildNumber"
          
          Write-Host "Generated tag: $tag"
          Write-Host "Generated release name: $releaseName"
          
          # Get the latest release tag to compare against
          $latestTag = ""
          try {
            $latestTag = & git describe --tags --abbrev=0 2>$null
            Write-Host "Latest tag found: $latestTag"
          } catch {
            Write-Host "No previous tags found, showing all commits"
          }
          
          # Generate commit history since last tag (or all commits if no tag)
          $commitRange = if ($latestTag) { "$latestTag..HEAD" } else { "HEAD" }
          
          # Get commits with format: short hash, subject, author
          $commits = & git log $commitRange --pretty=format:"%h|%s|%an" --no-merges
          
          # Build commit history as a single string
          $commitHistory = ""
          
          if ($commits) {
            $commitHistory += "`n`n## Changes Since Last Release`n`n"
            
            $commits | ForEach-Object {
              $parts = $_ -split '\|', 3
              $hash = $parts[0]
              $subject = $parts[1] -replace '"', '""'
              $author = $parts[2]
              $commitUrl = "https://github.com/${{ github.repository }}/commit/$hash"
              $commitHistory += "- [$hash]($commitUrl) $subject (by $author)`n"
            }
          } else {
            $commitHistory += "`n`n## Changes Since Last Release`n`nNo new commits since last release.`n"
          }
          
          # Set outputs for use in next steps
          echo "tag=$tag" >> $env:GITHUB_OUTPUT
          echo "release_name=$releaseName" >> $env:GITHUB_OUTPUT
          echo "short_sha=$shortSha" >> $env:GITHUB_OUTPUT
          echo "build_number=$buildNumber" >> $env:GITHUB_OUTPUT
          
          # Use heredoc syntax for multiline commit history
          Add-Content -Path $env:GITHUB_OUTPUT -Value "commit_history<<EOF"
          Add-Content -Path $env:GITHUB_OUTPUT -Value $commitHistory
          Add-Content -Path $env:GITHUB_OUTPUT -Value "EOF"
      - name: Download Windows Build
        uses: actions/download-artifact@v4
        with:
          name: windows-build
          path: ./windows/
      
      - name: Create Release
        id: create_release
        uses: actions/create-release@v1
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          tag_name: ${{ steps.release_info.outputs.tag }}
          release_name: ${{ steps.release_info.outputs.release_name }}
          body: |
            Automated build of PNGTuber Plus
            
            **Build Information:**
            - Build Number: ${{ steps.release_info.outputs.build_number }}
            - Commit: [${{ steps.release_info.outputs.short_sha }}](https://github.com/${{ github.repository }}/commit/${{ github.sha }})
            - Branch: ${{ github.ref_name }}
            ${{ steps.release_info.outputs.commit_history }}
            
            ## Installation
            1. Download PNGTuber-Plus.exe from the assets below
            2. Run the executable - no installation required!
            3. For StreamDeck integration, download the plugin from [here](https://github.com/BoyneGames/streamdeck-godot-plugin/releases/tag/1.0.0)
            
            ## Credits
            - Original project by [kaiakairos](https://github.com/kaiakairos/PNGTuber-Plus)
            - Microphone improvements by [k0ffinz](https://github.com/k0ffinz/PNGTuber-Plus)
          draft: false
          prerelease: false
      
      - name: Upload Windows Release Asset
        uses: actions/upload-release-asset@v1
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          upload_url: ${{ steps.create_release.outputs.upload_url }}
          asset_path: ./windows/PNGTuber-Plus.exe
          asset_name: PNGTuber-Plus.exe
          asset_content_type: application/octet-stream
