import sys

from anyio import Path
from pydantic import BaseModel
import typer


if sys.version_info >= (3, 11):
    import tomllib as toml
else:
    import tomli as toml


class Dependency(BaseModel):
    name: str
    version: str


async def parse_requirements_txt_file(file_path: Path) -> list[Dependency]:
    """Parse a requirements.txt file and extracts package PyPi dependencies"""
    data = await file_path.read_text()
    lines = data.splitlines()
    if (
        len(lines) == 0
        or lines[0].strip()
        != "# This file was autogenerated by uv via the following command:"
    ):
        typer.echo(
            f"Ignoring {file_path} as it doesn't appear to be a uv generated "
            "requirements.txt file"
        )
        return []
    dependencies = []
    for line in lines:
        if "==" not in line:
            continue
        name, version = line.split("==")
        dependencies.append(Dependency(name=name.strip(), version=version.strip()))
    return dependencies


async def parse_uv_lock_file(file_path: Path) -> list[Dependency]:
    """Parses a uv.lock TOML file and extracts package PyPi dependencies"""
    data = toml.loads(await file_path.read_text())

    package_data = data.get("package", [])
    return [
        Dependency(name=package["name"], version=package["version"])
        for package in package_data
        if package.get("source", {}).get("registry") == "https://pypi.org/simple"
    ]
