String GITHUB_REPOSITORY = 'lambda-bulk-asset-ingester'
String ECR_ACCOUNT_ID = '437795906767'
List<String> AWS_REGIONS = ['us-east-1']
String SLACK_NOTIFICATIONS_CHANNEL = '#integrations-alerts'
String QA_ACCOUNT_ID = '437795906767'
String QA_DEPLOYMENT_ROLE = 'prod-jenkins-aws-pipeline-agent'
String PROD_ACCOUNT_ID = '437795906767'
String PROD_DEPLOYMENT_ROLE = 'prod-jenkins-aws-pipeline-agent'

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

List<String> VULNERABILITIES_TO_IGNORE = []

pipeline {
    agent any

    options {
        ansiColor('xterm')
        disableConcurrentBuilds()
        skipDefaultCheckout()
        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).')
        booleanParam(name: 'BUILD_DOCKER', defaultValue: false, description: 'Whether or not to build Docker images.')
        booleanParam(name: 'FULL_REBUILD', defaultValue: false, description: 'Rebuild all lambda functions regardless of change detection.')
        booleanParam(name: 'FORCE_QA_DEPLOY', defaultValue: false, description: 'Deploy to QA even when not on master.')
    }

    triggers {
        issueCommentTrigger('.*retest this please.*')
    }

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

        stage('Compliance Checks') {
            steps {
                withModifiedFunctions(checkout: true) { functionName ->
                    echo "Running Compliance Checks for ${functionName}"
                    dir("lambda/${functionName}") {
                        complianceChecks()
                    }
                }
            }
        }

        stage('Validate Software Catalog Definition') {
            steps {
                withModifiedFunctions(checkout: true) { functionName ->
                    echo "Validating Software Catalog Definition for ${functionName}"
                    datadogSoftwareCatalogValidate(servicePath: "lambda/${functionName}")
                }
            }
        }

        stage('Unit Tests and Style Checks') {
            steps {
                withModifiedFunctions(checkout: true) { functionName ->
                    script {
                        echo "Running Unit Tests and Style Checks for ${functionName}"
                        dir("lambda/${functionName}") {
                            try {
                                sh "docker compose run --rm --build lint-and-test"
                            }
                            finally {
                                sh "docker compose down -v"
                            }
                        }
                    }
                }
            }
        }

        stage('Static Application Security Tests') {
            steps {
                withModifiedFunctions(checkout: true) { functionName ->
                    echo "Running Static App Security Tests for ${functionName}"
                    sastTests(projectDir: "lambda/${functionName}")
                }
            }
        }

        stage('Sonar Scan and Analysis') {
            agent any
            when {
                branch 'master'
            }
            steps {
                // Ensure workspace is checked out since skipDefaultCheckout() is set
                checkout scm
                script {
                    echo "Running Sonar scan for ${GITHUB_REPOSITORY}"
                    sonarScan project: GITHUB_REPOSITORY, language: 'py', exclusions: 'lambda/**/tests/**'
                }
            }
        }

        stage('Create a Release') {
            when {
                anyOf {
                    branch 'master'
                    // Manual toggle to force Docker build regardless of branch
                    expression { params.BUILD_DOCKER }
                    expression { (env.GITHUB_COMMENT ?: '') =~ 'build docker' }
                    expression { pullRequest?.labels?.contains('build docker') }
                }
            }
            steps {
                withModifiedFunctions(checkout: true) { functionName ->
                    echo "Building for ${functionName}"
                    dockerToEcr awsRegions: AWS_REGIONS,
                        ecrAccountId: ECR_ACCOUNT_ID,
                        imageName: "lambda-bulk-assets-ingester-${functionName.replaceAll('_', '-')}",
                        imageTag: env.GIT_COMMIT,
                        dockerBuildContext: "lambda/${functionName}",
                        dockerBuildFile: "lambda/${functionName}/Dockerfile",
                        additionalContexts: [
                            common: '../../common'
                        ]
                }
            }
        }

        stage('Deploy to QA') {
            when {
                anyOf {
                    branch 'master'
                    expression { params.FORCE_QA_DEPLOY }
                }
            }
            steps {
                // Need checkout to ensure fresh workspace per parallel branch
                withModifiedFunctions(checkout: true) { functionName ->
                    echo "Deploying to QA for ${functionName}"
                    dir("lambda/${functionName}") {
                        lambdaDeploy environment: 'qa',
                            awsRegions: AWS_REGIONS,
                            imageTag: env.GIT_COMMIT,
                            imageName: "lambda-bulk-assets-ingester-${functionName.replaceAll('_', '-')}",
                            ecrRegistryAccountId: ECR_ACCOUNT_ID,
                            awsDeploymentTargetAccountId: QA_ACCOUNT_ID,
                            awsDeploymentRoleName: QA_DEPLOYMENT_ROLE
                    }
                }
            }
        }

        stage('Scan Docker Images') {
            when {
                anyOf {
                    branch 'master'
                    // Manual toggle to force image scan even off master
                    expression { params.BUILD_DOCKER }
                    expression { (env.GITHUB_COMMENT ?: '') =~ 'build docker' }
                    expression { pullRequest?.labels?.contains('build docker') }
                }
            }
            steps {
                // Perform checkout so dockerScan has Dockerfile/context
                withModifiedFunctions(checkout: true) { functionName ->
                    echo "Scanning Docker Images for ${functionName}"
                    dir("lambda/${functionName}") {
                        dockerScan awsRegion: AWS_REGIONS[0],
                            ecrAccountId: ECR_ACCOUNT_ID,
                            imageName: "lambda-bulk-assets-ingester-${functionName.replaceAll('_', '-')}",
                            imageTag: env.GIT_COMMIT,
                            slackNotificationChannel: (env.BRANCH_NAME == 'master' ? SLACK_NOTIFICATIONS_CHANNEL : null),
                            failBuild: false
                    }
                }
            }
        }

        /* You can comment out PROD deploy stage for now to prevent accidental deployments
         * Remove these comment markers when ready to re-enable deployment to PROD.
        */
        stage('Deploy to PROD') {
            when {
                allOf {
                    branch 'master'
                    expression { params.DEPLOY_TO_PROD }
                }
            }
            steps {
                withModifiedFunctions(checkout: true) { functionName ->
                    echo "Deploying to PROD for ${functionName}"
                    dir("lambda/${functionName}") {
                        lambdaDeploy environment: 'prod',
                            awsRegions: AWS_REGIONS,
                            imageTag: env.GIT_COMMIT,
                            imageName: "lambda-bulk-assets-ingester-${functionName.replaceAll('_', '-')}",
                            ecrRegistryAccountId: ECR_ACCOUNT_ID,
                            awsDeploymentTargetAccountId: PROD_ACCOUNT_ID,
                            awsDeploymentRoleName: PROD_DEPLOYMENT_ROLE
                    }
                    datadogSoftwareCatalogPublish(servicePath: "lambda/${functionName}")
                }
            }
        }
    }

    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 withModifiedFunctions(Map args = [:], Closure steps) {
    parallel(getFunctionsToBuild().collectEntries { functionName ->
        return [
            (functionName): {
                node {
                    if (args.checkout?.toBoolean()) {
                        cleanWs()
                        def scmVars = checkout scm
                        // Set SCM vars as environment variables to replicate default checkout functionality
                        scmVars.each { k, v ->
                            env."${k}" = v
                        }
                    }
                    steps(functionName)
                }
            }
        ]
    })
}

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

    def lambdaFunctionName = params.LAMBDA_FUNCTION_NAME ?: null

    if (lambdaFunctionName) {
        this.@functionsToBuild = [lambdaFunctionName]
    } else {
        node {
            def scmVars = checkout scm
            def lambdaDirectories = findFiles(glob: 'lambda/**/Dockerfile')
            // Derive function names from Dockerfile paths (expect lambda/<function>/Dockerfile)
            // Only include direct children of lambda/ directory, not nested subdirectories
            def allLambdaFunctionNames = lambdaDirectories.collect { it.path.replaceFirst(/^lambda\//,'').replace('/Dockerfile','') }
                .findAll { !it.contains('/') }  // Exclude paths with slashes (nested directories)

            // Default: use shared library change detection
            def modified = getModifiedFunctions branchName: scmVars.BRANCH_NAME,
                previousSuccessfulCommit: scmVars.GIT_PREVIOUS_SUCCESSFUL_COMMIT,
                lambdaDirectories: lambdaDirectories

            def forceFull = params.FULL_REBUILD
            def changedPaths = []
            if (scmVars.GIT_PREVIOUS_SUCCESSFUL_COMMIT) {
                changedPaths = sh(script: "git diff --name-only ${scmVars.GIT_PREVIOUS_SUCCESSFUL_COMMIT} ${scmVars.GIT_COMMIT} || true", returnStdout: true).trim().split('\n')
            }
            // Trigger full rebuild if common code or Jenkinsfile changed
            def hasCommonChange = changedPaths.any { it.startsWith('common/') }
            def hasPipelineChange = changedPaths.contains('Jenkinsfile')

            if (forceFull || hasCommonChange || hasPipelineChange) {
                echo "Full rebuild triggered (forceFull=${forceFull}, commonChange=${hasCommonChange}, pipelineChange=${hasPipelineChange})"
                this.@functionsToBuild = allLambdaFunctionNames
            } else {
                this.@functionsToBuild = modified
            }
        }
    }

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

    return this.@functionsToBuild
}
