def runCommand(String command) {
    if (isUnix()) {
        sh(script: command)
    } else {
        bat(script: command)
    }
}

pipeline {
	agent {
		label 'windows'
	}
	stages {

        stage('Read stages config') {
            steps {
                script {
                    def configText = readFile './service/tests_config.json'
                    env.STAGES_CONFIG = configText
                }
            }
        }

		stage('Decrypt Data') {
            steps {
                powershell encoding: 'UTF-8', script:'cd ./src/en/OInt; opm build; opm install oint-1.30.0.ospx; del oint-1.30.0.ospx'
                withCredentials([string(credentialsId: 'gpgkey', variable: 'GPGKEY')]) {
                    bat encoding: 'UTF-8', script:'gpg --quiet --batch --yes --decrypt --passphrase="%GPGKEY%" --output ./data.json ./data.json.gpg'
                }
            }
        }

        stage('Remove oint.bat if exists') {
            steps {
                powershell encoding: 'UTF-8', script: '''
                    $batFile = "C:\\Program Files\\OneScript\\bin\\oint.bat"
                    if (Test-Path $batFile) {
                        Remove-Item -Path $batFile -Force
                        Write-Host "Файл oint.bat удален."
                    } else {
                        Write-Host "Файл oint.bat не найден, пропускаем удаление."
                    }
                '''

                // Проверяем, что файл действительно удален
                powershell encoding: 'UTF-8', script: '''
                    $batFile = "C:\\Program Files\\OneScript\\bin\\oint.bat"
                    if (Test-Path $batFile) {
                        Write-Error "Ошибка: Файл oint.bat не удален!"
                        exit 1
                    } else {
                        Write-Host "Проверка: oint.bat успешно удален или отсутствовал."
                    }
                '''
            }
        }

        stage('Uninstall OInt if installed') {
            steps {
                powershell encoding: 'UTF-8', script: '''
                    $uninstallerPath = "C:\\Program Files (x86)\\OInt\\unins000.exe"
                    if (Test-Path $uninstallerPath) {
                        Write-Host "OInt найден. Запускаем удаление..."
                        Start-Process -FilePath $uninstallerPath -ArgumentList "/VERYSILENT /NORESTART" -Wait
                        Write-Host "Удаление OInt завершено."
                    } else {
                        Write-Host "OInt не установлен. Пропускаем этап удаления."
                    }
                '''

                // Проверяем, что oint.bat в C:\Program Files (x86)\OInt\bin\oint.bat удален
                powershell encoding: 'UTF-8', script: '''
                    $batFile = "C:\\Program Files (x86)\\OInt\\bin\\oint.bat"
                    if (Test-Path $batFile) {
                        Write-Error "Ошибка: oint.bat всё ещё существует после uninstall!"
                        exit 1
                    } else {
                        Write-Host "Проверка: oint.bat после uninstall отсутствует."
                    }
                '''
            }
        }

        stage('Prepare Download Dir') {
            steps {
                bat 'if not exist "%USERPROFILE%\\Downloads" mkdir "%USERPROFILE%\\Downloads"'
            }
        }

        stage('Download Installer') {
            steps {
                powershell encoding: 'UTF-8', script: '''
                    $url = "https://jenkins.openintegrations.dev/job/OpiBuild/job/OpiRelease/lastSuccessfulBuild/artifact/1.30.0/oint_1.30.0_installer_en.exe "
                    $output = "$env:USERPROFILE\\Downloads\\oint_installer.exe"
                    Invoke-WebRequest -Uri $url -OutFile $output
                    Write-Host "Инсталлер скачан в: $output"
                '''
            }
        }

        stage('Install OInt') {
            steps {
                powershell encoding: 'UTF-8', script: '''
                    $installerPath = "$env:USERPROFILE\\Downloads\\oint_installer.exe"
                    Write-Host "Запускаем установку: $installerPath"
                    Start-Process -FilePath $installerPath -ArgumentList "/VERYSILENT /NORESTART" -NoNewWindow -Wait
                    Write-Host "Установка завершена."
                '''
            }
        }

        stage('Verify Installation') {
            steps {
                // Проверяем наличие oint.bat в C:\Program Files (x86)\OInt\bin\
                powershell encoding: 'UTF-8', script: '''
                    $batFile = "C:\\Program Files (x86)\\OInt\\bin\\oint.bat"
                    if (-not (Test-Path $batFile)) {
                        Write-Error "Ошибка: oint.bat не найден после установки!"
                        exit 1
                    } else {
                        Write-Host "Проверка: oint.bat найден после установки."
                    }
                '''

                // Проверяем, что where oint выводит нужный путь
                powershell encoding: 'UTF-8', script: '''
                    $result = (Get-Command oint -ErrorAction SilentlyContinue).Source
                    $expectedPath = "C:\\Program Files (x86)\\OInt\\bin\\oint.bat"

                    if ($result -ne $expectedPath) {
                        Write-Error "Ошибка: Команда 'where oint' указывает не на тот путь: $result"
                        exit 1
                    } else {
                        Write-Host "Проверка: 'where oint' указывает на правильный путь: $result"
                    }
                '''
            }
        }
        stage('Create ReportPortal launch'){
				steps{
					bat encoding: 'UTF-8', script:'chcp 65001 & oscript ./ci/os/rp_start.os "CLI"'
				}
		}

		stage('Testing-BuildCheck') {
            when {
                expression { return shouldRunStage('BuildCheck') }
            }
			steps {
				script {
					def tests = [
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'CheckIBToLastBuildCompliance'],
					]
					for (test in tests) {
							runLibraryTest(test[0], test[1])
					}
				}
			}
		}
		stage('Testing-Telegram') {
            when {
                expression { return shouldRunStage('Telegram') }
            }
			steps {
				script {
					def tests = [
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'TelegramAPI_GetBotInfo'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'TelegramAPI_GetUpdates'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'TelegramAPI_SetWebhook'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'TelegramAPI_SendTextMessage'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'TelegramAPI_SendImage'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'TelegramAPI_SendVideo'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'TelegramAPI_SendAudio'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'TelegramAPI_SendDocument'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'TelegramAPI_SendGIF'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'TelegramAPI_SendMediaGroup'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'TelegramAPI_SendLocation'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'TelegramAPI_SendContact'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'TelegramAPI_SendPoll'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'TelegramAPI_ForwardMessage'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'TelegramAPI_BanUnban'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'TelegramAPI_CreateInvitationLink'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'TelegramAPI_PinUnpinMessage'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'TelegramAPI_GetMemberCount'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'TelegramAPI_GetForumAvatarsList'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'TelegramAPI_CreateDeleteForumTopic'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'TelegramAPI_ChangeMainTopicName'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'TelegramAPI_HideShowMainTopic'],
					]
					for (test in tests) {
						catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
							runLibraryTest(test[0], test[1])
						}
					}
				}
			}
		}
		stage('Testing-VK') {
            when {
                expression { return shouldRunStage('VK') }
            }
			steps {
				script {
					def tests = [
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'VKAPI_CreateTokenLink'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'VKAPI_CreateDeletePost'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'VKAPI_CreateCompositePost'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'VKAPI_CreatePoll'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'VKAPI_SaveDeleteImage'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'VKAPI_CreateStory'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'VKAPI_DiscussionMethods'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'VKAPI_LikeRepostComment'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'VKAPI_GetStatistics'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'VKAPI_GetPostStatistics'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'VKAPI_CreateAdCampaign'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'VKAPI_SendMessage'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'VKAPI_GetProductCategories'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'VKAPI_CreateProductSelection'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'VKAPI_CreateProductWithProperties'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'VKAPI_GetProductList'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'VKAPI_GetSelectionList'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'VKAPI_GetPropertyList'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'VKAPI_GetOrderList'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'VKAPI_UploadVideo'],
					]
					for (test in tests) {
						catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
							runLibraryTest(test[0], test[1])
						}
					}
				}
			}
		}
		stage('Testing-Viber') {
            when {
                expression { return shouldRunStage('Viber') }
            }
			steps {
				script {
					def tests = [
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'Viber_DataRetrieval'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'Viber_MessagesSending'],
					]
					for (test in tests) {
						catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
							runLibraryTest(test[0], test[1])
						}
					}
				}
			}
		}
		stage('Testing-Twitter') {
            when {
                expression { return shouldRunStage('Twitter') }
            }
			steps {
				script {
					def tests = [
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'TwitterAPI_AccountData'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'TwitterAPI_Tweets'],
					]
					for (test in tests) {
						catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
							runLibraryTest(test[0], test[1])
						}
					}
				}
			}
		}
		stage('Testing-FTP') {
            when {
                expression { return shouldRunStage('FTP') }
            }
			steps {
				script {
					def tests = [
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'FT_DirecotryManagement'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'FT_FileOperations'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'FT_CommonMethods'],
					]
					for (test in tests) {
						catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
							runLibraryTest(test[0], test[1])
						}
					}
				}
			}
		}
		stage('Testing-SSH') {
            when {
                expression { return shouldRunStage('SSH') }
            }
			steps {
				script {
					def tests = [
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'SShell_CommonMethods'],
					]
					for (test in tests) {
						catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
							runLibraryTest(test[0], test[1])
						}
					}
				}
			}
		}
		stage('Testing-SFTP') {
            when {
                expression { return shouldRunStage('SFTP') }
            }
			steps {
				script {
					def tests = [
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'SF_CommonMethods'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'SF_DirectoryManagement'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'SF_FileManagement'],
					]
					for (test in tests) {
						catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
							runLibraryTest(test[0], test[1])
						}
					}
				}
			}
		}
		stage('Testing-PostgreSQL') {
            when {
                expression { return shouldRunStage('PostgreSQL') }
            }
			steps {
				script {
					def tests = [
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'Postgres_CommonMethods'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'Postgres_ORM'],
					]
					for (test in tests) {
						catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
							runLibraryTest(test[0], test[1])
						}
					}
				}
			}
		}
		stage('Testing-MySQL') {
            when {
                expression { return shouldRunStage('MySQL') }
            }
			steps {
				script {
					def tests = [
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'MYS_CommonMethods'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'MYS_ORM'],
					]
					for (test in tests) {
						catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
							runLibraryTest(test[0], test[1])
						}
					}
				}
			}
		}
		stage('Testing-MSSQL') {
            when {
                expression { return shouldRunStage('MSSQL') }
            }
			steps {
				script {
					def tests = [
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'MSS_CommonMethods'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'MSS_ORM'],
					]
					for (test in tests) {
						catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
							runLibraryTest(test[0], test[1])
						}
					}
				}
			}
		}
		stage('Testing-SQLite') {
            when {
                expression { return shouldRunStage('SQLite') }
            }
			steps {
				script {
					def tests = [
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'SQLL_CommonMethods'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'SQLL_ORM'],
					]
					for (test in tests) {
						catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
							runLibraryTest(test[0], test[1])
						}
					}
				}
			}
		}
		stage('Testing-MongoDB') {
            when {
                expression { return shouldRunStage('MongoDB') }
            }
			steps {
				script {
					def tests = [
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'Mongo_CommonMethods'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'Mong_DatabaseManagement'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'Mongo_CollectionManagement'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'Mongo_DocumentsManagement'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'Mongo_UserManagement'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'Mongo_RoleManagement'],
					]
					for (test in tests) {
						catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
							runLibraryTest(test[0], test[1])
						}
					}
				}
			}
		}
		stage('Testing-RCON') {
            when {
                expression { return shouldRunStage('RCON') }
            }
			steps {
				script {
					def tests = [
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'RC_CommandsExecution'],
					]
					for (test in tests) {
						catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
							runLibraryTest(test[0], test[1])
						}
					}
				}
			}
		}
		stage('Testing-YandexDisk') {
            when {
                expression { return shouldRunStage('YandexDisk') }
            }
			steps {
				script {
					def tests = [
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'YDisk_Authorization'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'YDisk_GetDiskInfo'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'YDisk_CreateFolder'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'YDisk_UploadByUrlAndGetObject'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'YDisk_UploadDeleteFile'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'YDisk_CreateObjectCopy'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'YDisk_GetDownloadLink'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'YDisk_GetFileList'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'YDisk_MoveObject'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'YDisk_PublicObjectActions'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'YDisk_GetPublishedList'],
					]
					for (test in tests) {
						catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
							runLibraryTest(test[0], test[1])
						}
					}
				}
			}
		}
		stage('Testing-GoogleWorkspace') {
            when {
                expression { return shouldRunStage('GoogleWorkspace') }
            }
			steps {
				script {
					def tests = [
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'GW_Auth'],
					]
					for (test in tests) {
						catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
							runLibraryTest(test[0], test[1])
						}
					}
				}
			}
		}
		stage('Testing-GoogleCalendar') {
            when {
                expression { return shouldRunStage('GoogleCalendar') }
            }
			steps {
				script {
					def tests = [
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'GC_Authorization'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'GC_GetCalendarList'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'GC_CreateDeleteCalendar'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'GC_CreateDeleteEvent'],
					]
					for (test in tests) {
						catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
							runLibraryTest(test[0], test[1])
						}
					}
				}
			}
		}
		stage('Testing-GoogleDrive') {
            when {
                expression { return shouldRunStage('GoogleDrive') }
            }
			steps {
				script {
					def tests = [
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'GD_Authorization'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'GD_GetCatalogList'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'GD_UploadDeleteFile'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'GD_CreateDeleteComment'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'GD_CreateCatalog'],
					]
					for (test in tests) {
						catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
							runLibraryTest(test[0], test[1])
						}
					}
				}
			}
		}
		stage('Testing-GoogleSheets') {
            when {
                expression { return shouldRunStage('GoogleSheets') }
            }
			steps {
				script {
					def tests = [
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'GT_Authorization'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'GT_CreateTable'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'GT_FillClearCells'],
					]
					for (test in tests) {
						catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
							runLibraryTest(test[0], test[1])
						}
					}
				}
			}
		}
		stage('Testing-Notion') {
            when {
                expression { return shouldRunStage('Notion') }
            }
			steps {
				script {
					def tests = [
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'NotionAPI_CreatePage'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'NotionAPI_CreateUpdateBase'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'NotionAPI_CreateDeleteBlock'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'NotionAPI_GetUsers'],
					]
					for (test in tests) {
						catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
							runLibraryTest(test[0], test[1])
						}
					}
				}
			}
		}
		stage('Testing-Slack') {
            when {
                expression { return shouldRunStage('Slack') }
            }
			steps {
				script {
					def tests = [
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'SlackGetData'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'Slack_SendDeleteMessage'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'Slack_CreateArchiveChannel'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'Slack_OpenCloseDialog'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'Slack_UploadDeleteFile'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'Slack_UploadDeleteExternalFile'],
					]
					for (test in tests) {
						catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
							runLibraryTest(test[0], test[1])
						}
					}
				}
			}
		}
		stage('Testing-Airtable') {
            when {
                expression { return shouldRunStage('Airtable') }
            }
			steps {
				script {
					def tests = [
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'AT_CreateDatabase'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'AT_CreateTable'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'AT_CreateField'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'AT_CreateDeleteRecords'],
					]
					for (test in tests) {
						catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
							runLibraryTest(test[0], test[1])
						}
					}
				}
			}
		}
		stage('Testing-Dropbox') {
            when {
                expression { return shouldRunStage('Dropbox') }
            }
			steps {
				script {
					def tests = [
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'DropboxAPI_GetUpdateToken'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'DropboxAPI_UploadFile'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'DropboxAPI_UploadFileByURL'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'DropboxAPI_CreateFolder'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'DropboxAPI_CreateDeleteTag'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'DropboxAPI_GetAccount'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'DropboxAPI_AccessManagement'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'DropboxAPI_GetFolderFileList'],
					]
					for (test in tests) {
						catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
							runLibraryTest(test[0], test[1])
						}
					}
				}
			}
		}
		stage('Testing-Bitrix24') {
            when {
                expression { return shouldRunStage('Bitrix24') }
            }
			steps {
				script {
					def tests = [
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'B24_TokenManagement'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'B24_ServerTime'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'B24_PostsManagement'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'B24_TaskManagement'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'B24_CommentsManagement'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'B24_WorkingWithDrive'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'B24_Kanban'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'B24_Timekeeping'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'B24_ChatManagement'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'B24_NotificationsManagement'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'B24_TasksFieldsManagement'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'B24_DepartmentsManagement'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'B2_UsersManagement'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'B24_LeadsManagement'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'B24_DealsManagement'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'B24_CalendarsManagement'],
					]
					for (test in tests) {
						catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
							runLibraryTest(test[0], test[1])
						}
					}
				}
			}
		}
		stage('Testing-VkTeams') {
            when {
                expression { return shouldRunStage('VkTeams') }
            }
			steps {
				script {
					def tests = [
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'VKT_MessagesSending'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'VKT_CommonMethods'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'VKT_ChatManagement'],
					]
					for (test in tests) {
						catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
							runLibraryTest(test[0], test[1])
						}
					}
				}
			}
		}
		stage('Testing-Neocities') {
            when {
                expression { return shouldRunStage('Neocities') }
            }
			steps {
				script {
					def tests = [
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'NC_FilesManagement'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'NC_DataRetrieving'],
					]
					for (test in tests) {
						catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
							runLibraryTest(test[0], test[1])
						}
					}
				}
			}
		}
		stage('Testing-CDEK') {
            when {
                expression { return shouldRunStage('CDEK') }
            }
			steps {
				script {
					def tests = [
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'CdekAPI_CommonMethods'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'CDEKAPI_OrdersManagement'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'CdekAPI_CourierInvitationsManagement'],
					]
					for (test in tests) {
						catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
							runLibraryTest(test[0], test[1])
						}
					}
				}
			}
		}
		stage('Testing-YandexMetrika') {
            when {
                expression { return shouldRunStage('YandexMetrika') }
            }
			steps {
				script {
					def tests = [
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'YaMetrika_TagsManagement'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'YaMetrika_CountersManagement'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'YaMetrika_ActionsManagement'],
					]
					for (test in tests) {
						catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
							runLibraryTest(test[0], test[1])
						}
					}
				}
			}
		}
		stage('Testing-S3') {
            when {
                expression { return shouldRunStage('S3') }
            }
			steps {
				script {
					def tests = [
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'AWS_CommonMethods'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'AWS_BucketsManagement'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'AWS_ObjectsManagement'],
					]
					for (test in tests) {
						catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
							runLibraryTest(test[0], test[1])
						}
					}
				}
			}
		}
		stage('Testing-TCP') {
            when {
                expression { return shouldRunStage('TCP') }
            }
			steps {
				script {
					def tests = [
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'TC_Client'],
					]
					for (test in tests) {
						catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
							runLibraryTest(test[0], test[1])
						}
					}
				}
			}
		}
		stage('Testing-GreenAPI') {
            when {
                expression { return shouldRunStage('GreenAPI') }
            }
			steps {
				script {
					def tests = [
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'GAPI_GroupManagement'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'GAPI_MessageSending'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'GAPI_NotificationsReceiving'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'GAPI_MessageQueue'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'GAPI_MessageLogs'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'GAPI_Account'],
					]
					for (test in tests) {
						catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
							runLibraryTest(test[0], test[1])
						}
					}
				}
			}
		}
		stage('Testing-GreenMax') {
            when {
                expression { return shouldRunStage('GreenMax') }
            }
			steps {
				script {
					def tests = [
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'GMax_GroupManagement'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'GMax_MessageSending'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'GMax_Notifications'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'GMax_MessageHistory'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'GMax_Queues'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'GMax_Account'],
					]
					for (test in tests) {
						catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
							runLibraryTest(test[0], test[1])
						}
					}
				}
			}
		}
		stage('Testing-Ollama') {
            when {
                expression { return shouldRunStage('Ollama') }
            }
			steps {
				script {
					def tests = [
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'OLLM_RequestsProcessing'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'OLLM_ModelsManagement'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'OLLM_WorkingWithBlob'],
					]
					for (test in tests) {
						catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
							runLibraryTest(test[0], test[1])
						}
					}
				}
			}
		}
		stage('Testing-HTTPClient') {
            when {
                expression { return shouldRunStage('HTTPClient') }
            }
			steps {
				script {
					def tests = [
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'HTTP_Initialization'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'HTTP_BodySet'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'HTTP_Settings'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'HTTP_HeadersSetting'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'HTTP_Authorization'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'HTTP_RequestProcessing'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'HTTP_ResponseReceiving'],
					]
					for (test in tests) {
						catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
							runLibraryTest(test[0], test[1])
						}
					}
				}
			}
		}
		stage('Testing-OpenAI') {
            when {
                expression { return shouldRunStage('OpenAI') }
            }
			steps {
				script {
					def tests = [
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'OAI_RequestsProcessing'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'OAI_Assistants'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'OAI_FileManagement'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'OAI_AudioProcessing'],
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'OAI_ModelsManagement'],
					]
					for (test in tests) {
						catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
							runLibraryTest(test[0], test[1])
						}
					}
				}
			}
		}
		stage('Testing-ReportPortal') {
            when {
                expression { return shouldRunStage('ReportPortal') }
            }
			steps {
				script {
					def tests = [
						['./src/en/OInt/tests/Modules/internal/OPI_TestsCLI.os', 'RPortal_Authorization'],
					]
					for (test in tests) {
						catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
							runLibraryTest(test[0], test[1])
						}
					}
				}
			}
		}

	}
	post{
		always{
			script {
                catchError() {   
				    runCommand('oscript ./ci/os/rp_stop.os "en"')
			    }
				withCredentials([gitUsernamePassword(credentialsId: 'gitmain', gitToolName: 'Default')]) {
					bat "git config user.email vitaly.the.alpaca@gmail.com"
					bat 'git config user.name "Vitaly the Alpaca (bot)"'
					bat "git config --global core.ignorecase true"
					bat "git add ."
					bat 'git commit -m "Test data update (Jenkins)"'
					bat "git push origin HEAD:main"
				}
			}
		}
	}
}

def shouldRunStage(stageName) {
    try {
        if (!env.STAGES_CONFIG) {
            echo "[WARN] STAGES_CONFIG not set. Assuming stage '${stageName}' is ENABLED."
            return true
        }
        def config = readJSON text: env.STAGES_CONFIG
        def value = config[stageName]
        if (value == null) {
            echo "[WARN] Stage '${stageName}' not found in config. Defaulting to DISABLED."
            return false
        }
        return value == true
    } catch (Exception e) {
        echo "[ERROR] Failed to parse STAGES_CONFIG: ${e.message}"
        echo "Raw config: ${env.STAGES_CONFIG}"
        // Решите: включать stage по умолчанию или нет?
        return false // или true — по вашему усмотрению
    }
}

def runLibraryTest(String configPath, String libraryName) {
    try {
        echo "Executing: 1testrunner -run \"${configPath}\" \"${libraryName}\""
        runCommand("1testrunner -run \"${configPath}\" \"${libraryName}\"")
        echo "Test ${libraryName} completed successfully"
    } catch (Exception e) {
        echo "ERROR in test ${libraryName}: ${e.getMessage()}"
        throw e 
    }
}