import { gracefulExit } from './chunk-XQSWW35O.js';
import { define } from './chunk-WIL4LMMA.js';
import { checkForSchemaErrors, checkForNoEnvFiles } from './chunk-4MCNC4YY.js';
import { loadVarlockEnvGraph } from './chunk-5SI4EGRL.js';
import { CliExitError } from './chunk-7M6WZ65V.js';
import { formattedValue, formatDuration, formatTimeAgo } from './chunk-VT7SXRVK.js';
import { StaticValueResolver, ansis_default } from './chunk-LTYLEVHC.js';
import { my_dash_default } from './chunk-DRL5U3PK.js';
import { redactString } from './chunk-UWUBFNLX.js';
import { __name } from './chunk-IBAHCH6O.js';

// src/cli/commands/explain.command.ts
var commandSpec = define({
  name: "explain",
  description: "Show detailed information about how a config item is resolved",
  args: {
    env: {
      type: "string",
      description: "Set the environment (e.g., production, development, etc)"
    },
    path: {
      type: "string",
      short: "p",
      multiple: true,
      description: "Path to a specific .env file or directory to use as the entry point (can be specified multiple times)"
    }
  },
  examples: `
Shows detailed information about all definitions, sources, and overrides
that feed into a single config item. Useful for debugging why a value
is not what you expect.

Examples:
  varlock explain DATABASE_URL          # Explain how DATABASE_URL is resolved
  varlock explain --env production API_KEY  # Explain in production context
`.trim()
});
function describeResolver(resolver, indent = "") {
  if (resolver instanceof StaticValueResolver) {
    return `${indent}static value`;
  }
  const fnName = resolver.fnName;
  if (fnName && !fnName.startsWith("\0")) {
    return `${indent}${fnName}()`;
  }
  return `${indent}(resolver)`;
}
__name(describeResolver, "describeResolver");
var commandFn = /* @__PURE__ */ __name(async (ctx) => {
  const positionals = (ctx.positionals ?? []).slice(ctx.commandPath?.length ?? 0);
  if (!positionals.length) {
    throw new CliExitError("Missing required argument: variable name", {
      suggestion: "Run `varlock explain MY_VAR` to explain a config item"
    });
  }
  const varName = positionals[0];
  const envGraph = await loadVarlockEnvGraph({
    currentEnvFallback: ctx.values.env,
    entryFilePaths: ctx.values.path
  });
  checkForSchemaErrors(envGraph);
  checkForNoEnvFiles(envGraph);
  if (!(varName in envGraph.configSchema)) {
    throw new CliExitError(`Variable "${varName}" not found in schema`);
  }
  await envGraph.resolveEnvValues();
  const item = envGraph.configSchema[varName];
  const isSensitive = item.isSensitive;
  console.log("");
  console.log(ansis_default.bold.cyan(`  ${item.key}`));
  console.log("");
  if (item.description) {
    console.log(`  ${ansis_default.gray("Description:")} ${item.description}`);
  }
  if (item.dataType) {
    console.log(`  ${ansis_default.gray("Type:")} ${item.dataType.name}`);
  }
  const props = [];
  if (item.isRequired) props.push("required");
  else props.push("optional");
  if (isSensitive) props.push("sensitive");
  else props.push("public");
  console.log(`  ${ansis_default.gray("Properties:")} ${props.join(", ")}`);
  console.log("");
  console.log(ansis_default.bold("  Resolved value"));
  if (item.validationState === "error") {
    console.log(`  ${ansis_default.red("  (resolution failed)")}`);
    for (const err of item.errors) {
      console.log(`  ${ansis_default.red(`  - ${err.message}`)}`);
    }
  } else {
    let valStr = formattedValue(item.resolvedValue, true);
    if (isSensitive && item.resolvedValue && my_dash_default.isString(item.resolvedValue)) {
      valStr = redactString(item.resolvedValue);
    }
    console.log(`    ${valStr}`);
    if (item.isCoerced) {
      let rawStr = formattedValue(item.resolvedRawValue, true);
      if (isSensitive && item.resolvedRawValue && my_dash_default.isString(item.resolvedRawValue)) {
        rawStr = redactString(item.resolvedRawValue);
      }
      console.log(`    ${ansis_default.gray.italic(`coerced from ${rawStr}`)}`);
    }
  }
  console.log("");
  console.log(ansis_default.bold("  Value source"));
  if (item.isOverridden) {
    console.log(`    ${ansis_default.yellow("\u26A1 process.env override")} ${ansis_default.yellow.bold("(active)")}`);
    const activeValueDef = item.activeValueDef;
    if (activeValueDef) {
      const sourceLabel = activeValueDef.source?.label || "internal";
      const resolverDesc = activeValueDef.itemDef.resolver ? describeResolver(activeValueDef.itemDef.resolver) : "no value";
      console.log(`    ${ansis_default.gray("\u2514")} ${ansis_default.gray.italic(`would use ${resolverDesc} from ${sourceLabel} without override`)}`);
    }
  } else {
    const activeValueDef = item.activeValueDef;
    if (activeValueDef) {
      const sourceLabel = activeValueDef.source?.label || "internal";
      const resolverDesc = activeValueDef.itemDef.resolver ? describeResolver(activeValueDef.itemDef.resolver) : "no value";
      console.log(`    ${resolverDesc} from ${ansis_default.cyan(sourceLabel)}`);
    } else {
      console.log(`    ${ansis_default.gray("(no value set)")}`);
    }
  }
  if (item.isCached || item.isCacheHit) {
    console.log("");
    console.log(ansis_default.bold("  Cache"));
    if (item.isCacheHit) {
      const hit = item._cacheHits[0];
      const ttlMs = hit.expiresAt - hit.cachedAt;
      const ttlDisplay = ttlMs > 50 * 365.25 * 864e5 ? "forever" : formatDuration(ttlMs);
      console.log(`    ${ansis_default.gray("TTL:")} ${ttlDisplay}`);
      console.log(`    ${ansis_default.blue("Status:")} hit (cached ${formatTimeAgo(hit.cachedAt)})`);
    } else {
      const cacheTtl = item.cacheTtl;
      const ttlDisplay = cacheTtl !== void 0 ? String(cacheTtl) : "forever";
      console.log(`    ${ansis_default.gray("TTL:")} ${ttlDisplay}`);
      console.log(`    ${ansis_default.gray("Status:")} miss (freshly resolved)`);
    }
  }
  const defs = item.defs;
  if (defs.length) {
    console.log("");
    console.log(ansis_default.bold("  All definitions") + ansis_default.gray(` (${defs.length} source${defs.length > 1 ? "s" : ""}, highest priority first)`));
    for (let i = 0; i < defs.length; i++) {
      const def = defs[i];
      const sourceLabel = def.source?.label || "internal (builtin)";
      const sourceType = def.source?.type || "builtin";
      const isActiveSource = !item.isOverridden && def === item.activeValueDef;
      const marker = isActiveSource ? ansis_default.green(" \u2190 active") : "";
      console.log(`    ${ansis_default.gray(`${i + 1}.`)} ${ansis_default.cyan(sourceLabel)} ${ansis_default.gray(`(${sourceType})`)}${marker}`);
      if (def.itemDef.resolver) {
        console.log(`       ${ansis_default.gray("value:")} ${describeResolver(def.itemDef.resolver)}`);
      } else {
        console.log(`       ${ansis_default.gray("value:")} ${ansis_default.gray.italic("(none - decorators only)")}`);
      }
      const decNames = def.itemDef.decorators?.map((d) => `@${d.name}`).join(", ");
      if (decNames) {
        console.log(`       ${ansis_default.gray("decorators:")} ${ansis_default.magenta(decNames)}`);
      }
    }
  }
  const docsLinks = item.docsLinks;
  if (docsLinks.length) {
    console.log("");
    console.log(ansis_default.bold("  Documentation"));
    for (const link of docsLinks) {
      const label = link.description ? `${link.description}: ` : "";
      console.log(`    ${label}${ansis_default.underline(link.url)}`);
    }
  }
  console.log("");
  if (item.validationState === "error") {
    gracefulExit(1);
  }
}, "commandFn");

export { commandFn, commandSpec };
//# sourceMappingURL=chunk-5CY4FMLS.js.map
//# sourceMappingURL=chunk-5CY4FMLS.js.map