package com.sonymusic
import org.codehaus.groovy.runtime.GStringImpl
import jenkins.model.Jenkins
import com.cloudbees.groovy.cps.NonCPS

class Utils implements Serializable {
    def steps

    Utils(steps) {
        this.steps = steps
    }

    // Validate each parameter against the rules and set default values for optional parameters
    static def validateParams(String globalVarName, Map params, Map<String, Map> validationRules) {
        def validatedParams = [:]
        def inputParams = params ?: [:]

        inputParams.each { key, value ->
            if (!validationRules.containsKey(key)) {
                throw new IllegalArgumentException("$globalVarName: Unknown parameter: '$key'.")
            }
        }

        validationRules.each { key, rule ->
            if( !rule.type) {
                throw new IllegalArgumentException("$globalVarName: The parameter validation rule for: '$key', does not specify a 'type'.")
            }

            if( rule.itemType && rule.type != List ){
                throw new IllegalArgumentException( "$globalVarName: The parameter validation rule for: '$key', defines a 'itemType', but the 'type' is not a List.")
            }

            def value = inputParams.containsKey(key) ? inputParams[key] : rule.defaultValue

            if (value == null && rule.required) {
                throw new IllegalArgumentException("$globalVarName: Missing required parameter: '$key'.")
            } else if (value != null && !isTypeValid(value, rule.type, rule.itemType)) {
                throw new IllegalArgumentException("$globalVarName: Invalid type for parameter '$key'. Expected: ${rule.type}, Actual: ${value.getClass().getSimpleName()}.")
            }

            validatedParams[key] = value
        }

        return validatedParams
    }

    // Check if the value's type matches the expected type
    static def isTypeValid(value, Class type, Class itemType = null) {
        if(type == String && value instanceof GStringImpl){
            return true
        }

        if( !type.isAssignableFrom(value.getClass())){
            return false
        }

        if (type == List && itemType) {
            return value.every { isTypeValid(it, itemType) }
        }

        return true;
    }

    static def stripTrailingSlash(String path) {
        return path.replaceAll(/\/$/, '')
    }

    static def ensureTrailingSlash(String path) {
        return path.endsWith('/') ? path : path + "/"
    }

    static def stripPrefix(String str, String prefix) {
        if (str.startsWith(prefix)) {
            return str.substring(prefix.length())
        }
        return str
    }

    // Get value from AWS Secrets Manager
    def getSecretValue(String secretId, String region = 'us-east-1') {
        def secretValue = steps.sh label: 'Get Secret Value', returnStdout: true, script: """
                aws secretsmanager get-secret-value --secret-id $secretId --region $region --query SecretString --output text
            """
        return secretValue.trim()
    }
}
