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

def runLibraryTest(String libraryName, String configPath) {
    catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {   
        script {
            runCommand("\"C:/Program Files/1cv8/8.3.18.1208/bin/1cv8c.exe\" /IBConnectionString \"Srvr=\"\"DEVSRV\"\";Ref=\"\"OpenIntegrations\"\";\" /C\"RunUnitTests=${configPath}\"")
        
            timeout(time: 60, unit: 'MINUTES') {
                waitUntil {
                    fileExists "./test_results/${libraryName}.code"
                }
            }

            if (fileExists("./test_results/${libraryName}.report")) {
                def reportContent = readFile("./test_results/${libraryName}.report")
                echo "=== ${libraryName} report content ==="
                echo reportContent
                echo "=========================="
            } else {
                echo "WARNING: ${libraryName}.report file not found"
            }

            def exitCode = readFile("./test_results/${libraryName}.code").trim().replaceAll("[^0-9]", "")
            echo "Exit code for ${libraryName}: ${exitCode}"
            if (exitCode != "0") {
                error "Tests ${libraryName} failed with exit code: ${exitCode}"
            }
        }
    }
}

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 — по вашему усмотрению
    }
}


pipeline {
	agent {
		label 'windows'
	}
	stages {

		stage('Prepare Test Results Directory') {
            steps {
                script {
                    runCommand '''
                        if exist ".\\test_results" (
                            rmdir /s /q ".\\test_results"
                        )
                        mkdir ".\\test_results"
                    '''
                }
            }
        }

		stage('Create ReportPortal launch'){
				steps{
					bat encoding: 'UTF-8', script:'chcp 65001 & oscript ./ci/os/rp_start.os "1C:Enterprise"'
				}
		}

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

		stage('Testing-BuildCheck') {
            when {
                expression { return shouldRunStage('BuildCheck') }
            }
			steps {
				script {
					def tests = [
						['BuildCheck', './service/yaxunit_conf/ru/BuildCheck.json'],
					]
					for (test in tests) {
							runLibraryTest(test[0], test[1])
					}
				}
			}
		}
		stage('Testing-Telegram') {
            when {
                expression { return shouldRunStage('Telegram') }
            }
			steps {
				script {
					def tests = [
						['Telegram', './service/yaxunit_conf/ru/Telegram.json'],
					]
					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 = [
						['VK', './service/yaxunit_conf/ru/VK.json'],
					]
					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 = [
						['Viber', './service/yaxunit_conf/ru/Viber.json'],
					]
					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 = [
						['Twitter', './service/yaxunit_conf/ru/Twitter.json'],
					]
					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 = [
						['FTP', './service/yaxunit_conf/ru/FTP.json'],
					]
					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 = [
						['SSH', './service/yaxunit_conf/ru/SSH.json'],
					]
					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 = [
						['SFTP', './service/yaxunit_conf/ru/SFTP.json'],
					]
					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 = [
						['PostgreSQL', './service/yaxunit_conf/ru/PostgreSQL.json'],
					]
					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 = [
						['MySQL', './service/yaxunit_conf/ru/MySQL.json'],
					]
					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 = [
						['MSSQL', './service/yaxunit_conf/ru/MSSQL.json'],
					]
					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 = [
						['SQLite', './service/yaxunit_conf/ru/SQLite.json'],
					]
					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 = [
						['MongoDB', './service/yaxunit_conf/ru/MongoDB.json'],
					]
					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 = [
						['RCON', './service/yaxunit_conf/ru/RCON.json'],
					]
					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 = [
						['YandexDisk', './service/yaxunit_conf/ru/YandexDisk.json'],
					]
					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 = [
						['GoogleWorkspace', './service/yaxunit_conf/ru/GoogleWorkspace.json'],
					]
					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 = [
						['GoogleCalendar', './service/yaxunit_conf/ru/GoogleCalendar.json'],
					]
					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 = [
						['GoogleDrive', './service/yaxunit_conf/ru/GoogleDrive.json'],
					]
					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 = [
						['GoogleSheets', './service/yaxunit_conf/ru/GoogleSheets.json'],
					]
					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 = [
						['Notion', './service/yaxunit_conf/ru/Notion.json'],
					]
					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 = [
						['Slack', './service/yaxunit_conf/ru/Slack.json'],
					]
					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 = [
						['Airtable', './service/yaxunit_conf/ru/Airtable.json'],
					]
					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 = [
						['Dropbox', './service/yaxunit_conf/ru/Dropbox.json'],
					]
					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 = [
						['Bitrix24', './service/yaxunit_conf/ru/Bitrix24.json'],
					]
					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 = [
						['VkTeams', './service/yaxunit_conf/ru/VkTeams.json'],
					]
					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 = [
						['Neocities', './service/yaxunit_conf/ru/Neocities.json'],
					]
					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 = [
						['CDEK', './service/yaxunit_conf/ru/CDEK.json'],
					]
					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 = [
						['YandexMetrika', './service/yaxunit_conf/ru/YandexMetrika.json'],
					]
					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 = [
						['S3', './service/yaxunit_conf/ru/S3.json'],
					]
					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 = [
						['TCP', './service/yaxunit_conf/ru/TCP.json'],
					]
					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 = [
						['GreenAPI', './service/yaxunit_conf/ru/GreenAPI.json'],
					]
					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 = [
						['GreenMax', './service/yaxunit_conf/ru/GreenMax.json'],
					]
					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 = [
						['Ollama', './service/yaxunit_conf/ru/Ollama.json'],
					]
					for (test in tests) {
						catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
							runLibraryTest(test[0], test[1])
						}
					}
				}
			}
		}
		stage('Testing-HTTPКлиент') {
            when {
                expression { return shouldRunStage('HTTPКлиент') }
            }
			steps {
				script {
					def tests = [
						['HTTPКлиент', './service/yaxunit_conf/ru/HTTPКлиент.json'],
					]
					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 = [
						['OpenAI', './service/yaxunit_conf/ru/OpenAI.json'],
					]
					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 = [
						['ReportPortal', './service/yaxunit_conf/ru/ReportPortal.json'],
					]
					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 "ru"')
			    }	
			}
		}
	}
}