from pathlib import Path
from ponytool.utils.ui import info, success, warning


def format_requirements(
        packages: dict[str, dict[str, str | list[Path]]],
        meta: dict[str, str] | None = None
) -> list[str]:

    lines = []
    lines.append("# Сгенерировано с помощью pony req gen")

    if meta:
        if meta.get("python"):
            lines.append(f"# Python: {meta['python']}")
        if meta.get("venv"):
            lines.append(f"# Venv: {meta['venv']}")

    lines.append("")

    for name in sorted(packages):
        pkg = packages[name]
        version = pkg["version"]

        if pkg.get("files"):
            lines.append(f"# Использовано в {len(pkg['files'])} файлах")

        lines.append(f"{name}=={version}")

    return lines

def print_requirements(lines: list[str]):
    info("requirements.txt (dry-run):")
    for line in lines:
        print(line)

def write_requirements(
        lines: list[str],
        path: Path,
        overwrite: bool = False
):
    if path.exists() and not overwrite:
        warning(f"{path} уже существует — используйте --force")
        return False

    path.write_text("\n".join(lines) + "\n", encoding="utf-8")
    success(f"Создан {path}")
    return True

def write(
        packages: dict[str, dict[str, str | list[Path]]],
        path: Path,
        dry_run: bool,
        force: bool,
        meta: dict[str, str] | None = None
):

    if not packages:
        warning("Пакеты не найдены, requirements.txt не был создан.")
        return

    lines = format_requirements(packages, meta=meta)

    if dry_run:
        print_requirements(lines)
        return

    write_requirements(lines, path, overwrite=force)
