import logging

from django.db.models.signals import post_save
from django.dispatch import receiver

from scrobbles.utils import tokenize_title_to_tags
from webpages.models import WebPage

logger = logging.getLogger(__name__)


@receiver(post_save, sender=WebPage)
def add_auto_tags_to_webpage(sender, instance, **kwargs):
    existing_tags = {t.name for t in instance.tags.all()}

    if instance.domain:
        domain_parts = instance.domain.root.split(".")
        for part in domain_parts:
            part = part.strip().lower()
            if part and part != "www" and part not in existing_tags:
                instance.tags.add(part)
                existing_tags.add(part)

    if instance.title:
        title_tags = tokenize_title_to_tags(instance.title)
        for tag in title_tags:
            if tag not in existing_tags:
                instance.tags.add(tag)
                existing_tags.add(tag)
