import os
import re

import toml

from metripy.Dependency.Dependency import Dependency
from metripy.Dependency.Pip.PyPi import PyPi


class Pip:
    def get_dependencies(self, path: str) -> list[Dependency]:
        try:
            requirements = self.get_from_requirements_txt(path)
        except FileNotFoundError:
            requirements = self.get_from_pyproject_toml(path)

        pypi = PyPi()
        packages = []
        for dependency in requirements:
            package = pypi.get_info(dependency)
            packages.append(package)

        return [item for item in packages if item is not None]

    def get_from_requirements_txt(self, path: str) -> list[Dependency]:
        requirements = []

        pattern = re.compile(r"([a-zA-Z0-9_\-]+)([<>=!~]+[^\s]+)?")
        with open(os.path.join(path, "requirements.txt"), "r") as file:
            lines = file.readlines()
            for line in lines:

                line = line.strip()
                if line and not line.startswith("#"):
                    match = pattern.match(line)
                    if match:
                        name = match.group(1)
                        version = match.group(2) if match.group(2) else None
                        requirements.append(Dependency(name, version))
        return requirements

    def get_from_pyproject_toml(self, path: str) -> list[Dependency]:
        dependencies = []

        with open(os.path.join(path, "pyproject.toml"), "r") as f:
            data = toml.load(f)

            # For PEP 621 / setuptools projects
            if "project" in data:
                deps = data["project"].get("dependencies", [])
                for dep in deps:
                    # dep is a string like "requests>=2.32.5"
                    # You can split it if needed
                    if "==" in dep:
                        name, version = dep.split("==")
                    elif ">=" in dep:
                        name, version = dep.split(">=")
                    else:
                        name, version = dep, None
                    dependencies.append(
                        Dependency(name.strip(), version.strip() if version else None)
                    )

        return dependencies


if __name__ == "__main__":
    pip = Pip()
    pip.get_dependencies("./")
