# Environment loader for the website-impl NATS admin toolchain.
#
# Reads the .env file and sets NATS admin env vars.
# Must be called before any nats-admin command.

# Load a .env file into the current scope.
#
# Skips comment lines and blank lines; handles values that contain `=`.
# Existing process env vars take precedence (env > file) to support CI overrides.
export def --env "admin load-env" [
    --env-file: string = "" # Explicit path to .env file (default: auto-detect)
] {
    # FILE_PWD is the directory of the script calling this command.
    let root = $env.FILE_PWD | path join ".."
    let dotenv = if ($env_file | is-not-empty) {
        $env_file
    } else {
        $root | path join ".env"
    }

    if not ($dotenv | path exists) {
        print $"(ansi yellow)warn(ansi reset): .env not found at ($dotenv) — relying on process env"
        return
    }

    let active_keys = $env | columns

    let pairs = open $dotenv
        | lines
        | where { |line|
            let trimmed = $line | str trim
            ($trimmed | is-not-empty) and not ($trimmed | str starts-with "#")
        }
        | each { |line|
            let parts = $line | split row "=" --number 2
            if ($parts | length) == 2 {
                let key = $parts | first | str trim
                let val = $parts | last | str trim
                    | str trim --char '"'
                    | str trim --char "'"
                { key: $key, val: $val }
            }
        }
        | where { |pair| $pair != null }

    for pair in $pairs {
        # Only set vars that are not already in the process env (CI wins)
        if not ($active_keys | any { |k| $k == $pair.key }) {
            load-env { ($pair.key): $pair.val }
        }
    }
}

# Set NATS admin defaults for this website-impl.
#
# These match the NCL-configured values.  Operators override via env vars.
export def --env "admin set-nats-defaults" [] {
    let cols = $env | columns

    if not ($cols | any { |k| $k == "NATS_ADMIN_URL" }) {
        $env.NATS_ADMIN_URL = "nats://localhost:4222"
    }
    if not ($cols | any { |k| $k == "NATS_ADMIN_NAMESPACE_PREFIX" }) {
        $env.NATS_ADMIN_NAMESPACE_PREFIX = "evol"
    }
    if not ($cols | any { |k| $k == "NATS_ADMIN_NAMESPACE_ENV" }) {
        $env.NATS_ADMIN_NAMESPACE_ENV = "website.dev"
    }
}

# Bootstrap: load .env then fill any missing NATS defaults.
export def --env "admin bootstrap" [--env-file: string = ""] {
    admin load-env --env-file $env_file
    admin set-nats-defaults
}
