import { EnvGraph, MultiplePathsContainerDataSource, DirectoryDataSource, DotEnvFileDataSource, ansis_default } from './chunk-LTYLEVHC.js';
import { getCacheEnvKey, createEnvKeyCacheStore, InMemoryCacheStore } from './chunk-223S32SW.js';
import { CacheStore } from './chunk-Y2ROUSC3.js';
import { getBackendInfo } from './chunk-JE2IMKMO.js';
import { my_dash_default } from './chunk-DRL5U3PK.js';
import { createDebug } from './chunk-QGM3LRUO.js';
import { redactString } from './chunk-UWUBFNLX.js';
import { __name } from './chunk-IBAHCH6O.js';
import fs from 'fs';
import path from 'path';

var debug = createDebug("varlock:loader");
async function loadEnvGraph(opts) {
  const graph = new EnvGraph();
  if (opts?.overrideValues) graph.overrideValues = opts.overrideValues;
  if (opts?.processEnvOverride) graph.processEnvOverride = opts.processEnvOverride;
  if (opts?.clearCache) graph._clearCacheMode = true;
  if (opts?.skipCache) graph._skipCacheMode = true;
  const envKey = getCacheEnvKey(opts?.processEnvOverride ?? process.env);
  if (opts?.clearCache) {
    const diskStores = [new CacheStore()];
    if (envKey) {
      try {
        diskStores.push(createEnvKeyCacheStore(envKey));
      } catch {
      }
    }
    for (const store of diskStores) {
      if (fs.existsSync(store.getFilePath())) await store.clearAll();
    }
  }
  if (!opts?.skipCache) {
    const backend = getBackendInfo();
    const isCi = graph.ciEnvInfo.isCI;
    if (backend.type !== "file" && !isCi) {
      graph._cacheMode = "disk";
      graph._cacheStore = new CacheStore();
    } else if (envKey) {
      try {
        graph._cacheStore = createEnvKeyCacheStore(envKey);
        graph._cacheMode = "disk";
      } catch (err) {
        debug("invalid %s \u2014 falling back to memory cache: %O", "_VARLOCK_CACHE_KEY", err);
        graph._cacheMode = "memory";
        graph._cacheStore = new InMemoryCacheStore();
      }
    } else {
      graph._cacheMode = "memory";
      graph._cacheStore = new InMemoryCacheStore();
    }
  }
  let rawPaths;
  if (opts?.entryFilePaths) {
    rawPaths = Array.isArray(opts.entryFilePaths) ? opts.entryFilePaths : [opts.entryFilePaths];
  }
  if (rawPaths && rawPaths.length > 1) {
    graph.basePath = opts?.basePath ?? process.cwd();
    if (opts?.afterInit) await opts.afterInit(graph);
    if (opts?.currentEnvFallback) graph.envFlagFallback = opts.currentEnvFallback;
    const resolvedPaths = rawPaths.map((p) => path.resolve(p));
    await graph.setRootDataSource(new MultiplePathsContainerDataSource(resolvedPaths));
  } else if (rawPaths?.length === 1) {
    const entryFilePath = rawPaths[0];
    const resolvedPath = path.resolve(entryFilePath);
    const isDirectory = entryFilePath.endsWith("/") || entryFilePath.endsWith(path.sep) || fs.existsSync(resolvedPath) && fs.statSync(resolvedPath).isDirectory();
    if (isDirectory) {
      graph.basePath = resolvedPath;
      if (opts?.afterInit) await opts.afterInit(graph);
      if (opts?.currentEnvFallback) graph.envFlagFallback = opts.currentEnvFallback;
      await graph.setRootDataSource(new DirectoryDataSource(resolvedPath));
    } else {
      graph.basePath = path.dirname(resolvedPath);
      if (opts?.afterInit) await opts.afterInit(graph);
      if (opts?.currentEnvFallback) graph.envFlagFallback = opts.currentEnvFallback;
      await graph.setRootDataSource(new DotEnvFileDataSource(resolvedPath));
    }
  } else {
    graph.basePath = opts?.basePath ?? process.cwd();
    if (opts?.afterInit) await opts.afterInit(graph);
    if (opts?.currentEnvFallback) graph.envFlagFallback = opts.currentEnvFallback;
    await graph.setRootDataSource(new DirectoryDataSource(graph.basePath));
  }
  await graph.finishLoad();
  return graph;
}
__name(loadEnvGraph, "loadEnvGraph");

// src/lib/formatting.ts
function applyMods(str, mods) {
  if (!mods) return str;
  if (my_dash_default.isArray(mods)) {
    let modStr = str;
    mods.forEach((mod) => {
      modStr = ansis_default[mod](modStr);
    });
    return modStr;
  }
  return ansis_default[mods](str);
}
__name(applyMods, "applyMods");
function formattedValue(val, showType = false) {
  let strVal = "";
  let strType = "";
  let mods;
  if (my_dash_default.isBoolean(val)) {
    strVal = val.toString();
    mods = ["yellow", "italic"];
    strType = "boolean";
  } else if (my_dash_default.isNumber(val)) {
    strVal = val.toString();
    mods = "yellow";
    strType = "number";
  } else if (my_dash_default.isString(val)) {
    strVal = `"${val}"`;
    strType = "string";
  } else if (my_dash_default.isPlainObject(val)) {
    strVal = JSON.stringify(val);
    strType = "object";
  } else if (val === null) {
    strVal = "null";
    mods = "gray";
  } else if (val === void 0) {
    strVal = "undefined";
    mods = "gray";
  }
  return [
    applyMods(strVal, mods),
    showType && strType ? ansis_default.gray(` (${strType})`) : ""
  ].join("");
}
__name(formattedValue, "formattedValue");
function joinAndCompact(strings, joinChar = " ") {
  return strings.filter((s) => (
    // we'll not filter out empty strings - because it's useful to just add newlines
    s !== void 0 && s !== null && s !== false
  )).join(joinChar);
}
__name(joinAndCompact, "joinAndCompact");
var VALIDATION_STATE_COLORS = {
  error: "red",
  warn: "yellow",
  valid: "cyan"
};
function formatDuration(ms) {
  if (ms < 1e3) return `${ms}ms`;
  const s = Math.floor(ms / 1e3);
  if (s < 60) return `${s}s`;
  const m = Math.floor(s / 60);
  if (m < 60) return `${m}m`;
  const h = Math.floor(m / 60);
  if (h < 24) return `${h}h`;
  const d = Math.floor(h / 24);
  if (d < 7) return `${d}d`;
  const w = Math.floor(d / 7);
  return `${w}w`;
}
__name(formatDuration, "formatDuration");
function formatTimeAgo(timestamp) {
  const diffMs = Date.now() - timestamp;
  const diffS = Math.floor(diffMs / 1e3);
  if (diffS < 60) return `${diffS}s ago`;
  const diffM = Math.floor(diffS / 60);
  if (diffM < 60) return `${diffM}m ago`;
  const diffH = Math.floor(diffM / 60);
  if (diffH < 24) return `${diffH}h ago`;
  const diffD = Math.floor(diffH / 24);
  return `${diffD}d ago`;
}
__name(formatTimeAgo, "formatTimeAgo");
function getItemSummary(item) {
  const summary = [];
  const itemErrors = item.errors;
  const icon = itemErrors.length ? (itemErrors.find((e) => !e.isWarning) ?? itemErrors[0]).icon : "\u2705";
  const isSensitive = item.isSensitive;
  const isRequired = item.isRequired;
  summary.push(joinAndCompact([
    icon,
    ansis_default[VALIDATION_STATE_COLORS[item.validationState]](item.isDeprecated ? ansis_default.strikethrough(item.key) : item.key) + (isRequired ? ansis_default.magenta("*") : ""),
    // ansis.gray(`[type = ${item.type.typeLabel}]`),
    isSensitive && ` \u{1F510}${ansis_default.gray.italic("sensitive")}`,
    item.isDeprecated && ` \u{1F635}${ansis_default.yellow.dim.italic("deprecated")}`
    // item.useAt ? ansis.gray.italic(`(${item.useAt?.join(', ')})`) : undefined,
  ]));
  let valAsStr = formattedValue(item.resolvedValue, false);
  if (isSensitive && item.resolvedValue && my_dash_default.isString(item.resolvedValue)) {
    valAsStr = redactString(item.resolvedValue);
  }
  const indicators = [];
  if (item.isCacheHit) {
    const oldest = Math.min(...item._cacheHits.map((h) => h.cachedAt));
    indicators.push(ansis_default.gray(`\u{1F4E6} ${formatTimeAgo(oldest)}`));
  }
  if (item.isOverridden) {
    indicators.push(ansis_default.yellow("\u{1F7E1} process.env"));
  }
  summary.push(joinAndCompact([
    ansis_default.gray("   \u2514"),
    valAsStr,
    item.isCoerced && ansis_default.gray.italic("< coerced from ") + (isSensitive ? formattedValue(item.resolvedRawValue) : formattedValue(item.resolvedRawValue, false)),
    indicators.length > 0 && ansis_default.gray(" ") + indicators.join(" ")
  ]));
  itemErrors?.forEach((err) => {
    summary.push(ansis_default[err.isWarning ? "yellow" : "red"](`   - ${err.isWarning ? "[WARNING] " : ""}${err.message}`));
    if (err.tip) {
      summary.push(...err.tip.split("\n").map((line) => `     ${line}`));
    }
  });
  return summary.join("\n");
}
__name(getItemSummary, "getItemSummary");

export { formatDuration, formatTimeAgo, formattedValue, getItemSummary, joinAndCompact, loadEnvGraph };
//# sourceMappingURL=chunk-VT7SXRVK.js.map
//# sourceMappingURL=chunk-VT7SXRVK.js.map