
from django.utils import timezone
from datetime import timedelta
from .services import NotificationService
from .models import NotificationTemplate
from tickets.models import Ticket
import logging

logger = logging.getLogger(__name__)

class TicketNotificationService:
    def __init__(self):
        self.notification_service = NotificationService()
    
    def send_ticket_assigned_notification(self, ticket):
        """Send notification to technician when ticket is assigned"""
        # Check for assigned employee first, then assigned user
        phone = None
        recipient_name = ""
        
        if ticket.assigned_employee and ticket.assigned_employee.phone:
            phone = ticket.assigned_employee.phone
            recipient_name = ticket.assigned_employee.full_name
        elif ticket.assigned_to and hasattr(ticket.assigned_to, 'employee_profile') and ticket.assigned_to.employee_profile:
            if ticket.assigned_to.employee_profile.phone:
                phone = ticket.assigned_to.employee_profile.phone
                recipient_name = ticket.assigned_to.employee_profile.full_name
        
        if not phone:
            logger.warning(f"No phone number found for assigned technician on ticket {ticket.ticket_id}")
            return False
        
        context = {
            'ticket_id': ticket.ticket_id,
            'title': ticket.title,
            'customer_name': ticket.customer_name,
            'priority': ticket.get_priority_display(),
            'scheduled_date': ticket.scheduled_date.strftime('%Y-%m-%d %H:%M') if ticket.scheduled_date else 'Not scheduled',
            'location': ticket.location or 'Location TBD'
        }
        
        try:
            template = NotificationTemplate.objects.get(
                template_type='sms_ticket_assigned',
                is_active=True
            )
            message = self.notification_service.render_template(template.content, context)
        except NotificationTemplate.DoesNotExist:
            message = f"New {ticket.get_priority_display()} ticket {ticket.ticket_id} assigned to you: {ticket.title}. Customer: {ticket.customer_name}"
        
        return self.notification_service.send_sms(
            phone_number=phone,
            message=message,
            template_type='sms_ticket_assigned',
            recipient_name=recipient_name
        )
    
    def send_appointment_reminder(self, ticket, minutes_before=30):
        """Send appointment reminder to customer"""
        if not ticket.customer or not ticket.customer.phone:
            return False
        
        context = {
            'customer_name': ticket.customer.full_name,
            'ticket_id': ticket.ticket_id,
            'scheduled_time': ticket.scheduled_date.strftime('%H:%M'),
            'technician_name': ticket.assigned_person,
            'service_type': ticket.get_category_display()
        }
        
        try:
            template = NotificationTemplate.objects.get(
                template_type='sms_appointment_reminder',
                is_active=True
            )
            message = self.notification_service.render_template(template.content, context)
        except NotificationTemplate.DoesNotExist:
            message = f"Reminder: Your {ticket.get_category_display()} appointment is scheduled for {context['scheduled_time']} today. Technician: {context['technician_name']}"
        
        return self.notification_service.send_sms(
            phone_number=ticket.customer.phone,
            message=message,
            template_type='sms_appointment_reminder',
            customer_id=ticket.customer.id
        )
    
    def send_technician_arriving_notification(self, ticket):
        """Send notification when technician is arriving"""
        if not ticket.customer or not ticket.customer.phone:
            return False
        
        context = {
            'customer_name': ticket.customer.full_name,
            'technician_name': ticket.assigned_person,
            'ticket_id': ticket.ticket_id
        }
        
        try:
            template = NotificationTemplate.objects.get(
                template_type='sms_technician_arriving',
                is_active=True
            )
            message = self.notification_service.render_template(template.content, context)
        except NotificationTemplate.DoesNotExist:
            message = f"Hello {context['customer_name']}, our technician {context['technician_name']} is arriving shortly for ticket {context['ticket_id']}."
        
        return self.notification_service.send_sms(
            phone_number=ticket.customer.phone,
            message=message,
            template_type='sms_technician_arriving',
            customer_id=ticket.customer.id
        )
    
    def send_service_completed_notification(self, ticket):
        """Send notification when service is completed"""
        if not ticket.customer or not ticket.customer.phone:
            return False
        
        context = {
            'customer_name': ticket.customer.full_name,
            'ticket_id': ticket.ticket_id,
            'service_type': ticket.get_category_display(),
            'completion_time': timezone.now().strftime('%H:%M')
        }
        
        try:
            template = NotificationTemplate.objects.get(
                template_type='sms_service_completed',
                is_active=True
            )
            message = self.notification_service.render_template(template.content, context)
        except NotificationTemplate.DoesNotExist:
            message = f"Service completed! Ticket {context['ticket_id']} for {context['service_type']} has been resolved. Thank you for choosing our services."
        
        return self.notification_service.send_sms(
            phone_number=ticket.customer.phone,
            message=message,
            template_type='sms_service_completed',
            customer_id=ticket.customer.id
        )
    
    def send_overdue_alert(self, ticket):
        """Send overdue alert to technician and supervisors"""
        if not ticket.assigned_employee:
            return False
        
        phone = ticket.assigned_employee.phone
        if not phone:
            return False
        
        context = {
            'ticket_id': ticket.ticket_id,
            'customer_name': ticket.customer_name,
            'overdue_time': (timezone.now() - ticket.scheduled_date).seconds // 60  # minutes overdue
        }
        
        try:
            template = NotificationTemplate.objects.get(
                template_type='sms_ticket_overdue',
                is_active=True
            )
            message = self.notification_service.render_template(template.content, context)
        except NotificationTemplate.DoesNotExist:
            message = f"OVERDUE: Ticket {context['ticket_id']} for {context['customer_name']} is overdue by {context['overdue_time']} minutes."
        
        return self.notification_service.send_sms(
            phone_number=phone,
            message=message,
            template_type='sms_ticket_overdue'
        )
    
    def send_ticket_status_change_notification(self, ticket, old_status, new_status):
        """Send notification to customer when ticket status changes"""
        if not ticket.customer or not ticket.customer.phone:
            return False
        
        context = {
            'customer_name': ticket.customer.full_name,
            'ticket_id': ticket.ticket_id,
            'old_status': old_status,
            'new_status': ticket.get_status_display(),
            'title': ticket.title,
            'assigned_person': ticket.assigned_person if ticket.assigned_person != 'Unassigned' else 'our team'
        }
        
        # Choose appropriate template based on new status
        template_type = 'sms_ticket_status_change'
        default_message = f"Hello {context['customer_name']}, your ticket {context['ticket_id']} status has been updated to {context['new_status']}."
        
        if new_status == 'scheduled':
            template_type = 'sms_appointment_confirmed'
            if ticket.scheduled_date:
                context['scheduled_time'] = ticket.scheduled_date.strftime('%Y-%m-%d %H:%M')
                default_message = f"Hello {context['customer_name']}, your appointment for ticket {context['ticket_id']} is confirmed for {context['scheduled_time']}."
        elif new_status == 'in_progress':
            template_type = 'sms_technician_arriving'
            default_message = f"Hello {context['customer_name']}, {context['assigned_person']} is now working on your ticket {context['ticket_id']}."
        elif new_status == 'resolved':
            template_type = 'sms_service_completed'
            default_message = f"Hello {context['customer_name']}, your ticket {context['ticket_id']} has been resolved. Thank you for choosing our services."
        
        try:
            template = NotificationTemplate.objects.get(
                template_type=template_type,
                is_active=True
            )
            message = self.notification_service.render_template(template.content, context)
        except NotificationTemplate.DoesNotExist:
            message = default_message
        
        return self.notification_service.send_sms(
            phone_number=ticket.customer.phone,
            message=message,
            template_type=template_type,
            customer_id=ticket.customer.id
        )
    
    def send_appointment_confirmation(self, ticket):
        """Send appointment confirmation to customer"""
        if not ticket.customer or not ticket.customer.phone or not ticket.scheduled_date:
            return False
        
        context = {
            'customer_name': ticket.customer.full_name,
            'ticket_id': ticket.ticket_id,
            'scheduled_date': ticket.scheduled_date.strftime('%Y-%m-%d'),
            'scheduled_time': ticket.scheduled_date.strftime('%H:%M'),
            'service_type': ticket.get_category_display(),
            'technician_name': ticket.assigned_person if ticket.assigned_person != 'Unassigned' else 'our technician',
            'location': ticket.location or 'your location'
        }
        
        try:
            template = NotificationTemplate.objects.get(
                template_type='sms_appointment_confirmed',
                is_active=True
            )
            message = self.notification_service.render_template(template.content, context)
        except NotificationTemplate.DoesNotExist:
            message = f"Hello {context['customer_name']}, your {context['service_type']} appointment is confirmed for {context['scheduled_date']} at {context['scheduled_time']}. {context['technician_name']} will visit {context['location']}."
        
        return self.notification_service.send_sms(
            phone_number=ticket.customer.phone,
            message=message,
            template_type='sms_appointment_confirmed',
            customer_id=ticket.customer.id
        )
