from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.conf import settings
from django.contrib.auth.models import Permission
from django.contrib.auth import get_user_model
import logging

User = get_user_model()
logger = logging.getLogger(__name__)


def get_report_recipients():
    """Get list of admin emails who should receive report notifications"""
    try:
        permission = Permission.objects.get(codename='can_receive_ai_report_emails')
        admins = User.objects.filter(
            is_staff=True,
            user_permissions=permission,
            email__isnull=False,
            is_active=True
        ).exclude(email='').values_list('email', flat=True)
        
        return list(admins)
    except Permission.DoesNotExist:
        logger.error("Permission 'can_receive_ai_report_emails' does not exist")
        return []
    except Exception as e:
        logger.error(f"Error getting report recipients: {e}")
        return []


def send_admin_report_notification(analysis_obj, analysis_type, category, user_message, silent=None):
    """Send email notification to admins about new report
    
    Args:
        analysis_obj: The analysis object being reported
        analysis_type: Type of analysis ('bazi', 'liuyao', 'number')
        category: Report category
        user_message: Message from user
        silent: If True, suppress warning logs. If None, auto-detect test environment
    """
    from django.conf import settings
    
    recipients = get_report_recipients()
    
    if not recipients:
        # Auto-detect if we should be silent (during testing or if explicitly requested)
        should_be_silent = (
            silent is True or 
            (silent is None and (
                getattr(settings, 'TESTING', False) or
                'test' in getattr(settings, 'EMAIL_BACKEND', '') or
                'locmem' in getattr(settings, 'EMAIL_BACKEND', '') or
                hasattr(settings, 'TEST_RUNNER')
            ))
        )
        
        if not should_be_silent:
            logger.warning("No admin recipients found for report notifications")
        return False
    
    try:
        # Get the user who reported
        if hasattr(analysis_obj, 'created_by'):
            reporting_user = analysis_obj.created_by
        elif hasattr(analysis_obj, 'user'):
            reporting_user = analysis_obj.user
        else:
            reporting_user = None
        
        # Get the correct choices based on analysis type
        if analysis_type == 'bazi':
            from bazi.models import Person
            category_choices = Person.REPORT_CATEGORY_CHOICES
        elif analysis_type == 'liuyao':
            from liuyao.models import liuyao
            category_choices = liuyao.REPORT_CATEGORY_CHOICES
        else:
            category_choices = []
        
        # Prepare context with safe field access
        context = {
            'analysis_obj': analysis_obj,
            'analysis_type': analysis_type,
            'category': category,
            'category_display': dict(category_choices).get(category, category),
            'user_message': user_message,
            'reporting_user': reporting_user,
            'admin_url': f"{getattr(settings, 'SITE_URL', 'http://localhost:8000')}/admin/",
        }
        
        # Add safe field access for templates
        if analysis_type == 'bazi':
            context['report_timestamp'] = getattr(analysis_obj, 'bazi_report_timestamp', None)
        elif analysis_type == 'number':
            context['report_timestamp'] = getattr(analysis_obj, 'number_report_timestamp', None)
        elif analysis_type == 'liuyao':
            context['report_timestamp'] = getattr(analysis_obj, 'report_timestamp', None)
        
        subject = f"新的AI分析举报 - {analysis_type.upper()}"
        html_message = render_to_string('emails/report_admin_notification.html', context)
        plain_message = render_to_string('emails/report_admin_notification.txt', context)
        
        send_mail(
            subject=subject,
            message=plain_message,
            from_email=getattr(settings, 'DEFAULT_FROM_EMAIL', 'noreply@example.com'),
            recipient_list=recipients,
            html_message=html_message,
            fail_silently=False,
        )
        
        logger.info(f"Admin notification sent for {analysis_type} report (ID: {analysis_obj.id})")
        return True
        
    except Exception as e:
        logger.error(f"Failed to send admin notification: {e}")
        return False


def send_user_resolution_notification(user, analysis_obj, analysis_type, report_status, admin_notes):
    """Send email notification to user about report resolution
    
    Args:
        user: User who submitted the report
        analysis_obj: The analysis object being reported
        analysis_type: Type of analysis ('bazi', 'liuyao', 'number')
        report_status: Status of the report ('resolved', 'dismissed')
        admin_notes: Notes from admin for the user
    """
    if not user or not user.email:
        logger.warning("No valid user email for resolution notification")
        return False
    
    # Only send emails for 'resolved' status, not 'dismissed'
    if report_status != 'resolved':
        logger.info(f"No email sent for {report_status} status")
        return False
    
    # Check if email has already been sent for this resolution cycle
    if analysis_type == 'bazi':
        email_sent_flag = getattr(analysis_obj, 'bazi_report_resolution_email_sent', False)
    elif analysis_type == 'number':
        email_sent_flag = getattr(analysis_obj, 'number_report_resolution_email_sent', False)
    elif analysis_type == 'liuyao':
        email_sent_flag = getattr(analysis_obj, 'report_resolution_email_sent', False)
    else:
        email_sent_flag = False
    
    if email_sent_flag:
        logger.info(f"Email already sent for {analysis_type} report (ID: {analysis_obj.id})")
        return False
    
    try:
        # Get the correct status choices based on analysis type
        if analysis_type in ['bazi', 'number']:
            from bazi.models import Person
            status_choices = Person.REPORT_STATUS_CHOICES
        elif analysis_type == 'liuyao':
            from liuyao.models import liuyao
            status_choices = liuyao.REPORT_STATUS_CHOICES
        else:
            status_choices = [('pending', '待处理'), ('resolved', '已解决'), ('dismissed', '已忽略')]
        
        # Prepare context with safe field access
        context = {
            'user': user,
            'analysis_obj': analysis_obj,
            'analysis_type': analysis_type,
            'analysis_type_display': {
                'bazi': '八字分析',
                'number': '数字分析', 
                'liuyao': '六爻分析'
            }.get(analysis_type, analysis_type),
            'report_status': report_status,
            'report_status_display': dict(status_choices).get(report_status, report_status),
            'admin_notes': admin_notes,
        }
        
        # Add safe field access for templates
        if analysis_type == 'bazi':
            context['report_resolved_at'] = getattr(analysis_obj, 'bazi_report_resolved_at', None)
            context['report_timestamp'] = getattr(analysis_obj, 'bazi_report_timestamp', None)
        elif analysis_type == 'number':
            context['report_resolved_at'] = getattr(analysis_obj, 'number_report_resolved_at', None)
            context['report_timestamp'] = getattr(analysis_obj, 'number_report_timestamp', None)
        elif analysis_type == 'liuyao':
            context['report_resolved_at'] = getattr(analysis_obj, 'report_resolved_at', None)
            context['report_timestamp'] = getattr(analysis_obj, 'report_timestamp', None)
        
        subject = f"AI分析举报处理结果 - {context['analysis_type_display']}"
        html_message = render_to_string('emails/report_user_resolution.html', context)
        plain_message = render_to_string('emails/report_user_resolution.txt', context)
        
        send_mail(
            subject=subject,
            message=plain_message,
            from_email=getattr(settings, 'DEFAULT_FROM_EMAIL', 'noreply@example.com'),
            recipient_list=[user.email],
            html_message=html_message,
            fail_silently=False,
        )
        
        # Set the email flag to indicate email was sent
        if analysis_type == 'bazi':
            analysis_obj.bazi_report_resolution_email_sent = True
            analysis_obj.save(update_fields=['bazi_report_resolution_email_sent'])
        elif analysis_type == 'number':
            analysis_obj.number_report_resolution_email_sent = True
            analysis_obj.save(update_fields=['number_report_resolution_email_sent'])
        elif analysis_type == 'liuyao':
            analysis_obj.report_resolution_email_sent = True
            analysis_obj.save(update_fields=['report_resolution_email_sent'])
        
        logger.info(f"User resolution notification sent for {analysis_type} report (ID: {analysis_obj.id})")
        return True
        
    except Exception as e:
        logger.error(f"Failed to send user resolution notification: {e}")
        return False


def get_category_display(category):
    """Get display name for report category"""
    from bazi.models import Person as BaziPerson
    categories = dict(BaziPerson.REPORT_CATEGORY_CHOICES)
    return categories.get(category, category)


def get_status_display(status):
    """Get display name for report status"""
    status_choices = [('pending', '待处理'), ('resolved', '已解决'), ('dismissed', '已忽略')]
    return dict(status_choices).get(status, status)


def get_admin_action_display(admin_action):
    """Get display text for admin action (for backward compatibility)"""
    # This function is kept for backward compatibility with tests
    # The admin_action field has been removed, but tests still expect this function
    action_choices = [
        ('resolve', '已解决'),
        ('dismiss', '已忽略'),
    ]
    return dict(action_choices).get(admin_action, admin_action) 