string GITHUB_REPOSITORY = 'insights-cross-app-data-tests'

def TestOptions = [
    'INSIGHTS_PLAYLIST_FRESHNESS',
    'INSIGHTS_PLAYLIST_UPDATE',
    'INSIGHTS_PLAYLISTS_EXISTENCE',
    'INSIGHTS_NMF_FRESHNESS',
    'INSIGHTS_PLAYLISTS_COMPLETENESS',
    'INSIGHTS_PLAYLISTS_COMPLETENESS_PRIORITY',
    'INSIGHTS_PLAYLISTS_METRICS_PRIORITY',
    'INSIGHTS_PLAYLISTS_METRICS_HOURLY',
    'INSIGHTS_PLAYLISTS_METRICS_AM',
    'INSIGHTS_PLAYLISTS_BRANDS_PRIORITY',
    'INSIGHTS_PLAYLISTS_BRANDS_HOURLY',
    'INSIGHTS_PLAYLISTS_BRANDS_AM'
]

pipeline {
    agent any

    parameters {
        string(name: 'ENV', defaultValue: 'prod', description: 'Environment to run the tests against. Example: qa, prod')
        choice(choices: TestOptions, description: 'Select which tests to run', name: 'TEST_OPTION')
        string(name: 'SHARED_LIBRARIES_VERSION', defaultValue: 'master', description: 'The version of the Jenkins shared libraries to use. Can be a branch, tag or Git revision.')
        string(name: 'FRESHNESS_TIMEOUT', defaultValue: '15', description: 'Set timeout in minutes for playlist freshness verification')
        string(name: 'PLAYLISTS', defaultValue: '',
        description: 'List of playlists. Example: PLAYLIST_ID_1,PLAYLIST_ID_2')
        string(name: 'MARKET', defaultValue: '',
        description: 'For INSIGHTS_NMF_FRESHNESS test set market code. Example: AU')
        string(name: 'PLAYLIST_SAMPLE_SIZE', defaultValue: '100',
                description: 'For INSIGHTS_PLAYLISTS_METRICS_*/INSIGHTS_PLAYLISTS_BRANDS_* tests set count of items to check.')
        string(name: 'NO_FAIL', defaultValue: 'false',
                description: 'For INSIGHTS_NMF_FRESHNESS test, skip instead of fail when market is not received yet.')
    }

    environment {
        ENV = "${params.ENV}"
        FRESHNESS_TIMEOUT = "${params.FRESHNESS_TIMEOUT}"
        PLAYLISTS = "${params.PLAYLISTS}"
        MARKET = "${params.MARKET}"
        PLAYLIST_SAMPLE_SIZE = "${params.PLAYLIST_SAMPLE_SIZE}"
        NO_FAIL = "${params.NO_FAIL}"
    }

    triggers {
        parameterizedCron('''
            0 23 * * 4 %TEST_OPTION=INSIGHTS_NMF_FRESHNESS;NO_FAIL=true
            0 13 * * 5 %TEST_OPTION=INSIGHTS_NMF_FRESHNESS
            TZ=Europe/London
            0 7-18 * * 1-5 %TEST_OPTION=INSIGHTS_PLAYLISTS_EXISTENCE
        ''')
    }

    stages {
        stage('Set Build Name') {
            steps {
                script {
                    currentBuild.displayName = "#${BUILD_NUMBER} - ${params.TEST_OPTION}"
                }
            }
        }

        stage('Load Shared Libraries') {
            steps {
                library "jenkins-global-libraries@${params.SHARED_LIBRARIES_VERSION}"
            }
        }

        stage('Install Dependencies') {
            steps {
                script {
                    // Create and activate a virtual environment
                    sh '''
                        python3 -m venv venv
                        . venv/bin/activate
                        pip install --upgrade pip
                        pip install -r requirements.txt
                    '''
                }
            }
        }

        stage('Run Tests') {
            when {
                anyOf {
                    branch 'master'
                    expression { env.BRANCH_NAME == null || env.BRANCH_NAME == 'null' }
                }
            }
            steps {
                script {
                    withCredentials([aws(credentialsId: 'cucumber-tests')]) {
                        sh '''#!/bin/bash
                set -e
                . venv/bin/activate

                TEST_OPTION=${TEST_OPTION}
                PYTEST_BASE_CMD="pytest -s --rootdir=app"
                COMMON_ARGS="--report=test_results/report.html --split-report --template=html1/index.html"

                case "$TEST_OPTION" in
                  "INSIGHTS_PLAYLIST_FRESHNESS")
                    export ENV=qa
                    $PYTEST_BASE_CMD app/src/tests/insights/playlist_freshness/test_spotify_playlist_freshness.py -n auto $COMMON_ARGS
                    ;;
                  "INSIGHTS_PLAYLISTS_EXISTENCE")
                    $PYTEST_BASE_CMD app/src/tests/insights/playlist_freshness/test_playlists_existence.py $COMMON_ARGS
                    ;;
                  "INSIGHTS_PLAYLISTS_COMPLETENESS")
                    $PYTEST_BASE_CMD app/src/tests/insights/playlist_freshness/test_playlists_completeness.py $COMMON_ARGS
                    ;;
                  "INSIGHTS_PLAYLISTS_COMPLETENESS_PRIORITY")
                    export PRIORITY_PLAYLISTS_ONLY=true
                    $PYTEST_BASE_CMD app/src/tests/insights/playlist_freshness/test_playlists_completeness.py $COMMON_ARGS
                    ;;
                  "INSIGHTS_PLAYLIST_UPDATE")
                    export ENV=qa
                    $PYTEST_BASE_CMD app/src/tests/insights/playlist_freshness/test_spotify_playlist_update.py $COMMON_ARGS
                    ;;
                  "INSIGHTS_NMF_FRESHNESS")
                    $PYTEST_BASE_CMD app/src/tests/insights/playlist_freshness/test_nmf_playlist_freshness.py $COMMON_ARGS
                    ;;
                  "INSIGHTS_PLAYLISTS_METRICS_PRIORITY")
                    export PLAYLIST_TYPE=PRIORITY
                    $PYTEST_BASE_CMD app/src/tests/insights/playlist_freshness/test_playlists_metrics.py $COMMON_ARGS
                    ;;
                  "INSIGHTS_PLAYLISTS_METRICS_HOURLY")
                    export PLAYLIST_TYPE=HOURLY
                    $PYTEST_BASE_CMD app/src/tests/insights/playlist_freshness/test_playlists_metrics.py $COMMON_ARGS
                    ;;
                  "INSIGHTS_PLAYLISTS_METRICS_AM")
                    export PLAYLIST_TYPE=AM
                    $PYTEST_BASE_CMD app/src/tests/insights/playlist_freshness/test_playlists_metrics.py $COMMON_ARGS
                    ;;
                  "INSIGHTS_PLAYLISTS_BRANDS_PRIORITY")
                    export PLAYLIST_TYPE=PRIORITY
                    $PYTEST_BASE_CMD app/src/tests/insights/playlist_freshness/test_track_company_brand.py $COMMON_ARGS
                    ;;
                  "INSIGHTS_PLAYLISTS_BRANDS_HOURLY")
                    export PLAYLIST_TYPE=HOURLY
                    $PYTEST_BASE_CMD app/src/tests/insights/playlist_freshness/test_track_company_brand.py $COMMON_ARGS
                    ;;
                  "INSIGHTS_PLAYLISTS_BRANDS_AM")
                    export PLAYLIST_TYPE=AM
                    $PYTEST_BASE_CMD app/src/tests/insights/playlist_freshness/test_track_company_brand.py $COMMON_ARGS
                    ;;
                  *)
                    echo "Invalid test option: $TEST_OPTION"
                    exit 1
                    ;;
                esac
                        '''
                    }
                }
            }
            post {
                always {
                    archiveArtifacts artifacts: 'test_results/report.html', allowEmptyArchive: true
                    publishHTML(target: [
                        allowMissing: true,
                        alwaysLinkToLastBuild: true,
                        keepAll: true,
                        reportDir: 'test_results',
                        reportFiles: 'report.html',
                        reportName: 'HTML Report',
                        reportTitles: ''
                    ])
                }
            }
        }

        stage('Zip Test Results') {
            steps {
                script {
                    // Check if the test_results folder exists and zip its contents if it does
                    if (fileExists('test_results')) {
                        sh 'zip -r test_results.zip test_results/'
                    } else {
                        echo 'test_results folder does not exist, skipping zip step.'
                    }
                }
            }
        }

        stage('Archive Artifacts') {
            steps {
                script {
                    // Archive the zip file if it exists
                    if (fileExists('test_results.zip')) {
                        archiveArtifacts artifacts: 'test_results.zip', allowEmptyArchive: true
                    } else {
                        echo 'test_results.zip file does not exist, skipping archive step.'
                    }

                    // Archive the HTML report if it exists
                    if (fileExists('test_results/report.html')) {
                        archiveArtifacts artifacts: 'test_results/report.html', allowEmptyArchive: true
                    } else {
                        echo 'test_results/report.html file does not exist, skipping archive step.'
                    }
                }
            }
        }
    }

post {
        always {
            echo 'Cleaning up...'
            deleteDir()
        }

        success {
            echo 'Tests succeeded!'
        }

        failure {
            echo 'Tests failed!'
            archiveArtifacts artifacts: 'test_results/report.html', allowEmptyArchive: true
            script {
                if (params.TEST_OPTION == 'INSIGHTS_NMF_FRESHNESS') {
                    slackSend(
                        color: 'danger',
                        channel: '#insights-private',
                        message: "NMF Playlist Freshness tests failed! ${env.JOB_NAME} - #${env.BUILD_NUMBER} (<${env.BUILD_URL}|Open>)"
                    )
                }
                if (params.TEST_OPTION == 'INSIGHTS_PLAYLISTS_EXISTENCE') {
                    slackSend(
                        color: 'danger',
                        channel: '#insights-private',
                        message: "Playlists Existence tests failed! ${env.JOB_NAME} - #${env.BUILD_NUMBER} (<${env.BUILD_URL}|Open>)"
                    )
                }
            }
        }
    }
}
