import json
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from .models import Batch
from django.conf import settings
import os

def export_batch_data():
    batches_data = []
    # Use select_related to optimize database queries by fetching related objects in a single query
    batches = Batch.objects.select_related('department', 'advisor', 'status').all()
    for batch in batches:
        batches_data.append({
            'batch_id': batch.batch_id,
            'batch_name': batch.batch_name,
            'slug': batch.slug,
            'department': batch.department.department_name if batch.department else None,
            'department_id': batch.department.department_id if batch.department else None,
            'start_year': batch.start_year,
            'end_year': batch.end_year,
            'advisor': str(batch.advisor) if batch.advisor else None,
            'advisor_id': batch.advisor.teacher_id if batch.advisor else None,
            'status': batch.status.title if batch.status else None,
        })

    file_path = os.path.join(settings.DATA_CACHE_DIR, 'batches.json')
    os.makedirs(os.path.dirname(file_path), exist_ok=True)
    with open(file_path, 'w') as f:
        json.dump(batches_data, f, indent=4)

@receiver(post_save, sender=Batch)
def batch_post_save(sender, instance, created, **kwargs):
    export_batch_data()

@receiver(post_delete, sender=Batch)
def batch_post_delete(sender, instance, **kwargs):
    export_batch_data()
