import sys
from pathlib import Path

from showmereqs.package_info import PackageInfo


def get_toml_path(analysis_dir: str):
    """
    check the toml file in the analysis_dir, if not exist, create it,
    return None if user cancel
    """
    toml_path = Path(analysis_dir) / "pyproject.toml"
    if not toml_path.exists():
        print(f"no toml file found in {analysis_dir}, create it? (y/n)")
        if input() == "y":
            toml_path.touch()
            return toml_path
        else:
            return None
    else:
        return toml_path


def update_toml(package_infos: list[PackageInfo], toml_path: str):
    """update the toml file with the package infos"""
    ...


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": full_info,
        "no_version": no_version,
        "no_package_name": no_package_name,
        "no_info": no_info,
    }


def generate_reqs(
    package_infos: list[PackageInfo],
    outdir: str,
    pypi_server: str,
    no_detail: bool,
):
    detail = not 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 = sort_row_txts(row_txts)
    header_txts = [
        "package with version in environment",
        "package without version",
        "can not get package name",
        "can not get package name and version",
    ]
    prefix_txts = ["", "", "# ", "# "]
    with open(Path(outdir) / "requirements.txt", "w") as f:
        f.write("# generated by showmereqs\n")
        f.write(f"# python version: {'.'.join(map(str, sys.version_info[:3]))}\n")
        f.write(f"# pypi server: {pypi_server}\n\n")

        for i, (group, row_txts) in enumerate(sorted_row_txts.items()):
            _detail = detail

            if group == "no_package_name" or group == "no_info":
                _detail = True

            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)
