from billiard.exceptions import SoftTimeLimitExceeded
from django.db.models import Subquery

from config import celery_app
from verify_trusted.companies.models import Review, Company
from verify_trusted.reviews.models import ReviewSource
from verify_trusted.widgets.models import WidgetReivews


@celery_app.task(time_limit=10000, soft_time_limit=10000)
def remove_duplicate_reviews_task(review_source):
    try:
        for row in Review.objects.filter(source_id=review_source.id, id__in=Subquery(
            WidgetReivews.objects.values_list('review_id', flat=True))).reverse():
            if Review.objects.filter(author=row.body, body=row.date, rating=row.rating).count() > 1:
                row.delete()
    except SoftTimeLimitExceeded as e:
        review_source.sync_status = ReviewSource.SyncStatus.FALSE
        review_source.save()
        print(e)
    review_source.sync_status = ReviewSource.SyncStatus.SYNCED
    review_source.save()
