"""
Command to cleanup unused elasticsearch indices
"""

from django.conf import settings
from django.core.management.base import BaseCommand
from django.utils.translation import activate

from wagtail.search.backends import get_search_backend
from wagtail.search.index import get_indexed_models
from wagtail.search.management.commands.update_index import group_models_by_index

from ocyan.core.fender import config


class Command(BaseCommand):
    help = __doc__

    def add_arguments(self, parser):
        parser.add_argument(
            "--remove-stale", action="store_true", help="Remove all stale indices"
        )

    def handle(self, *args, **options):
        self.stdout.write("cleaning up old elasticsearch indices")

        if config.i18n_enabled:
            for lang, _ in settings.LANGUAGES:
                activate(lang)
                self.cleanup_indices(options)
        else:
            self.cleanup_indices(options)

    def cleanup_indices(self, options):
        backend = get_search_backend("default")

        models_grouped_by_index = group_models_by_index(
            backend, get_indexed_models()
        ).items()
        if not models_grouped_by_index:
            self.stdout.write("No indices found")
            return

        stale_indices = []

        for es_index, _ in models_grouped_by_index:
            (alias,) = backend.es.cat.aliases(es_index.name, format="json")
            index_name = alias["index"]
            for index in backend.es.cat.indices("%s_*" % es_index.name, format="json"):
                if index["index"] == index_name:
                    msg = (
                        "Active index %(index)s is %(health)s %(docs.count)s %(store.size)s"
                        % index
                    )
                    if index["health"] == "green":
                        out_msg = self.style.SUCCESS(msg)
                    else:
                        out_msg = self.style.WARNING(msg)
                    self.stdout.write(out_msg)
                else:
                    stale_indices.append(index)

        if stale_indices:
            self.stdout.write(self.style.WARNING("Stale indices found"))
            for stale_index in stale_indices:
                self.stdout.write(
                    " - stale index %(index)s %(health)s %(docs.count)s %(store.size)s"
                    % stale_index
                )

            if options["remove_stale"]:
                self.stdout.write(self.style.ERROR("REMOVING STALE INDICES"))
                for stale_index in stale_indices:
                    self.stdout.write(
                        self.style.ERROR(
                            "REMOVING %(index)s is %(health)s %(docs.count)s %(store.size)s"
                            % stale_index
                        )
                    )
                    backend.es.indices.delete(stale_index["index"])
            else:
                self.stdout.write(self.style.SUCCESS("Not removing anything"))
        else:
            self.stdout.write(self.style.SUCCESS("No stale indices found"))
