import functools
import os

import google.protobuf.json_format

from synthtool.protos.preconfig_pb2 import Preconfig

PRECONFIG_ENVIRONMENT_VARIABLE = "SYNTHTOOL_PRECONFIG_FILE"

PRECONFIG_HELP = """
A json file containing a description of prefetch sources that this synth.py may
us.  See preconfig.proto for detail about the format.
"""


@functools.lru_cache(maxsize=None)
def load():
    """Loads the preconfig file specified in an environment variable.

    Returns:
      An instance of Preconfig
    """
    preconfig_file_path = os.environ.get(PRECONFIG_ENVIRONMENT_VARIABLE)
    if not preconfig_file_path:
        return Preconfig()
    with open(preconfig_file_path, "rt") as json_file:
        return google.protobuf.json_format.Parse(json_file.read(), Preconfig())
