import sys
from typing import TextIO

from showmereqs.package_info import PackageInfo


def write_block(
    header: str,
    max_version_len: int,
    infos: list[tuple[str, str]],
    f: TextIO,
    version_prefix: str = "",
):
    if len(infos) == 0:
        return

    f.write(f"# {header}\n")
    _txt = "[package]"
    f.write(f"# {_txt: <{max_version_len+1}}[import name]\n")

    for info in infos:
        version_txt = info[0]
        f.write(f"{version_prefix}{version_txt: <{max_version_len+1}}")
        f.write(info[1] + "\n")

    f.write("\n")


def sort_row_txts(row_txts: list[tuple[bool, bool, str, str]]):
    full_info = [(x[2], x[3]) for x in row_txts if x[0] and x[1]]
    no_version = [(x[2], x[3]) for x in row_txts if not x[0] and x[1]]
    no_package_name = [(x[2], x[3]) for x in row_txts if x[0] and not x[1]]
    no_info = [(x[2], x[3]) for x in row_txts if not x[0] and not x[1]]

    full_info.sort()
    no_version.sort()
    no_package_name.sort()
    no_info.sort()
    return full_info, no_version, no_package_name, no_info


def generate_reqs(package_infos: list[PackageInfo]):
    max_package_len = 0
    row_txts: list[tuple[bool, bool, str, str]] = []
    for package_info in package_infos:
        max_package_len = max(
            max_package_len,
            len(package_info.format_version_info()),
        )
        row_txts.append(package_info.format_row())

    full_info, no_version, no_package_name, no_info = sort_row_txts(row_txts)

    with open("requirements.txt", "w") as f:
        f.write("# generated by showmereqs\n")
        f.write(f"# python version: {sys.version}\n\n")

        write_block("package with version", max_package_len, full_info, f)
        write_block("package without version", max_package_len, no_version, f)
        write_block(
            "package without package name, please check to find the correct package name",
            max_package_len,
            no_package_name,
            f,
            "# ",
        )
        write_block(
            "package without version and package name",
            max_package_len,
            no_info,
            f,
            "# ",
        )
