use std
use ../sops/lib.nu *
use ../kms/lib.nu *
use ../utils/error.nu throw-error
use ../utils/interface.nu _print
use ../utils/interface.nu _ansi

export def get_secret_provider []: nothing -> string {
    if $env.PROVISIONING_SECRET_PROVIDER? != null {
        return $env.PROVISIONING_SECRET_PROVIDER
    }
    
    # Default to sops for backward compatibility
    if $env.PROVISIONING_USE_SOPS? != null {
        return "sops"
    }
    
    if $env.PROVISIONING_USE_KMS? != null {
        return "kms"
    }
    
    return "sops"
}

export def on_secrets [
    task: string            
    source_path: string     
    output_path?: string    
    ...args                 
    --check (-c)            
    --error_exit
    --quiet
]: nothing -> string {
    let provider = (get_secret_provider)
    
    match $provider {
        "sops" => {
            if $quiet {
                on_sops $task $source_path $output_path --quiet
            } else {
                on_sops $task $source_path $output_path
            }
        },
        "kms" => {
            if $quiet {
                on_kms $task $source_path $output_path --quiet
            } else {
                on_kms $task $source_path $output_path
            }
        },
        _ => {
            (throw-error $"🛑 Unknown secret provider" $"(_ansi red)($provider)(_ansi reset) - supported: sops, kms"
                "on_secrets" --span (metadata $provider).span)
        }
    }
}

export def encrypt_secret [
    source_path: string     
    output_path?: string    
    --quiet
]: nothing -> string {
    on_secrets "encrypt" $source_path $output_path --quiet=$quiet
}

export def decrypt_secret [
    source_path: string     
    output_path?: string    
    --quiet
]: nothing -> string {
    on_secrets "decrypt" $source_path $output_path --quiet=$quiet
}

export def is_encrypted_file [
    target: string
]: nothing -> bool {
    let provider = (get_secret_provider)
    
    match $provider {
        "sops" => {
            is_sops_file $target
        },
        "kms" => {
            is_kms_file $target
        },
        _ => {
            false
        }
    }
}

export def decode_secret_file [
    source: string
    target: string
    quiet: bool
]: nothing -> nothing {
    let provider = (get_secret_provider)
    
    match $provider {
        "sops" => {
            decode_sops_file $source $target $quiet
        },
        "kms" => {
            decode_kms_file $source $target $quiet
        },
        _ => {
            if not $quiet {
                _print $"🛑 Unknown secret provider ($provider)"
            }
        }
    }
}

export def generate_secret_file [
    source_path: string
    target_path: string
    quiet: bool
]: nothing -> bool {
    let provider = (get_secret_provider)
    
    match $provider {
        "sops" => {
            generate_sops_file $source_path $target_path $quiet
        },
        "kms" => {
            let result = (on_kms "encrypt"  $source_path --error_exit)
            if $result == "" {
                _print $"🛑 File ($source_path) not KMS encrypted"
                return false
            }
            $result | save -f $target_path
            if not $quiet {
                _print $"($source_path) generated for 'KMS' "
            }
            return  true
        },
        _ => {
            if not $quiet {
                _print $"🛑 Unknown secret provider ($provider)"
            }
            return false
        }
    }
}

export def setup_secret_env []: nothing -> nothing {
    let provider = (get_secret_provider)
    
    match $provider {
        "sops" => {
            # Set up SOPS environment variables
            if $env.CURRENT_INFRA_PATH != null and $env.CURRENT_INFRA_PATH != "" {
                if $env.CURRENT_KLOUD_PATH? != null {
                    $env.PROVISIONING_SOPS = (get_def_sops $env.CURRENT_KLOUD_PATH)
                    $env.PROVISIONING_KAGE = (get_def_age $env.CURRENT_KLOUD_PATH)
                } else {
                    $env.PROVISIONING_SOPS = (get_def_sops $env.CURRENT_INFRA_PATH)
                    $env.PROVISIONING_KAGE = (get_def_age $env.CURRENT_INFRA_PATH)
                } 
                if $env.PROVISIONING_KAGE? != null {  
                    $env.SOPS_AGE_KEY_FILE = $env.PROVISIONING_KAGE
                    $env.SOPS_AGE_RECIPIENTS = (grep "public key:" $env.SOPS_AGE_KEY_FILE | split row ":" |
                        get -o 1  | str trim |  default "") 
                    if $env.SOPS_AGE_RECIPIENTS == "" { 
                        print $"❗Error no key found in (_ansi red_bold)($env.SOPS_AGE_KEY_FILE)(_ansi reset) file for secure AGE operations "
                        exit 1
                    }
                }
            }
        },
        "kms" => {
            # Set up KMS environment variables from KCL configuration
            if $env.CURRENT_INFRA_PATH != null and $env.CURRENT_INFRA_PATH != "" {
                let kms_config_path = (get_def_kms_config $env.CURRENT_INFRA_PATH)
                if ($kms_config_path | is-not-empty) {
                    $env.PROVISIONING_KMS_CONFIG = $kms_config_path
                    # Load KMS configuration from YAML file
                    let kms_config = (open $kms_config_path)
                    if ($kms_config.server_url? | is-not-empty) {
                        $env.PROVISIONING_KMS_SERVER = $kms_config.server_url
                    }
                    if ($kms_config.auth_method? | is-not-empty) {
                        $env.PROVISIONING_KMS_AUTH_METHOD = $kms_config.auth_method
                    }
                    if ($kms_config.client_cert_path? | is-not-empty) {
                        $env.PROVISIONING_KMS_CLIENT_CERT = $kms_config.client_cert_path
                    }
                    if ($kms_config.client_key_path? | is-not-empty) {
                        $env.PROVISIONING_KMS_CLIENT_KEY = $kms_config.client_key_path
                    }
                    if ($kms_config.ca_cert_path? | is-not-empty) {
                        $env.PROVISIONING_KMS_CA_CERT = $kms_config.ca_cert_path
                    }
                    if ($kms_config.api_token? | is-not-empty) {
                        $env.PROVISIONING_KMS_API_TOKEN = $kms_config.api_token
                    }
                    if ($kms_config.username? | is-not-empty) {
                        $env.PROVISIONING_KMS_USERNAME = $kms_config.username
                    }
                    if ($kms_config.password? | is-not-empty) {
                        $env.PROVISIONING_KMS_PASSWORD = $kms_config.password
                    }
                    if ($kms_config.timeout? | is-not-empty) {
                        $env.PROVISIONING_KMS_TIMEOUT = ($kms_config.timeout | into string)
                    }
                    if ($kms_config.verify_ssl? | is-not-empty) {
                        $env.PROVISIONING_KMS_VERIFY_SSL = ($kms_config.verify_ssl | into string)
                    }
                }
            }
        }
    }
}