"""
Field Mobile Celery Tasks

Background tasks for notifications and cleanup.
"""
import logging
from celery import shared_task
from django.conf import settings
from django.utils import timezone

logger = logging.getLogger(__name__)


@shared_task
def send_customer_status_notification(tenant_id, event_id, notification_type):
    """
    Send a notification to the customer about a job status change.

    Args:
        tenant_id: The tenant ID
        event_id: The event/job ID
        notification_type: One of 'en_route_notification', 'arrived_notification', 'completed_notification'
    """
    from smoothschedule.identity.core.models import Tenant
    from django_tenants.utils import schema_context
    from smoothschedule.scheduling.schedule.models import Event, Participant
    from django.contrib.contenttypes.models import ContentType
    from smoothschedule.identity.users.models import User

    try:
        tenant = Tenant.objects.get(id=tenant_id)
    except Tenant.DoesNotExist:
        logger.error(f"Tenant {tenant_id} not found")
        return {'error': 'Tenant not found'}

    with schema_context(tenant.schema_name):
        try:
            event = Event.objects.get(id=event_id)
        except Event.DoesNotExist:
            logger.error(f"Event {event_id} not found")
            return {'error': 'Event not found'}

        # Get customer from participants
        user_ct = ContentType.objects.get_for_model(User)
        customer_participant = Participant.objects.filter(
            event=event,
            role=Participant.Role.CUSTOMER,
            content_type=user_ct
        ).first()

        if not customer_participant:
            logger.warning(f"No customer found for event {event_id}")
            return {'error': 'No customer found'}

        customer = customer_participant.content_object
        if not customer:
            return {'error': 'Customer object not found'}

        # Determine notification content based on type
        messages = {
            'en_route_notification': {
                'sms': f"Your technician from {tenant.name} is on the way! They should arrive soon.",
                'subject': f"Technician En Route - {tenant.name}",
            },
            'arrived_notification': {
                'sms': f"Your technician from {tenant.name} has arrived and is starting work.",
                'subject': f"Technician Arrived - {tenant.name}",
            },
            'completed_notification': {
                'sms': f"Your appointment with {tenant.name} has been completed. Thank you!",
                'subject': f"Appointment Completed - {tenant.name}",
            },
        }

        content = messages.get(notification_type, {})
        if not content:
            logger.warning(f"Unknown notification type: {notification_type}")
            return {'error': f'Unknown notification type: {notification_type}'}

        # Send SMS if customer has phone and tenant has SMS enabled
        if customer.phone and tenant.has_feature('sms_reminders'):
            try:
                send_sms_notification.delay(
                    tenant_id=tenant_id,
                    phone_number=customer.phone,
                    message=content['sms'],
                )
            except Exception as e:
                logger.error(f"Error queuing SMS: {e}")

        # Send email notification
        if customer.email:
            try:
                send_email_notification.delay(
                    tenant_id=tenant_id,
                    email=customer.email,
                    subject=content['subject'],
                    message=content['sms'],  # Use SMS content as email body for now
                    customer_name=customer.full_name or 'Customer',
                )
            except Exception as e:
                logger.error(f"Error queuing email: {e}")

        logger.info(
            f"Queued {notification_type} for event {event_id}, "
            f"customer: {customer.email}"
        )
        return {'success': True, 'notification_type': notification_type}


@shared_task
def send_sms_notification(tenant_id, phone_number, message):
    """
    Send an SMS notification using the tenant's Twilio account.

    Args:
        tenant_id: The tenant ID
        phone_number: Recipient phone number
        message: SMS message body
    """
    from smoothschedule.identity.core.models import Tenant
    from smoothschedule.communication.credits.models import CommunicationCredits

    try:
        tenant = Tenant.objects.get(id=tenant_id)
    except Tenant.DoesNotExist:
        return {'error': 'Tenant not found'}

    # Check credits
    try:
        credits = CommunicationCredits.objects.get(tenant=tenant)
        if credits.balance_cents < 5:  # Minimum for SMS
            logger.warning(f"Insufficient credits for tenant {tenant.name}")
            return {'error': 'Insufficient credits'}
    except CommunicationCredits.DoesNotExist:
        return {'error': 'Credits not configured'}

    # Get Twilio client
    if not tenant.twilio_subaccount_sid:
        return {'error': 'Twilio not configured'}

    try:
        from twilio.rest import Client

        client = Client(
            tenant.twilio_subaccount_sid,
            tenant.twilio_subaccount_auth_token
        )

        # Use tenant's phone number or default
        from_number = tenant.twilio_phone_number
        if not from_number:
            from_number = getattr(settings, 'TWILIO_DEFAULT_FROM_NUMBER', '')

        if not from_number:
            return {'error': 'No from number configured'}

        # Send SMS
        sms = client.messages.create(
            to=phone_number,
            from_=from_number,
            body=message,
        )

        # Deduct credits
        credits.deduct(
            5,  # SMS cost in cents
            f"Status notification SMS to {phone_number[-4:]}",
            reference_type='notification_sms',
            reference_id=sms.sid,
        )

        logger.info(f"Sent SMS notification {sms.sid} to {phone_number[-4:]}")
        return {'success': True, 'message_sid': sms.sid}

    except Exception as e:
        logger.error(f"Error sending SMS: {e}")
        return {'error': str(e)}


@shared_task
def send_email_notification(tenant_id, email, subject, message, customer_name='Customer'):
    """
    Send an email notification.

    Args:
        tenant_id: The tenant ID
        email: Recipient email address
        subject: Email subject
        message: Email body
        customer_name: Customer's name for personalization
    """
    from smoothschedule.identity.core.models import Tenant
    from django.core.mail import send_mail

    try:
        tenant = Tenant.objects.get(id=tenant_id)
    except Tenant.DoesNotExist:
        return {'error': 'Tenant not found'}

    # Build email body
    email_body = f"""
Hi {customer_name},

{message}

Best regards,
{tenant.name}
"""

    try:
        from_email = tenant.contact_email or settings.DEFAULT_FROM_EMAIL
        send_mail(
            subject,
            email_body,
            from_email,
            [email],
            fail_silently=False,
        )

        logger.info(f"Sent email notification to {email}")
        return {'success': True}

    except Exception as e:
        logger.error(f"Error sending email: {e}")
        return {'error': str(e)}


@shared_task
def cleanup_old_location_data(days_to_keep=30):
    """
    Clean up old location tracking data.

    Removes location updates older than the specified number of days.
    This is a privacy measure to not retain location data indefinitely.

    Args:
        days_to_keep: Number of days of data to retain (default 30)
    """
    from smoothschedule.communication.mobile.models import EmployeeLocationUpdate

    cutoff = timezone.now() - timezone.timedelta(days=days_to_keep)

    deleted_count, _ = EmployeeLocationUpdate.objects.filter(
        created_at__lt=cutoff
    ).delete()

    logger.info(f"Deleted {deleted_count} old location updates (older than {days_to_keep} days)")
    return {'deleted': deleted_count}


@shared_task
def cleanup_old_status_history(days_to_keep=365):
    """
    Clean up old status history records.

    Keeps status history for longer (1 year default) for auditing.

    Args:
        days_to_keep: Number of days of data to retain (default 365)
    """
    from smoothschedule.communication.mobile.models import EventStatusHistory

    cutoff = timezone.now() - timezone.timedelta(days=days_to_keep)

    deleted_count, _ = EventStatusHistory.objects.filter(
        changed_at__lt=cutoff
    ).delete()

    logger.info(f"Deleted {deleted_count} old status history records")
    return {'deleted': deleted_count}
