use std
use lib_provisioning/context.nu setup_user_context
export-env {
    let context = (setup_user_context)
    $env.PROVISIONING = ($env.PROVISIONING? | default
        ($context | get -o "provisioning" | default ("/" | path join "usr" |path join "local" | path join "provisioning") | into string))
    $env.PROVISIONING_CORE = ($env.PROVISIONING | path join "core")
    if ($env.PROVISIONING_CORE | path exists)  == false {
        print $"🛑 ($env.PROVISIONING_CORE) not found. Review PROVISIONING environment setting"
        exit 1
    }
    $env.PROVISIONING_PROVIDERS_PATH = ($env.PROVISIONING | path join "providers")
    $env.PROVISIONING_TASKSERVS_PATH = ($env.PROVISIONING | path join "taskservs")
    $env.PROVISIONING_CLUSTERS_PATH = ($env.PROVISIONING | path join "clusters")
    $env.PROVISIONING_RESOURCES = ($env.PROVISIONING | path join "resources" )
    $env.PROVISIONING_NOTIFY_ICON = ($env.PROVISIONING_RESOURCES | path join "images"| path join "cloudnative.png")

    $env.PROVISIONING_DEBUG = ($env | get -o PROVISIONING_DEBUG | default false | into bool)
    $env.PROVISIONING_METADATA = ($env | get -o PROVISIONING_METADATA | default
        ($context | get -o "metadata" | default  false) | into bool)

    $env.PROVISIONING_DEBUG_CHECK = ($env | get -o PROVISIONING_DEBUG_CHECK | default false | into bool)
    $env.PROVISIONING_DEBUG_REMOTE = ($env | get -o PROVISIONING_DEBUG_REMOTE | default false | into bool)
    $env.PROVISIONING_LOG_LEVEL = ($env | get -o NU_LOG_LEVEL_DEBUG | default
        ($context | get -o "log_level" | default  "") | into string)

    $env.PROVISIONING_NO_TERMINAL = match ($env | get -o PROVISIONING_NO_TERMINAL | default "") {
        "true" | "True" => true,
        _ => false
    }
    $env.PROVISIONING_ARGS = ($env | get -o PROVISIONING_ARGS | default "")
    $env.PROVISIONING_MODULE = ($env | get -o PROVISIONING_MODULE | default "")
    $env.PROVISIONING_NAME = ($env | get -o PROVISIONING_NAME | default "provisioning")

    $env.PROVISIONING_FILEVIEWER = ($env | get -o PROVISIONING_FILEVIEWER | default "bat")

    $env.PROVISIONING_METADATA = if ($env.PROVISIONING_ARGS? | str contains "--xm" ) { true } else { $env.PROVISIONING_METADATA }
    $env.PROVISIONING_DEBUG_CHECK = if ($env.PROVISIONING_ARGS? | str contains "--xc" ) { true } else { $env.PROVISIONING_DEBUG_CHECK }
    $env.PROVISIONING_DEBUG_REMOTE = if ($env.PROVISIONING_ARGS? | str contains "--xr" ) { true } else { $env.PROVISIONING_DEBUG_REMOTE }
    $env.PROVISIONING_LOG_LEVEL = if ($env.PROVISIONING_ARGS? | str contains "--xld" ) { "debug" } else {  $env.PROVISIONING_LOG_LEVEL }

    if $env.PROVISIONING_LOG_LEVEL == "debug" or $env.PROVISIONING_LOG_LEVEL == "DEBUG"  { $env.NU_LOG_LEVEL = "DEBUG" } else { $env.NU_LOG_LEVEL = ""}

    $env.PROVISIONING_INFRA_PATH = ($env.PROVISIONING_KLOUD_PATH? | default
        ($context | get -o "infra_path" | default $env.PWD ) | into string)

    $env.PROVISIONING_DFLT_SET = ($context | get -o "dflt_set" | default  "settings.k" | into string)

    $env.NOW = (date now | format date "%Y_%m_%d_%H_%M_%S")
    $env.PROVISIONING_MATCH_DATE = ($env | get -o PROVISIONING_MATCH_DATE | default "%Y_%m")

    #$env.PROVISIONING_MATCH_CMD = "v"

    $env.PROVISIONING_WK_FORMAT = ($context | get -o "wk_format" | default "yaml" | into string)

    $env.PROVISIONING_REQ_VERSIONS = ($env.PROVISIONING | path join "core" | path join "versions.yaml")
    $env.PROVISIONING_TOOLS_PATH = ($env.PROVISIONING | path join "core" | path join "tools")
    $env.PROVISIONING_TEMPLATES_PATH = ($env.PROVISIONING | path join "templates")
    $env.SSH_OPS = [StrictHostKeyChecking=accept-new UserKnownHostsFile=(if $nu.os-info.name == "windows" { "NUL" } else { "/dev/null" })]

    # Path for cloud local tasks definition can not exist if all tasks are using library install mode from 'lib-tasks'
    $env.PROVISIONING_RUN_TASKSERVS_PATH = "taskservs"
    $env.PROVISIONING_RUN_CLUSTERS_PATH = "clusters"
    $env.PROVISIONING_GENERATE_DIRPATH = "generate"
    $env.PROVISIONING_GENERATE_DEFSFILE = "defs.toml"

    $env.PROVISIONING_KEYS_PATH = ($env | get -o PROVISIONING_KEYS_PATH | default
        ($context | get -o "keys_path" | default  ".keys.k") | into string)

    $env.PROVISIONING_USE_KCL = if (^bash -c "type -P kcl" | is-not-empty) { true } else { false }
    $env.PROVISIONING_USE_KCL_PLUGIN = if ( (version).installed_plugins | str contains "kcl" ) { true } else { false }
    #$env.PROVISIONING_J2_PARSER = ($env.PROVISIONING_$TOOLS_PATH | path join "parsetemplate.py")
    #$env.PROVISIONING_J2_PARSER = (^bash -c "type -P tera")
    $env.PROVISIONING_USE_TERA_PLUGIN = if ( (version).installed_plugins | str contains "tera" ) { true } else { false }

    $env.PROVISIONING_URL = ($env.PROVISIONING_URL? | default  "https://provisioning.systems" | into string)
    #let infra = ($env.PROVISIONING_ARGS | split row "-k" | get -o 1 | split row " " | get -o 1 | default "")
    #$env.CURR_KLOUD = if $infra == "" { (^pwd) } else { $infra }

    $env.PROVISIONING_USE_SOPS = ($context | get -o "use_sops" | default  "age" | into string)
    $env.PROVISIONING_USE_KMS = ($context | get -o "use_kms" | default "" | into string)
    $env.PROVISIONING_SECRET_PROVIDER = ($context | get -o "secret_provider" | default "sops" | into string)
    
    # AI Configuration
    $env.PROVISIONING_AI_ENABLED = ($context | get -o "ai_enabled" | default false | into bool | into string)
    $env.PROVISIONING_AI_PROVIDER = ($context | get -o "ai_provider" | default "openai" | into string)
    $env.PROVISIONING_LAST_ERROR = ""
    $env.PROVISIONING_KLOUD_PATH = ($env | get -o "PROVISIONING_KLOUD_PATH" | default "")

    # For SOPS if settings below fails -> look at: sops_env.nu  loaded when is need to set env context
    let curr_infra = ($context | get -o "infra" | default "" )
    if $curr_infra != "" { $env.CURRENT_INFRA_PATH = $curr_infra }

    let sops_path = ($context | get -o "sops_path" | default "" | str replace "KLOUD_PATH" $env.PROVISIONING_KLOUD_PATH)
    if $sops_path != "" {
       $env.PROVISIONING_SOPS = $sops_path
    } else if $env.CURRENT_KLOUD_PATH? != null and ($env.CURRENT_INFRA_PATH | is -not-empty) {
        $env.PROVISIONING_SOPS = (get_def_sops $env.CURRENT_KLOUD_PATH)
    }

    let kage_path = ($context | get -o "kage_path" | default "" | str replace "KLOUD_PATH" $env.PROVISIONING_KLOUD_PATH)
    if $kage_path != "" {
        $env.PROVISIONING_KAGE = $kage_path
    } else if $env.CURRENT_KLOUD_PATH? != null and ($env.CURRENT_INFRA_PATH | is-not-empty) {
        $env.PROVISIONING_KAGE = (get_def_age $env.CURRENT_KLOUD_PATH)
    }

    if $env.PROVISIONING_KAGE? != null and ($env.PROVISIONING_KAGE | is-not-empty) {
        $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
        }
    }
    $env.PROVISIONING_OUT = ($env | get -o PROVISIONING_OUT| default "")
    if ($env.PROVISIONING_OUT | is-not-empty) {
        $env.PROVISIONING_NO_TERMINAL = true
        # if ($env.PROVISIONING_OUT | str ends-with ".yaml") or ($env.PROVISIONING_OUT | str ends-with ".yml") {
        #     $env.PROVISIONING_NO_TERMINAL = true
        # } else if ($env.PROVISIONING_OUT | str ends-with ".json") {
        #     $env.PROVISIONING_NO_TERMINAL = true
        # } else {
        #     $env.PROVISIONING_NO_TERMINAL = true
        # }
    }
    # KCL Module Path Configuration
    # Set up KCL_MOD_PATH to help KCL resolve modules when running from different directories
    $env.KCL_MOD_PATH = ($env.KCL_MOD_PATH? | default [] | append [
        ($env.PROVISIONING | path join "kcl")
        ($env.PROVISIONING_PROVIDERS_PATH)
        $env.PWD
    ] | uniq | str join ":")

    # Path helpers for dynamic imports
    $env.PROVISIONING_CORE_NULIB = ($env.PROVISIONING | path join "core" "nulib")
    $env.PROVISIONING_PROV_LIB = ($env.PROVISIONING_PROVIDERS_PATH | path join "prov_lib")

    # Extension System Configuration
    $env.PROVISIONING_EXTENSIONS_PATH = ($env.PROVISIONING_EXTENSIONS_PATH? | default
        ($context | get -o "extensions_path" | default "") | into string)

    $env.PROVISIONING_EXTENSION_MODE = ($env.PROVISIONING_EXTENSION_MODE? | default
        ($context | get -o "extension_mode" | default "full") | into string)

    $env.PROVISIONING_PROFILE = ($env.PROVISIONING_PROFILE? | default
        ($context | get -o "profile" | default "") | into string)

    $env.PROVISIONING_ALLOWED_EXTENSIONS = ($env.PROVISIONING_ALLOWED_EXTENSIONS? | default
        ($context | get -o "allowed_extensions" | default "") | into string)

    $env.PROVISIONING_BLOCKED_EXTENSIONS = ($env.PROVISIONING_BLOCKED_EXTENSIONS? | default
        ($context | get -o "blocked_extensions" | default "") | into string)

    # Custom paths for extensions
    $env.PROVISIONING_CUSTOM_PROVIDERS = ($env.PROVISIONING_CUSTOM_PROVIDERS? | default "" | into string)
    $env.PROVISIONING_CUSTOM_TASKSERVS = ($env.PROVISIONING_CUSTOM_TASKSERVS? | default "" | into string)

    # Project-local environment should be loaded manually if needed
    # Example: source .env.nu (from project directory)

    # Load providers environment settings...
    # use ../../providers/prov_lib/env_middleware.nu
}

export def "show_env" [
]: nothing -> record {
  let env_vars = {
    PROVISIONING: $env.PROVISIONING,
    PROVISIONING_CORE: $env.PROVISIONING_CORE,
    PROVISIONING_PROVIDERS_PATH: $env.PROVISIONING_PROVIDERS_PATH,
    PROVISIONING_TASKSERVS_PATH: $env.PROVISIONING_TASKSERVS_PATH,
    PROVISIONING_CLUSTERS_PATH: $env.PROVISIONING_CLUSTERS_PATH,
    PROVISIONING_RESOURCES: $env.PROVISIONING_RESOURCES,
    PROVISIONING_NOTIFY_ICON: $env.PROVISIONING_NOTIFY_ICON,

    PROVISIONING_DEBUG: $"($env.PROVISIONING_DEBUG)",
    PROVISIONING_METADATA: $"($env.PROVISIONING_METADATA)",

    PROVISIONING_DEBUG_CHECK: $"($env.PROVISIONING_DEBUG_CHECK)",
    PROVISIONING_DEBUG_REMOTE: $"($env.PROVISIONING_DEBUG_REMOTE)",
    PROVISIONING_LOG_LEVEL: $env.PROVISIONING_LOG_LEVEL,

    PROVISIONING_NO_TERMINAL: $env.PROVISIONING_NO_TERMINAL,
    PROVISIONING_ARGS: $env.PROVISIONING_ARGS,
    PROVISIONING_MODULE: $env.PROVISIONING_MODULE,
    PROVISIONING_NAME: $env.PROVISIONING_NAME,

    PROVISIONING_FILEVIEWER: $env.PROVISIONING_FILEVIEWER,

    NU_LOG_LEVEL: ($env.NU_LOG_LEVEL| default null),

    PROVISIONING_KLOUD_PATH: $env.PROVISIONING_KLOUD_PATH,

    PROVISIONING_DFLT_SET: $env.PROVISIONING_DFLT_SET,

    NOW: $env.NOW,
    PROVISIONING_MATCH_DATE: $env.PROVISIONING_MATCH_DATE,

    PROVISIONING_WK_FORMAT: $env.PROVISIONING_WK_FORMAT,

    PROVISIONING_REQ_VERSIONS: $env.PROVISIONING_REQ_VERSIONS,
    PROVISIONING_TOOLS_PATH: $env.PROVISIONING_TOOLS_PATH,
    PROVISIONING_TEMPLATES_PATH: $env.PROVISIONING_TEMPLATES_PATH,
    SSH_OPS: (if ($env.PROVISIONING_OUT | is-empty) { $env.SSH_OPS } else { $"($env.SSH_OPS | to json)"}),

    PROVISIONING_RUN_TASKSERVS_PATH: $env.PROVISIONING_RUN_TASKSERVS_PATH,
    PROVISIONING_RUN_CLUSTERS_PATH: $env.PROVISIONING_RUN_CLUSTERS_PATH,
    PROVISIONING_GENERATE_DIRPATH: $env.PROVISIONING_GENERATE_DIRPATH,
    PROVISIONING_GENERATE_DEFSFILE: $env.PROVISIONING_GENERATE_DEFSFILE,

    PROVISIONING_KEYS_PATH: $env.PROVISIONING_KEYS_PATH,

    PROVISIONING_USE_KCL: $"($env.PROVISIONING_USE_KCL)",
    PROVISIONING_J2_PARSER: ($env | get -o PROVISIONING_J2_PARSER | default ""),

    PROVISIONING_URL: $env.PROVISIONING_URL,

    PROVISIONING_USE_SOPS: $env.PROVISIONING_USE_SOPS,
    PROVISIONING_LAST_ERROR: $env.PROVISIONING_LAST_ERROR,

    CURRENT_KLOUD_PATH: ($env | get -o CURRENT_INFRA_PATH | default ""),

    PROVISIONING_SOPS: ($env | get -o PROVISIONING_SOPS | default ""),

    PROVISIONING_KAGE: ($env | get -o PROVISIONING_KAGE | default ""),

    PROVISIONING_OUT: $env.PROVISIONING_OUT,
  };

  if $env.PROVISIONING_KAGE? != null and ($env.PROVISIONING_KAGE | is-not-empty) {
    $env_vars | merge {
      SOPS_AGE_KEY_FILE: $env.SOPS_AGE_KEY_FILE,
      SOPS_AGE_RECIPIENTS: $env.SOPS_AGE_RECIPIENTS,
    }
  } else {
    $env_vars
  }
}
