from .models import DISTRIBUTION_INSTALLABLE, DISTRIBUTION_PACKAGE, INSTALLABLE_PLATFORM_SPECS


def featured_version(qs):
    ordered = qs.order_by("order", "pk")
    cand = ordered.filter(is_featured_stable=True).first()
    return cand if cand else ordered.first()


def install_specs_from_versions(version_list):
    present = set()
    for ver in version_list:
        for field_name, *_ in INSTALLABLE_PLATFORM_SPECS:
            if (getattr(ver, field_name) or "").strip():
                present.add(field_name)
    return tuple(s for s in INSTALLABLE_PLATFORM_SPECS if s[0] in present)


def build_release_context(distribution, active_versions):
    context = {
        "distribution_installable": distribution == DISTRIBUTION_INSTALLABLE,
        "distribution_package": distribution == DISTRIBUTION_PACKAGE,
        "show_releases_section": False,
        "featured_version": None,
        "featured_install_cells": [],
        "show_older_versions_link": False,
        "package_versions": [],
    }

    if distribution == DISTRIBUTION_INSTALLABLE:
        featured = featured_version(active_versions)
        if (
            featured
            and not featured.has_any_install_asset()
            and not (featured.package_resource_url or "").strip()
        ):
            for cand in active_versions.exclude(pk=featured.pk).order_by("order", "pk"):
                if cand.has_any_install_asset() or (cand.package_resource_url or "").strip():
                    featured = cand
                    break
        context["featured_version"] = featured
        if featured and (
            featured.has_any_install_asset()
            or (featured.package_resource_url or "").strip()
        ):
            if featured.has_any_install_asset():
                specs = install_specs_from_versions([featured])
                context["featured_install_cells"] = featured.install_urls_for_specs(specs)
            context["show_releases_section"] = True
        older_list = list(
            active_versions.exclude(pk=featured.pk).order_by("order", "pk")
            if featured
            else active_versions.order_by("order", "pk")
        )
        context["show_older_versions_link"] = len(older_list) > 0

    elif distribution == DISTRIBUTION_PACKAGE:
        pkg_versions = list(active_versions.order_by("order", "pk"))
        context["package_versions"] = pkg_versions
        context["show_releases_section"] = len(pkg_versions) > 0

    return context


def build_archive_context(distribution, active_versions):
    featured = featured_version(active_versions)
    archive = list(
        active_versions.exclude(pk=featured.pk).order_by("order", "pk")
        if featured
        else active_versions.order_by("order", "pk")
    )
    context = {
        "featured_version": featured,
        "archive_versions": archive,
    }

    if distribution == DISTRIBUTION_INSTALLABLE:
        specs = install_specs_from_versions(archive)
        context["archive_specs"] = specs
        archive_rows_installable = []
        for ver in archive:
            cells = []
            for field_name, label, icon in specs:
                u = (getattr(ver, field_name) or "").strip()
                cells.append(
                    {"field": field_name, "label": label, "icon": icon, "url": u}
                )
            archive_rows_installable.append({"version_obj": ver, "cells": cells})
        context["archive_rows_installable"] = archive_rows_installable
        context["archive_rows_package"] = False
        context["distribution_installable"] = True
        context["distribution_package"] = False
    else:
        context["archive_specs"] = ()
        context["archive_rows_installable"] = []
        context["archive_rows_package"] = True
        context["distribution_installable"] = False
        context["distribution_package"] = True

    return context
