import json
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from .models import Status
from django.conf import settings
import os

def export_status_to_json():
    status_data = {}
    statuses = Status.objects.all()
    for status in statuses:
        if status.type not in status_data:
            status_data[status.type] = []
        status_data[status.type].append({
            'id': status.id,
            'title': status.title,
            'type': status.type,
            'slug': status.slug,
            'description': status.description,
        })

    # Create directory if it doesn't exist
    os.makedirs(settings.DATA_CACHE_DIR, exist_ok=True)
    
    with open(os.path.join(settings.DATA_CACHE_DIR, 'status.json'), 'w') as f:
        json.dump(status_data, f, indent=4)

@receiver(post_save, sender=Status)
def status_post_save(sender, instance, created, **kwargs):
    """
    Update status.json when a status is created or updated.
    """
    export_status_to_json()

@receiver(post_delete, sender=Status)
def status_post_delete(sender, instance, **kwargs):
    """
    Update status.json when a status is deleted.
    """
    export_status_to_json()
