import { CliExitError } from './chunk-7M6WZ65V.js';
import { getItemSummary, joinAndCompact } from './chunk-VT7SXRVK.js';
import { ansis_default, FileBasedDataSource } from './chunk-LTYLEVHC.js';
import { ParseError, LoadingError } from './chunk-DRL5U3PK.js';
import { __name } from './chunk-IBAHCH6O.js';

// src/cli/helpers/error-checks.ts
function showErrorLocationDetails(err) {
  if (!err.location) return;
  const errLoc = err.location;
  const errPreview = [
    errLoc.lineStr,
    `${ansis_default.gray("-".repeat(errLoc.colNumber - 1))}${ansis_default.red("^")}`
  ].join("\n");
  console.error("");
  console.error(`\u{1F4C2} ${errLoc.id}:${errLoc.lineNumber}:${errLoc.colNumber}`);
  console.error(errPreview);
}
__name(showErrorLocationDetails, "showErrorLocationDetails");
function showErrorTip(err) {
  if (!err.tip) return;
  for (const line of err.tip.split("\n")) {
    console.error(`  ${line}`);
  }
}
__name(showErrorTip, "showErrorTip");
function checkForNoEnvFiles(envGraph, opts) {
  if (Object.keys(envGraph.configSchema).length === 0) {
    const hasParseErrors = envGraph.sortedDataSources.some((s) => s.loadingError instanceof ParseError);
    if (hasParseErrors) {
      if (opts?.noThrow) return;
      throw new CliExitError("Parse error", { silent: true });
    }
    const displayPath = envGraph.basePath ?? process.cwd();
    const hasLoadedFiles = envGraph.sortedDataSources.some((s) => s instanceof FileBasedDataSource);
    if (!hasLoadedFiles) {
      console.error(`\u{1F6A8} No .env files found in ${displayPath}
`);
      console.error("Run `varlock init` to create a .env.schema file, or use `--path` to specify a file or directory.");
    } else {
      console.error(`\u{1F6A8} No config items defined in ${displayPath}
`);
      console.error("Add items to your .env.schema file to get started.");
    }
    if (opts?.noThrow) return;
    throw new CliExitError("No env files", { silent: true });
  }
}
__name(checkForNoEnvFiles, "checkForNoEnvFiles");
function checkForSchemaErrors(envGraph, opts) {
  let hasErrors = false;
  let hasOutput = false;
  for (const source of envGraph.sortedDataSources) {
    const warnings = source.errors.filter((e) => e.isWarning);
    const errors = source.errors.filter((e) => !e.isWarning);
    const resolutionErrors = source.resolutionErrors;
    if (!warnings.length && !errors.length && !resolutionErrors.length) continue;
    hasOutput = true;
    const loadingErrors = errors.filter((e) => e instanceof LoadingError || e instanceof ParseError);
    const otherErrors = errors.filter((e) => !(e instanceof LoadingError || e instanceof ParseError));
    const hasAnyError = errors.length || resolutionErrors.length;
    console.error(ansis_default.bold[hasAnyError ? "red" : "yellow"](`-- Problems encountered in ${source.label} --`));
    if (source instanceof FileBasedDataSource) {
      console.error("\u{1F4C1}", ansis_default.dim(`${source.fullPath}`));
      console.log("");
    }
    for (const warning of warnings) {
      console.error(ansis_default.yellow(`- \u26A0\uFE0F  ${warning.message}`));
      showErrorLocationDetails(warning);
    }
    for (const err of loadingErrors) {
      console.error(ansis_default.red(`- \u274C ${err.message}`));
      showErrorLocationDetails(err);
      if (err.isUnexpected && err.originalError?.stack) {
        console.error(`
${ansis_default.dim("Stack trace:")}`);
        console.error(ansis_default.dim(err.originalError.stack));
      }
    }
    for (const err of otherErrors) {
      console.error(ansis_default.red(`- \u274C ${err.message}`));
      showErrorTip(err);
      showErrorLocationDetails(err);
    }
    if (resolutionErrors.length) {
      console.error(ansis_default.red(`\u{1F6A8} Error(s) during initialization of ${source.label}`));
      for (const resErr of resolutionErrors) {
        console.error(ansis_default.red(`- \u274C ${resErr.message}`));
        showErrorTip(resErr);
        showErrorLocationDetails(resErr);
      }
    }
    if (hasAnyError) {
      hasErrors = true;
      if (!opts?.noThrow) throw new CliExitError("Schema error", { silent: true });
    }
  }
  return { hasErrors, hasOutput };
}
__name(checkForSchemaErrors, "checkForSchemaErrors");
function showPluginWarnings(envGraph) {
  for (const plugin of envGraph.plugins) {
    if (!plugin.warnings.length) continue;
    for (const warning of plugin.warnings) {
      console.error(ansis_default.yellow(`[WARNING] ${warning.message}`));
      if (warning.tip) {
        for (const line of warning.tip.split("\n")) {
          console.error(`  ${line}`);
        }
      }
    }
  }
}
__name(showPluginWarnings, "showPluginWarnings");
var InvalidEnvError = class extends Error {
  static {
    __name(this, "InvalidEnvError");
  }
  constructor() {
    super("Resolved config/env did not pass validation");
  }
  getFormattedOutput() {
    return `
\u{1F4A5} ${ansis_default.red(this.message)} \u{1F4A5}
`;
  }
};
function checkForConfigErrors(envGraph, opts) {
  let hasRootDecoratorErrors = false;
  for (const source of envGraph.sortedDataSources) {
    const resErrors = source.resolutionErrors;
    if (resErrors.length) {
      hasRootDecoratorErrors = true;
      console.error(`\u{1F6A8} Root decorator error(s) in ${source.label}`);
      if (source instanceof FileBasedDataSource) {
        console.error(ansis_default.dim(`   ${source.fullPath}`));
      }
      for (const err of resErrors) {
        console.error(ansis_default.red(`  - \u274C ${err.message}`));
        showErrorTip(err);
        showErrorLocationDetails(err);
      }
    }
  }
  if (hasRootDecoratorErrors) {
    if (!opts?.noThrow) throw new CliExitError("Schema error", { silent: true });
    return;
  }
  const failingItems = envGraph.sortedConfigKeys.map((k) => envGraph.configSchema[k]).filter((item) => item.validationState === "error");
  const warningItems = envGraph.sortedConfigKeys.map((k) => envGraph.configSchema[k]).filter((item) => item.validationState === "warn");
  if (failingItems.length > 0) {
    console.error(`
\u{1F6A8}\u{1F6A8}\u{1F6A8}  ${ansis_default.bold.red.underline("Configuration is currently invalid")}  \u{1F6A8}\u{1F6A8}\u{1F6A8}
`);
    for (const item of failingItems) {
      console.error(getItemSummary(item));
    }
    for (const item of warningItems) {
      console.error(getItemSummary(item));
    }
    if (opts?.showAll) {
      console.error();
      console.error(joinAndCompact([
        "Valid items:",
        ansis_default.italic.gray("(remove `--show-all` flag to hide)")
      ]));
      const validItems = envGraph.sortedConfigKeys.map((k) => envGraph.configSchema[k]).filter((i) => !!i.isValid);
      for (const item of validItems) {
        console.error(getItemSummary(item));
      }
    }
    showPluginWarnings(envGraph);
    if (!opts?.noThrow) {
      throw new InvalidEnvError();
    }
  }
}
__name(checkForConfigErrors, "checkForConfigErrors");

export { InvalidEnvError, checkForConfigErrors, checkForNoEnvFiles, checkForSchemaErrors, showPluginWarnings };
//# sourceMappingURL=chunk-4MCNC4YY.js.map
//# sourceMappingURL=chunk-4MCNC4YY.js.map