#!/usr/bin/env bash
# Environment configuration loader
# Usage: source "$SCRIPT_DIR/lib/config/env.sh"

# Source paths if not already sourced
[ -z "${PROJECT_ROOT:-}" ] && source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/../common/paths.sh"

# Default subscription ID
DEFAULT_SUBSCRIPTION_ID="${DEFAULT_SUBSCRIPTION_ID:-fc08d829-4f14-413d-ab27-ce024425db0b}"

# Load environment variables from .env file
load_env() {
    local env_file="${1:-${PROJECT_ROOT}/.env}"
    
    if [ -f "$env_file" ]; then
        # Export variables, ignoring comments and empty lines.
        # Disable set -e so a failing command in .env (e.g. command substitution) does not exit the shell.
        local had_nounset=0
        if [[ $- == *u* ]]; then
            had_nounset=1
            set +u
        fi
        set -a
        set +e
        source <(grep -v '^#' "$env_file" | grep -v '^$' | sed 's/^/export /') 2>/dev/null || true
        set -e
        set +a
        (( had_nounset )) && set -u
    fi
}

# Get Azure subscription ID
get_subscription_id() {
    echo "${AZURE_SUBSCRIPTION_ID:-${DEFAULT_SUBSCRIPTION_ID}}"
}

# Set Azure subscription
set_subscription() {
    local subscription_id="${1:-$(get_subscription_id)}"
    az account set --subscription "$subscription_id" &> /dev/null || return 1
}

# Auto-load env if PROJECT_ROOT is set
[ -n "${PROJECT_ROOT:-}" ] && load_env
