import convict from "convict";

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const visitLeaf = (acc: any, key: any, leaf: any) => {
  if (leaf.skipGenerate) {
    return;
  }

  if (leaf.default === undefined) {
    acc[key] = undefined;
  } else {
    acc[key] = leaf.default;
  }
};

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const visitNode = (acc: any, node: any, key = "") => {
  if (node._cvtProperties) {
    const keys = Object.keys(node._cvtProperties);
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    let subacc: any;
    if (key === "") {
      subacc = acc;
    } else {
      subacc = {};
      acc[key] = subacc;
    }

    keys.forEach((key) => {
      visitNode(subacc, node._cvtProperties[key], key);
    });
    // In the case that the entire sub-tree specified skipGenerate, remove the empty node
    if (Object.keys(subacc).length === 0) {
      delete acc[key];
    }
  } else {
    visitLeaf(acc, key, node);
  }
};

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const generateConfig = (conf: convict.Config<any>): unknown => {
  const schema = conf.getSchema();
  const generated = {};
  visitNode(generated, schema);
  return JSON.stringify(generated, undefined, 1);
};
