#!/usr/bin/env bash

# Shared helpers for explorer-monorepo address inventory access.

_inventory_helper_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
EXPLORER_PROJECT_ROOT="${EXPLORER_PROJECT_ROOT:-$(cd "$_inventory_helper_dir/../.." && pwd)}"
EXPLORER_RUNTIME_ENV_FILE="${EXPLORER_RUNTIME_ENV_FILE:-$EXPLORER_PROJECT_ROOT/.env}"
EXPLORER_PARENT_ENV_FILE="${EXPLORER_PARENT_ENV_FILE:-$EXPLORER_PROJECT_ROOT/../.env}"
EXPLORER_ADDRESS_INVENTORY_FILE="${EXPLORER_ADDRESS_INVENTORY_FILE:-$EXPLORER_PROJECT_ROOT/config/address-inventory.json}"

load_explorer_runtime_env() {
    source "$EXPLORER_RUNTIME_ENV_FILE" 2>/dev/null || true
    source "$EXPLORER_PARENT_ENV_FILE" 2>/dev/null || true
}

inventory_get() {
    local key="${1:-}"
    if [ -z "$key" ] || [ ! -f "$EXPLORER_ADDRESS_INVENTORY_FILE" ] || ! command -v jq >/dev/null 2>&1; then
        return 1
    fi
    jq -r --arg key "$key" '.inventory[$key] // empty' "$EXPLORER_ADDRESS_INVENTORY_FILE"
}

resolve_address_value() {
    local env_name="${1:-}"
    local inventory_key="${2:-$env_name}"
    local fallback="${3:-}"
    local current="${!env_name:-}"

    if [ -n "$current" ]; then
        printf '%s\n' "$current"
        return 0
    fi

    current="$(inventory_get "$inventory_key" 2>/dev/null || true)"
    if [ -n "$current" ]; then
        printf '%s\n' "$current"
        return 0
    fi

    if [ -n "$fallback" ]; then
        printf '%s\n' "$fallback"
        return 0
    fi

    return 1
}

persist_inventory_value() {
    local key="${1:-}"
    local value="${2:-}"
    local tmp_file

    if [ -z "$key" ] || [ -z "$value" ] || [ ! -f "$EXPLORER_ADDRESS_INVENTORY_FILE" ]; then
        return 1
    fi
    if ! command -v jq >/dev/null 2>&1; then
        echo "jq is required to update $EXPLORER_ADDRESS_INVENTORY_FILE" >&2
        return 1
    fi

    tmp_file="$(mktemp)"
    jq --arg key "$key" --arg value "$value" --arg updated "$(date -I)" \
        '.updated = $updated | .inventory[$key] = $value' \
        "$EXPLORER_ADDRESS_INVENTORY_FILE" > "$tmp_file"
    mv "$tmp_file" "$EXPLORER_ADDRESS_INVENTORY_FILE"
}
