import click
from funfedi_connect import ImplementedFeature

from .archive.per_tag import passing_counts

from .archive import features_for_result
from .archive.types import ResultDescription

from .codeberg import CodebergPackageDownloader, PackageDescription


def display_long(package_description, latest):
    for app_name, app_version in latest.items():
        print(f"{app_name}: {app_version}")

        result_description = ResultDescription(
            package_description, app_name, app_version
        )
        features = features_for_result(result_description)

        for f in features:
            print(f"{f.name}: {f.status}")
        print()


def display_snippet(package_description, latest):
    result_string = "| Name | Version | "
    result_string += " | ".join(str(f) for f in ImplementedFeature) + " |"
    print(result_string)

    print("| " + " | ".join(["---"] * (2 + len(ImplementedFeature))) + " |")

    for app_name, app_version in latest.items():
        result_description = ResultDescription(
            package_description, app_name, app_version
        )
        counts = passing_counts(result_description)

        result_string = f"| {app_name} | {app_version} |"
        for feature in ImplementedFeature:
            result_string += f" {counts[feature].status()} |"

        print(result_string)


@click.command
@click.pass_context
@click.option(
    "--package", default="results_funfedi_connect", help="The results to display"
)
@click.option("--package_version", default="0.1.3", help="The version to display")
@click.option("--display")
def display_command(ctx: click.Context, package: str, package_version: str, display):
    package_description = PackageDescription(package, package_version)
    downloader = CodebergPackageDownloader(package_description)
    downloader.download_latest(ctx.obj["data_dir"])

    latest = downloader.latest_version_per_app()

    if display == "snippet":
        display_snippet(package_description, latest)
    else:
        display_long(package_description, latest)


if __name__ == "__main__":
    display_command()
