# Copyright (C) 2021 Intel Corporation
# SPDX-License-Identifier: GPL-3.0-or-later

import ast
import os
import subprocess
import sys
from io import StringIO

try:
    from cve_bin_tool.version import VERSION
except ModuleNotFoundError:
    with open(os.path.join("cve_bin_tool", "version.py")) as f:
        for line in f:
            if line.startswith("VERSION"):
                VERSION = ast.literal_eval(line.strip().split("=")[-1].strip())
                break


def IS_DEVELOP() -> bool:
    """
    Check if any of the paths in sys.path contain a file named 'cve-bin-tool.egg-link'.

    Returns:
        bool: True if at least one 'cve-bin-tool.egg-link' file exists in any of the directories
              listed in sys.path, False otherwise.
    """

    return any(
        list(
            map(
                os.path.isfile,
                list(
                    map(
                        lambda syspath: os.path.join(syspath, "cve-bin-tool.egg-link"),
                        sys.path,
                    )
                ),
            )
        )
    )


def update_egg() -> None:
    """
    Update the egg-info(metadata directory) for the 'cve-bin-tool' package.

    This function updates the egg information for the 'cve-bin-tool' package
    by running the 'egg_info' command using the 'setup.py' script.

    Raises:
        None
        subprocess.CalledProcessError: If the setup.py command fails
        FileNotFoundError: If setup.py doesn't exist or python isn't in PATH

    Returns:
        None
    """

    with StringIO() as f:
        cwd = os.getcwd()
        try:
            os.chdir(os.path.join(os.path.dirname(__file__), ".."))

            # Check if setup.py exists
            if not os.path.isfile("setup.py"):
                raise FileNotFoundError("setup.py not found in the parent directory")

            # Capture output to prevent console noise
            result = subprocess.run(
                [sys.executable, "setup.py", "egg_info"],
                check=True,
                capture_output=True,
                text=True,
            )

            # Store output in StringIO for consistency with original
            f.write(result.stdout)
            f.write(result.stderr)

        finally:
            os.chdir(cwd)


if __name__ == "__main__":
    update_egg()
