import logging

from django.db.models import Q
from safe_environ import from_env
from celery import Celery
from projects.models import Project
from projects.management.scrapers.projects import fetch_public_projects

logger = logging.getLogger(__name__)

app = Celery()


@app.task
def update_projects():
    owner = from_env("GITHUB_HANDLE")
    names = lambda x: {i.name if hasattr(i, "name") else i["name"] for i in x}

    try:
        projects = fetch_public_projects(owner)

        existing = Project.objects.filter(Q(name__in=names(projects)))
        former = Project.objects.filter(~Q(name__in=names(projects)))

        logger.info(
            {
                "retrieved": names(projects),
                "create": names(projects) - names(existing),
                "update": names(existing),
                "delete": names(former),
            }
        )

        for i in projects:
            Project.objects.update_or_create(name=i["name"], defaults=i)

        former.delete()

    except Exception as e:
        logger.critical(e)

import logging

from django.db.models import Q
from safe_environ import from_env
from celery import Celery
from projects.models import Project
from projects.management.scrapers.projects import fetch_public_projects

logger = logging.getLogger(__name__)

app = Celery()


@app.task
def update_projects():
    owner = from_env("GITHUB_HANDLE")
    names = lambda x: {i.name if hasattr(i, "name") else i["name"] for i in x}

    try:
        projects = fetch_public_projects(owner)

        existing = Project.objects.filter(Q(name__in=names(projects)))
        former = Project.objects.filter(~Q(name__in=names(projects)))

        logger.info(
            {
                "retrieved": names(projects),
                "create": names(projects) - names(existing),
                "update": names(existing),
                "delete": names(former),
            }
        )

        for i in projects:
            Project.objects.update_or_create(name=i["name"], defaults=i)

        former.delete()

    except Exception as e:
        logger.critical(e)
