from django.db.models.signals import post_save
from django.dispatch import receiver
from django.conf import settings
from django.db import transaction
from .models import GovernmentPlanUpdate, GovernmentPlan
import re
import html

if not settings.DEBUG:
    from mastodon import Mastodon

def strip_html_tags(text):
    tag_re = re.compile(r'<[^>]+>')
    plain_text = tag_re.sub('', text)
    return html.unescape(plain_text)

def post_to_mastodon(text):
    if settings.DEBUG:
        return
    mastodon = Mastodon(
        access_token=settings.MASTODON_ACCESS_TOKEN,
        api_base_url=settings.MASTODON_API_BASE_URL
    )
    mastodon.status_post(text)

@receiver(post_save, sender=GovernmentPlanUpdate)
def send_mastodon_toot_update(sender, instance, created, **kwargs):
    if created and instance.public:
        transaction.on_commit(lambda: post_to_mastodon(
            f"📢 Neue Entwicklung im Verwaltungsvorhaben: {instance.plan.title}!\n\n"
            f"{instance.title}: {strip_html_tags(instance.content)}\n\n"
            f"🔗 Primärquelle: {instance.url}\n"
            f"📋 Verwaltungstracker-Eintrag: {instance.plan.get_absolute_domain_url()}\n\n"
            f"#karlsruhe #kommunalpolitik"
        ))

@receiver(post_save, sender=GovernmentPlan)
def send_mastodon_toot_plan(sender, instance, created, **kwargs):
    if created and instance.public:
        transaction.on_commit(lambda: post_to_mastodon(
            f"📢 Neues Verwaltungsvorhaben '{instance.title}' wurde aufgenommen.\n\n"
            f"🔗 Primärquelle: {instance.reference}\n"
            f"📋 Verwaltungstracker-Eintrag: {instance.get_absolute_domain_url()}\n\n"
            f"#karlsruhe #kommunalpolitik"
        ))
