"""
Django Signals for Core Application

This module contains signal handlers for automatic user creation
and other core application events.
"""

import os
import logging
from django.db.models.signals import post_migrate
from django.dispatch import receiver
from django.contrib.auth.models import User
from django.conf import settings

logger = logging.getLogger('stream_processor.core')


@receiver(post_migrate)
def create_default_admin_user(sender, **kwargs):
    """
    Create default admin user after migrations run.
    
    This signal handler automatically creates a default admin user
    if no users exist in the system. It uses environment variables
    for configuration and only runs after the auth app migrations.
    
    Args:
        sender: The app that sent the signal
        **kwargs: Additional signal arguments
    """
    # Only run for the auth app to avoid multiple executions
    if sender.name != 'django.contrib.auth':
        return
    
    try:
        # Check if any users exist
        if User.objects.exists():
            logger.info("Users already exist, skipping default admin creation")
            return
        
        # Get admin credentials from environment variables
        admin_username = os.environ.get('DEFAULT_ADMIN_USERNAME', 'admin')
        admin_email = os.environ.get('DEFAULT_ADMIN_EMAIL', 'admin@streamprocessor.com')
        admin_password = os.environ.get('DEFAULT_ADMIN_PASSWORD', 'StreamAdmin2024!')
        
        # Create the default admin user
        admin_user = User.objects.create_superuser(
            username=admin_username,
            email=admin_email,
            password=admin_password,
            first_name='Stream',
            last_name='Administrator'
        )
        
        logger.info(f"Created default admin user: {admin_username}")
        print(f"✅ Created default admin user: {admin_username}")
        
    except Exception as e:
        logger.error(f"Error creating default admin user: {e}")
        print(f"❌ Error creating default admin user: {e}")


@receiver(post_migrate)
def setup_initial_data(sender, **kwargs):
    """
    Set up initial application data after migrations.
    
    This signal handler can be used to create initial configuration
    data, notification templates, or other required setup after
    the database schema is ready.
    
    Args:
        sender: The app that sent the signal
        **kwargs: Additional signal arguments
    """
    # Only run for our core app
    if sender.name != 'apps.core':
        return
    
    try:
        logger.info("Setting up initial application data")
        
        # Add any initial data setup here
        # For example: creating default notification templates,
        # system configurations, etc.
        
        logger.info("Initial application data setup completed")
        
    except Exception as e:
        logger.error(f"Error setting up initial data: {e}")
