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



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

    lines.append("# Generated by 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"# used in {len(pkg['files'])} 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:
        warn(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],
    path: Path,
    dry_run: bool,
    force: bool,
    meta: dict | None = None,
):

    if not packages:
        warn("Пакеты не найдены — requirements.txt пуст")
        return

    lines = format_requirements(packages, meta=meta)

    if dry_run:
        print_requirements(lines)
        return

    write_requirements(lines, path, overwrite=force)
