from loguru import logger

from pipzap import __uv_version__, __version__
from pipzap.formatting.base import DependenciesFormatter
from pipzap.utils.requirement_string import parse_requirement_string


class RequirementsTXTFormatter(DependenciesFormatter):
    """Re-builds a requirements.txt file from parsed dependencies."""

    def format(self) -> str:
        """Build a requirements.txt string from the dependencies.

        Returns:
            A string representing the contents of a requirements.txt file.
        """
        requirements_txt = self.workspace.run(
            ["uv", "export", "--no-hashes", "--format", "requirements-txt", "--locked"],
            "pip export",
        )
        lines = [
            f"# Auto-generated by uv ({__uv_version__}) and pruned by pipzap ({__version__})",
            f"#     Requires Python {self.dependencies.py_version}",
            "",
            *[line for line in requirements_txt.strip().splitlines() if not line.startswith("#")],
        ]

        direct_deps = {dep.name: dep for dep in self.dependencies.direct}

        filtered_lines = []
        for line in lines:
            line = line.strip()

            if line == "-e .":
                continue

            if not line or line.startswith("#"):
                filtered_lines.append(line)
                continue

            try:
                req = parse_requirement_string(line.split(";")[0].split("#")[0].strip())
            except ValueError as err:
                logger.error(
                    f"Unable to parse '{line}' as a requirement. Skipping. \nError: {err}"
                    "This is likely a bug, please report it."
                )
                continue

            if req.name not in direct_deps:
                continue

            comment = f"  # pinned: {direct_deps[req.name].pinned_version or 'none'}"
            if "==" in str(req.specifier):
                comment = ""

            filtered_lines.append(line + comment)

        return "\n".join(filtered_lines) + "\n"
