from pprint import pprint

from django.db.models import Count

from recipe.models import Recipe
from transfer.models import PageTexts
from transfer.serializers.recipe import RecipeSerializer


def transfer_recipe():
    queryset = PageTexts.objects.filter(
        page__type='Recipe',
    ).values(
        'id',
        'title',
        'summary',
        'body',
        'locale',
        'state',
        'slug',
        'created_at',
        'page__attachment_suffix_url',
        'page__account_id',
    )

    serialized_data = RecipeSerializer(data=list(queryset), many=True)
    if serialized_data.is_valid():
        serialized_data.save()
    else:
        pprint(f'Recipe serializer errors: {serialized_data.errors}')
        return

    # Удаление дубликатов рецептов по одинаковым description
    duplicate_descriptions = Recipe.objects.values(
        'description'
    ).annotate(
        description_count=Count('description')
    ).filter(
        description_count__gt=1
    )
    for data in duplicate_descriptions:
        description = data['description']
        _list = list(Recipe.objects.filter(description=description).values_list('pk', flat=True)[1:])
        Recipe.objects.filter(id__in=_list).delete()


data_types = {
    'recipe': [transfer_recipe]
}
