import groovy.transform.Field

@Field String GITHUB_REPOSITORY = 'lambda-fan-response'
@Field String ECR_ACCOUNT_ID = '086679231553'
@Field List<String> AWS_REGIONS = ['us-east-1']
@Field String SLACK_NOTIFICATIONS_CHANNEL = '#kafka-data-highway-alerts'
@Field String QA_ACCOUNT_ID = '437795906767'
@Field String QA_DEPLOYMENT_ROLE = 'prod-jenkins-aws-pipeline-agent'
@Field String QA_FANSIFTER_ACCOUNT_ID = '285943604611'
@Field String QA_FANSIFTER_DEPLOYMENT_ROLE = 'qa-jenkins-pipeline-deploy-role'
@Field String PROD_ACCOUNT_ID = '437795906767'
@Field String PROD_DEPLOYMENT_ROLE = 'prod-jenkins-aws-pipeline-agent'
@Field String PROD_FANSIFTER_ACCOUNT_ID = '737325105821'
@Field String PROD_FANSIFTER_DEPLOYMENT_ROLE = 'prod-jenkins-pipeline-deploy-role'

@groovy.transform.Field
List<String> functionsToBuild = null

@groovy.transform.Field
List<Map<String, List<String>>> functionsToDeploy = null

DEPLOY_CONFIG = [
    'smf-fan-response': [
        [name: 'smf-fan-response', accountSet: 'default']
    ],
    'fan-response-authorizer': [
        [name: 'smf-fan-response-authorizer', accountSet: 'default']
    ],
    'fan-campaign': [
        [name: 'fan-campaign', accountSet: 'default']
    ],
    'fan-triggered-send-definitions': [
        [name: 'fan-triggered-send-definitions', accountSet: 'default']
    ],
    'fan-triggered-sends': [
        [name: 'fan-triggered-sends', accountSet: 'fansifter']
    ],
    'fan-vendor-weekly-deletions-emails': [
        [name: 'fan-vendor-weekly-deletions-emails', accountSet: 'default']
    ],
]

List<String> VULNERABILITIES_TO_IGNORE = [
    'CVE-2025-22871'  // pkg:generic/aws-lambda-rie?go_toolchain
]


pipeline {
    agent any

    options {
        ansiColor('xterm')
        disableConcurrentBuilds()
        timestamps()
    }

    parameters {
        booleanParam(name: 'DEPLOY_TO_PROD', defaultValue: true, description: 'Whether or not to deploy to prod.')
        string(name: 'LAMBDA_FUNCTION_NAME', defaultValue: '', description: 'Name of the Lambda function to build and deploy')
        string(name: 'SHARED_LIBRARIES_VERSION', defaultValue: 'master', description: 'The version of the Jenkins shared libraries to use. Can be a branch, tag, Git revision or PR ref (e.g. pull/PR_NUMBER/merge).')
    }

    triggers {
        issueCommentTrigger('.*retest this please.*')
    }
    
    stages {
        stage('Load Shared Libraries') {
            steps {
                library "jenkins-global-libraries@${params.SHARED_LIBRARIES_VERSION}"
            }
        }

        stage('Compliance Checks') {
            steps {
                script {
                    parallel(getFunctionsToBuild().collectEntries { functionName ->
                        return [
                            (functionName): {
                                echo "Running Compliance Checks for ${functionName}"
                                dir("lambda/${functionName}") {
                                    complianceChecks()
                                }
                            }
                        ]
                    })
                }
            }
        }

        stage('Validate Software Catalog Definitions') {
            steps {
                script {
                    parallel(getFunctionsToBuild().collectEntries { functionName ->
                        return [
                            (functionName): {
                                echo "Validating Software Catalog definition for ${functionName}"
                                datadogSoftwareCatalogValidate(servicePath: "lambda/${functionName}")
                            }
                        ]
                    })
                }
            }
        }

        stage('Unit Tests and Style Checks') {
            steps {
                script {
                    parallel(getFunctionsToBuild().collectEntries { functionName ->
                        return [
                            (functionName): {
                                echo "Running Unit Tests and Style Checks for ${functionName}"
                                dir("lambda/${functionName}") {
                                    sh "docker compose run --rm --build lint-and-test"
                                }
                            }
                        ]
                    })
                }
            }
        }

        stage('Static Application Security Tests') {
            steps {
                script {
                    parallel(getFunctionsToBuild().collectEntries { functionName ->
                        return [
                            (functionName): {
                                echo "Running Static App Security Tests for ${functionName}"
                                sastTests(projectDir: "lambda/${functionName}")
                            }
                        ]
                    })
                }
            }
        }

        stage('Sonar Scan and Analysis') {
            when {
                branch 'master'
            }
            steps {
                script {
                    echo "Running Sonar scan for ${GITHUB_REPOSITORY}"
                    sonarScan project: GITHUB_REPOSITORY, language: 'py'
                }
            }
        }

        stage('Create a Release') {
            when {
                anyOf {
                    branch 'master'
                    expression { env.GITHUB_COMMENT =~ 'build docker' }
                }
            }
            steps {
                script {
                    parallel(getFunctionsToBuild().collectEntries { functionName ->
                        return [
                            (functionName): {
                                echo "Building for ${functionName}"
                                dockerToEcr awsRegions: AWS_REGIONS,
                                    ecrAccountId: ECR_ACCOUNT_ID,
                                    imageName: "lambda-${functionName.replaceAll('_', '-')}",
                                    imageTag: env.GIT_COMMIT,
                                    dockerBuildContext: "lambda/${functionName}",
                                    dockerBuildFile: "lambda/${functionName}/Dockerfile"
                            }
                        ]
                    })
                }
            }
        }

        stage('Deploy to QA') {
            when {
                branch 'master'
            }
            steps {
                script {
                    parallel(getFunctionsToDeploy('qa').collectEntries { lambdaToDeploy ->
                        return [
                            (lambdaToDeploy['functionName']): {
                                echo "Deploying to QA for ${lambdaToDeploy['functionName']}"
                                dir(lambdaToDeploy['dir']) {
                                    lambdaDeploy functionName: lambdaToDeploy['functionName'],
                                        awsRegions: AWS_REGIONS,
                                        imageTag: env.GIT_COMMIT,
                                        imageName: lambdaToDeploy['imageName'],
                                        ecrRegistryAccountId: ECR_ACCOUNT_ID,
                                        awsDeploymentTargetAccountId: lambdaToDeploy['awsDeploymentTargetAccountId'],
                                        awsDeploymentRoleName: lambdaToDeploy['awsDeploymentRoleName']
                                }
                            }
                        ]
                    })
                }
            }
        }

        stage('Integration Tests') {
            when {
                branch 'master'
            }
            steps {
                script {
                    parallel(getFunctionsToDeploy('qa').collectEntries { lambdaToDeploy ->
                        return [
                            (lambdaToDeploy['functionName']): {
                                dir(lambdaToDeploy['dir']) {
                                    if (fileExists('integration-test.sh')) {
                                        echo "Running Integration Tests for ${lambdaToDeploy['functionName']}"
                                        withAWS(role: 'qa-fan-response-api-integration-tests-role', roleAccount: '437795906767', roleSessionName: 'lambda-integration-tests', useNode: true) {
                                            sh '''
                                                chmod +x ./integration-test.sh
                                                docker compose run --rm --build integration-test
                                            '''
                                        }
                                    } else {
                                        echo "Skipping since 'integration-test.sh' not found for ${lambdaToDeploy['functionName']}."
                                    }
                                }
                            }
                        ]
                    })
                }
            }
        }

        stage('Scan Docker Images') {
            when {
                anyOf {
                    branch 'master'
                    expression { env.GITHUB_COMMENT =~ 'build docker' }
                }
            }
            steps {
                script {
                    parallel(getFunctionsToBuild().collectEntries { functionName ->
                        return [
                            (functionName): {
                                echo "Scanning Docker Images for ${functionName}"
                                dir("lambda/${functionName}") {
                                    dockerScan awsRegion: AWS_REGIONS[0],
                                        ecrAccountId: ECR_ACCOUNT_ID,
                                        imageName: "lambda-${functionName.replaceAll('_', '-')}",
                                        imageTag: env.GIT_COMMIT,
                                        vulnerabilitiesToIgnore: VULNERABILITIES_TO_IGNORE
                                }
                            }
                        ]
                    })
                }
            }
        }

        stage('Deploy to PROD') {
            when {
                allOf {
                    branch 'master'
                    expression { return params.DEPLOY_TO_PROD }
                }
            }
            steps {
                script {
                    parallel(getFunctionsToDeploy('prod').collectEntries { lambdaToDeploy ->
                        return [
                            (lambdaToDeploy['functionName']): {
                                echo "Deploying to PROD for ${lambdaToDeploy['functionName']}"
                                dir(lambdaToDeploy['dir']) {
                                    lambdaDeploy functionName: lambdaToDeploy['functionName'],
                                        awsRegions: AWS_REGIONS,
                                        imageTag: env.GIT_COMMIT,
                                        imageName: lambdaToDeploy['imageName'],
                                        ecrRegistryAccountId: ECR_ACCOUNT_ID,
                                        awsDeploymentTargetAccountId: lambdaToDeploy['awsDeploymentTargetAccountId'],
                                        awsDeploymentRoleName: lambdaToDeploy['awsDeploymentRoleName']
                                        datadogSoftwareCatalogPublish()
                                }
                            }
                        ]
                    })
                }
            }
        }
    }

    post {
        regression {
            script {
                if (env.BRANCH_NAME == 'master') {
                    slackNotify channel: SLACK_NOTIFICATIONS_CHANNEL
                }
            }
        }
        fixed {
            script {
                if (env.BRANCH_NAME == 'master') {
                    slackNotify channel: SLACK_NOTIFICATIONS_CHANNEL
                }
            }
        }
        cleanup {
            cleanWs()
        }
    }
}

def getFunctionsToBuild() {
    if (this.@functionsToBuild != null) {
        return this.@functionsToBuild
    }

    def lambdaFunctionName = params.LAMBDA_FUNCTION_NAME ?: null

    if (lambdaFunctionName) {
        this.@functionsToBuild = [lambdaFunctionName]
    } else {
        def lambdaDirectories = findFiles(glob: '**/Dockerfile')
        this.@functionsToBuild = getModifiedFunctions branchName: env.BRANCH_NAME,
            previousSuccessfulCommit: env.GIT_PREVIOUS_SUCCESSFUL_COMMIT,
            lambdaDirectories: lambdaDirectories
    }

    if (this.@functionsToBuild) {
        currentBuild.description = this.@functionsToBuild.join('<br>')
    }

    return this.@functionsToBuild
}

def getFunctionsToDeploy(String environment) {
    def lambdaFunctionName = params.LAMBDA_FUNCTION_NAME ?: null
    println "Lambda function name: ${lambdaFunctionName}"

    if (lambdaFunctionName) {
        this.@functionsToDeploy = getLambdasToDeploy(environment, lambdaFunctionName)
    } else {
        def lambdaDirectories = findFiles(glob: '**/Dockerfile')
        println "Lambda directories: ${lambdaDirectories}"
        this.@functionsToBuild = getModifiedFunctions branchName: env.BRANCH_NAME,
            previousSuccessfulCommit: env.GIT_PREVIOUS_SUCCESSFUL_COMMIT,
            lambdaDirectories: lambdaDirectories
        println "Functions to build: ${this.@functionsToBuild}"
        this.@functionsToDeploy = []
        for (functionName in this.@functionsToBuild) {
            this.@functionsToDeploy.addAll(getLambdasToDeploy(environment, functionName))
        }
    }
    println "Functions to deploy: ${this.@functionsToDeploy}"
    if (this.@functionsToDeploy) {
        currentBuild.description = this.@functionsToDeploy.collect {it['functionName']} .join('<br>')
    }

    return this.@functionsToDeploy
}

def getLambdasToDeploy(String env, String functionName) {
    def result = []
    println "Getting config for ${functionName}"
    for (lambdaConfig in DEPLOY_CONFIG[functionName]) {
        println "Adding ${lambdaConfig.name} lambda"
        def accountId, roleName
        if (lambdaConfig.accountSet == 'fansifter') {
            accountId = (env == 'qa') ? QA_FANSIFTER_ACCOUNT_ID : PROD_FANSIFTER_ACCOUNT_ID
            roleName = (env == 'qa') ? QA_FANSIFTER_DEPLOYMENT_ROLE : PROD_FANSIFTER_DEPLOYMENT_ROLE
        } else {
            accountId = (env == 'qa') ? QA_ACCOUNT_ID : PROD_ACCOUNT_ID
            roleName = (env == 'qa') ? QA_DEPLOYMENT_ROLE : PROD_DEPLOYMENT_ROLE
        }
        result.add([
            dir: "lambda/${functionName}",
            functionName: "${env}-lambda-${lambdaConfig.name}",
            imageName: "lambda-${functionName.replaceAll('_', '-')}",
            awsDeploymentTargetAccountId: accountId,
            awsDeploymentRoleName: roleName
        ])
    }
    println "Lambdas to deploy: ${result}"
    return result
}
