from pathlib import Path
import sys
from typing import Union


def getsitepath() -> list:
    """
    Finds all 'site-packages' directories in the current Python path.

    This function iterates through all entries in `sys.path` and returns a list
    of paths that end with the string "site-packages". These directories are
    the standard locations where third-party packages are installed.

    Returns:
        list: A list of strings, each representing a full path to a
              'site-packages' directory found in `sys.path`.
    """
    sites = []
    for site in sys.path:
        if site.endswith("site-packages"):
            sites.append(site)
    return sites


def getmetafilepkg(name: str, path: str = None) -> Union[None, str]:
    """
    Locates the METADATA file for a specific package version within a site-packages directory.

    This function searches for a .dist-info directory matching the pattern
    '{name}-{version}.dist-info' (case-insensitive, with underscores converted to hyphens)
    within the specified site-packages directory. If found, it returns the full path
    to the METADATA file inside that directory.

    Args:
        name (str): The name of the package to search for.
        path (str, optional): The path to the site-packages directory to search in.
                              If not provided, the first site-packages directory
                              found by `getsitepath()` is used.

    Returns:
        Union[None, str]: The full path to the METADATA file as a string if found,
                          otherwise None.

    Note:
        The search is case-insensitive and converts underscores in the package name
        to hyphens to match standard packaging conventions.
    """
    from ..metadata.meta import version

    path = getsitepath()[0] if not path else path
    site = Path(path)
    v = version(name)

    for p in site.iterdir():
        if (
            p.is_dir()
            and p.name.lower().startswith(f"{name.lower()}-{v}".replace("_", "-"))
            and p.name.endswith(".dist-info")
        ):
            return str(Path(p) / Path("METADATA"))


def getmetapath(name: str, path: str = None):
    try:
        return Path(getmetafilepkg(name, path)).resolve().parent
    except TypeError:
        raise FileNotFoundError(f"MetaPath not found for '{name}'") from None
