pipeline {
    agent none

    environment {
        TAIGA_PROJECT_ID = '1'
        TAIGA_URL = 'https://taiga.grigowashere.ru'
    }

    stages {
        stage('Build Windows Qt') {
            agent { label 'windows' }

            steps {
                deleteDir()
                checkout scm

                bat '''
                    call "C:\\Program Files (x86)\\Microsoft Visual Studio\\2022\\BuildTools\\VC\\Auxiliary\\Build\\vcvars64.bat"

                    cmake -S . -B build\\windows -G Ninja ^
                      -DCMAKE_BUILD_TYPE=Release ^
                      -DCMAKE_TOOLCHAIN_FILE=C:\\vcpkg\\scripts\\buildsystems\\vcpkg.cmake ^
                      -DVCPKG_TARGET_TRIPLET=x64-windows

                    cmake --build build\\windows

                    if exist dist\\windows rmdir /s /q dist\\windows
                    mkdir dist\\windows

                    copy build\\windows\\test_app.exe dist\\windows\\test_app.exe

                    for /f "delims=" %%i in ('dir /b /s C:\\vcpkg\\installed\\x64-windows\\tools\\Qt6\\windeployqt.exe') do set WINDEPLOYQT=%%i

                    "%WINDEPLOYQT%" --release --no-translations dist\\windows\\test_app.exe

                    xcopy /Y /I C:\\vcpkg\\installed\\x64-windows\\bin\\*.dll dist\\windows\\
                '''

                archiveArtifacts artifacts: 'dist/windows/**', fingerprint: true
            }
        }

stage('Create Gitea Release and Upload ZIP') {
    agent { label 'windows' }

    steps {
        withCredentials([string(credentialsId: 'Gitea_Credentials', variable: 'GITEA_TOKEN')]) {
            writeFile file: 'gitea-release.ps1', text: '''
$ErrorActionPreference = "Stop"

Compress-Archive -Path "dist\\windows\\*" -DestinationPath "dist\\windows-build.zip" -Force

$headers = @{
    Authorization = "token $env:GITEA_TOKEN"
}

$body = @{
    tag_name = "v$env:BUILD_NUMBER"
    target_commitish = "main"
    name = "Release v$env:BUILD_NUMBER"
    body = "Jenkins build $env:BUILD_NUMBER"
    draft = $false
    prerelease = $false
} | ConvertTo-Json

$release = Invoke-RestMethod `
    -Method Post `
    -Uri "https://git.grigowashere.ru/api/v1/repos/Grigo/Testing/releases" `
    -Headers $headers `
    -ContentType "application/json" `
    -Body $body

$uploadUrl = "https://git.grigowashere.ru/api/v1/repos/Grigo/Testing/releases/$($release.id)/assets?name=windows-build.zip"

Invoke-RestMethod `
    -Method Post `
    -Uri $uploadUrl `
    -Headers $headers `
    -InFile "dist\\windows-build.zip" `
    -ContentType "application/zip"
'''

            bat '''
powershell -NoProfile -ExecutionPolicy Bypass -File gitea-release.ps1
'''
        }
    }
}
    }

    post {
        always {
            node('windows') {
                script {
                    def result = currentBuild.currentResult ?: 'UNKNOWN'

                    withCredentials([string(credentialsId: 'TAIGA_TOKEN', variable: 'TAIGA_TOKEN')]) {
                        writeFile file: 'taiga-post.ps1', text: '''
$ErrorActionPreference = "Continue"

$commitMsg = git log -1 --pretty=%B 2>$null

if ([string]::IsNullOrWhiteSpace($commitMsg)) {
    Write-Host "No git commit message available"
    exit 0
}

$match = [regex]::Match($commitMsg, 'TG-(\d+)')

if (-not $match.Success) {
    Write-Host "No TG-* reference found"
    exit 0
}

$ref = $match.Groups[1].Value

$headers = @{
    Authorization = "Bearer $env:TAIGA_TOKEN"
    "Content-Type" = "application/json"
}

$targets = @(
    @{ endpoint = "userstories"; label = "User Story" },
    @{ endpoint = "issues"; label = "Issue" },
    @{ endpoint = "tasks"; label = "Task" }
)

$found = $null

foreach ($target in $targets) {
    try {
        $url = "$env:TAIGA_URL/api/v1/$($target.endpoint)/by_ref?project=$env:TAIGA_PROJECT_ID&ref=$ref"
        $data = Invoke-RestMethod -Uri $url -Headers $headers -Method Get
        if ($data.id) {
            $found = @{
                endpoint = $target.endpoint
                label = $target.label
                data = $data
            }
            break
        }
    } catch {
        Write-Host "Taiga lookup warning"
    }
}

if (-not $found) {
    Write-Host "Taiga TG-$ref not found"
    exit 0
}

$comment = "Jenkins Windows Qt build #$env:BUILD_NUMBER: $env:BUILD_RESULT`n$env:BUILD_URL"

$body = @{
    comment = $comment
    version = $found.data.version
} | ConvertTo-Json

try {
    $url = "$env:TAIGA_URL/api/v1/$($found.endpoint)/$($found.data.id)"
    Invoke-RestMethod -Uri $url -Headers $headers -Method Patch -Body $body
    Write-Host "Commented Taiga TG-$ref ($($found.label))"
} catch {
    Write-Host "Taiga comment warning"
}

exit 0
'''

                        withEnv(["BUILD_RESULT=${result}"]) {
                            bat(returnStatus: true, script: '''
                                powershell -NoProfile -ExecutionPolicy Bypass -File taiga-post.ps1
                                exit /b 0
                            ''')
                        }
                    }
                }
            }
        }
    }
}