import sys
from pathlib import Path

from showmereqs.package_info import PackageInfo


def get_block_txt(
    header: str,
    max_row_len: int,
    infos: list[tuple[str, str]],
    row_prefix: str = "",
    detail: bool = True,
):
    if len(infos) == 0:
        return

    block_txt = f"# {header}\n"
    _txt = "[package]"
    block_txt += f"# {_txt: <{max_row_len+1}}[import name]\n"

    block_txt = block_txt if detail else ""
    for info in infos:
        version_txt = info[0]
        block_txt += f"{row_prefix}{version_txt: <{max_row_len+1}}"
        block_txt += info[1] if detail else ""
        block_txt += "\n"

    block_txt += "\n"
    return block_txt


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], **kwargs):
    detail = not kwargs["no_detail"]

    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())

    # sorted_row_txts is (full_info, no_version, no_package_name, no_info)
    sorted_row_txts = sort_row_txts(row_txts)
    header_txts = [
        "package with version",
        "package without version",
        "package without package name",
        "package without version and package name",
    ]
    prefix_txts = ["", "", "# ", "# "]
    with open(Path(kwargs["outdir"]) / "requirements.txt", "w") as f:
        f.write("# generated by showmereqs\n")
        f.write(f"# python version: {sys.version}\n\n")

        for i, row_txts in enumerate(sorted_row_txts):
            block_txt = get_block_txt(
                header=header_txts[i],
                infos=row_txts,
                max_row_len=max_package_len,
                row_prefix=prefix_txts[i],
                detail=detail,
            )
            if block_txt:
                f.write(block_txt)
