import functools
import os
import typing

import omni.kit.app
import omni.log


def _simple_yaml_load(file_path):
    # avoid bringing in a new dependency on PyYaml to parse a simple yaml file
    d = {}
    with open(file_path, "r", encoding="utf-8") as f:
        for line in f.readlines():
            if ":" not in line:
                continue
            key, value = line.split(":", maxsplit=1)
            value = value.strip()
            if value.startswith("b'"):
                value = value[2:-1]
            d[key.strip()] = value

    return d


def get_info_path() -> str:
    app = omni.kit.app.get_app_interface()
    manager = app.get_extension_manager()

    # get the usd build information that is currently being built against
    usd_libs_ext_id = manager.get_enabled_extension_id("omni.usd.libs")
    usd_libs_path = manager.get_extension_path(usd_libs_ext_id)

    return os.path.join(usd_libs_path, "PACKAGE-INFO.yaml")


@functools.lru_cache()
def get_info_data() -> typing.Optional[typing.Dict[str, object]]:
    # get the current usd build information
    package_info_path = get_info_path()
    try:
        yaml_data = _simple_yaml_load(package_info_path)
    except FileNotFoundError:
        omni.log.warn(f"{package_info_path} can not be found")
    except Exception as err:
        omni.log.warn(f"{package_info_path} can not be loaded: {err}")
    else:
        return yaml_data

    return None


def get_name() -> str:
    package_info_data = get_info_data()
    return package_info_data.get("Package", "")


def get_version() -> str:
    # get the current usd build information
    package_info_data = get_info_data()
    return package_info_data.get("Version", "")
