import dns.resolver
from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from django.db.models import Q
from rest_framework.filters import OrderingFilter, SearchFilter

from smoothschedule.identity.core.models import Tenant
from smoothschedule.identity.users.models import User
from .models import Ticket, TicketComment, TicketTemplate, CannedResponse, IncomingTicketEmail, TicketEmailAddress
from .serializers import (
    TicketSerializer, TicketListSerializer, TicketCommentSerializer,
    TicketTemplateSerializer, CannedResponseSerializer,
    IncomingTicketEmailSerializer, IncomingTicketEmailListSerializer,
    TicketEmailAddressSerializer, TicketEmailAddressListSerializer
)


def is_platform_admin(user):
    """Check if user is a platform-level administrator."""
    return user.role in [
        User.Role.SUPERUSER,
        User.Role.PLATFORM_MANAGER,
        User.Role.PLATFORM_SUPPORT,
    ]


def is_customer(user):
    """Check if user is a customer."""
    return user.role == User.Role.CUSTOMER


class IsTenantUser(IsAuthenticated):
    """
    Custom permission to only allow users of the current tenant to access.
    Platform admins can access all.
    """
    def has_permission(self, request, view):
        if not super().has_permission(request, view):
            return False
        # Platform admins can do anything
        if is_platform_admin(request.user):
            return True
        # Check if user has ticket access permission
        if hasattr(request.user, 'can_access_tickets') and not request.user.can_access_tickets():
            return False
        # Tenant users can only access their own tenant's data
        return hasattr(request.user, 'tenant') and request.user.tenant is not None


class IsTicketOwnerOrAssigneeOrPlatformAdmin(IsTenantUser):
    """
    Custom permission to only allow owners, assignees, or platform admins to view/edit tickets.
    """
    def has_object_permission(self, request, view, obj):
        if is_platform_admin(request.user):
            return True
        if request.user == obj.creator or request.user == obj.assignee:
            return True
        # Tenant owner/manager/staff can manage tickets for their tenant
        if hasattr(request.user, 'tenant') and obj.tenant == request.user.tenant:
            # Additional checks can be added here, e.g., request.user.role in [User.Role.TENANT_OWNER, User.Role.MANAGER]
            return True
        return False


class TicketViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows tickets to be viewed or edited.
    Includes filtering by status, priority, category, ticket_type, and assignee.
    """
    queryset = Ticket.objects.all().select_related('tenant', 'creator', 'assignee')
    serializer_class = TicketSerializer
    permission_classes = [IsTicketOwnerOrAssigneeOrPlatformAdmin]
    filter_backends = [OrderingFilter, SearchFilter]
    ordering_fields = ['created_at', 'updated_at', 'priority', 'status', 'due_at']
    ordering = ['-created_at']
    search_fields = ['subject', 'description']

    def get_serializer_class(self):
        """Use TicketListSerializer for list view, TicketSerializer for detail view."""
        if self.action == 'list':
            return TicketListSerializer
        return TicketSerializer

    def get_queryset(self):
        """
        Filter tickets based on user role, ticket type, and sandbox mode.
        - Platform Admins see ONLY PLATFORM tickets (support requests from business users)
        - Tenant Owners/Managers/Staff see CUSTOMER, STAFF_REQUEST, INTERNAL tickets for their tenant
          plus PLATFORM tickets they created (to track their own support requests)
        - Customers see only CUSTOMER tickets they created
        - All users see only tickets matching their sandbox mode (live vs test)
        """
        user = self.request.user
        queryset = super().get_queryset()

        # Filter by sandbox mode - check request.sandbox_mode set by middleware
        # Platform tickets are NOT filtered by sandbox mode (they're always live)
        is_sandbox = getattr(self.request, 'sandbox_mode', False)
        queryset = queryset.filter(
            Q(ticket_type=Ticket.TicketType.PLATFORM) |  # Platform tickets always visible
            Q(is_sandbox=is_sandbox)  # Other tickets filtered by mode
        )

        if is_platform_admin(user):
            # Platform admins see ALL PLATFORM tickets
            # This includes tickets from business users AND tickets created from inbound emails
            queryset = queryset.filter(
                ticket_type=Ticket.TicketType.PLATFORM
            )
        elif is_customer(user):
            # Customers can only see tickets they personally created
            queryset = queryset.filter(creator=user)
        elif hasattr(user, 'tenant') and user.tenant:
            # Tenant-level users (owners, managers, staff) see:
            # 1. CUSTOMER, STAFF_REQUEST, INTERNAL tickets for their tenant
            # 2. PLATFORM tickets they personally created (to track their support requests)
            tenant_tickets = Q(
                tenant=user.tenant,
                ticket_type__in=[
                    Ticket.TicketType.CUSTOMER,
                    Ticket.TicketType.STAFF_REQUEST,
                    Ticket.TicketType.INTERNAL,
                ]
            )
            own_platform_tickets = Q(
                creator=user,
                ticket_type=Ticket.TicketType.PLATFORM
            )
            queryset = queryset.filter(tenant_tickets | own_platform_tickets).distinct()
        else:
            # Regular users without an associated tenant
            # They should only see tickets they created
            queryset = queryset.filter(creator=user)

        # Apply query parameter filters
        status_filter = self.request.query_params.get('status')
        priority_filter = self.request.query_params.get('priority')
        category_filter = self.request.query_params.get('category')
        ticket_type_filter = self.request.query_params.get('ticket_type')
        assignee_filter = self.request.query_params.get('assignee')

        if status_filter:
            queryset = queryset.filter(status=status_filter)
        if priority_filter:
            queryset = queryset.filter(priority=priority_filter)
        if category_filter:
            queryset = queryset.filter(category=category_filter)
        if ticket_type_filter:
            queryset = queryset.filter(ticket_type=ticket_type_filter)
        if assignee_filter:
            queryset = queryset.filter(assignee_id=assignee_filter)

        return queryset

    def perform_create(self, serializer):
        # Creator is automatically set by the serializer
        # Tenant is automatically set by the serializer for non-platform tickets
        # Set sandbox mode based on current request context
        is_sandbox = getattr(self.request, 'sandbox_mode', False)

        # Platform tickets are always created in live mode (not sandbox)
        ticket_type = serializer.validated_data.get('ticket_type', Ticket.TicketType.CUSTOMER)
        if ticket_type == Ticket.TicketType.PLATFORM:
            is_sandbox = False

        serializer.save(is_sandbox=is_sandbox)

    def perform_update(self, serializer):
        # Prevent changing creator or tenant through update
        serializer.validated_data.pop('creator', None)
        serializer.validated_data.pop('tenant', None)
        serializer.save()

    @action(detail=False, methods=['get'], permission_classes=[IsAuthenticated])
    def my_tickets(self, request):
        """
        Get all tickets created by or assigned to the requesting user.
        URL: /api/tickets/my-tickets/
        """
        user = request.user
        queryset = self.get_queryset().filter(
            Q(creator=user) | Q(assignee=user)
        ).distinct()

        # Apply filters
        queryset = self.filter_queryset(queryset)

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    @action(detail=False, methods=['get'], permission_classes=[IsAuthenticated])
    def tenant_tickets(self, request):
        """
        Get all tickets for the business owner's tenant.
        Only accessible by tenant owners, managers, and staff.
        URL: /api/tickets/tenant-tickets/
        """
        user = request.user

        # Check if user has tenant access
        if not hasattr(user, 'tenant') or not user.tenant:
            return Response(
                {'error': 'You do not have access to tenant tickets.'},
                status=status.HTTP_403_FORBIDDEN
            )

        # Customers should use my-tickets instead
        if is_customer(user):
            return Response(
                {'error': 'Customers should use the my-tickets endpoint.'},
                status=status.HTTP_403_FORBIDDEN
            )

        # Get all tickets for the user's tenant
        queryset = self.get_queryset().filter(tenant=user.tenant)

        # Apply filters
        queryset = self.filter_queryset(queryset)

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


class TicketCommentViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows ticket comments to be viewed or edited.
    """
    queryset = TicketComment.objects.all().select_related('ticket', 'author')
    serializer_class = TicketCommentSerializer
    permission_classes = [IsTicketOwnerOrAssigneeOrPlatformAdmin] # Reusing for now

    def get_queryset(self):
        """Filter comments based on the associated ticket and user permissions."""
        queryset = super().get_queryset()
        ticket_pk = self.kwargs.get('ticket_pk') # Assuming nested URL like /tickets/{ticket_pk}/comments/

        if ticket_pk:
            queryset = queryset.filter(ticket__pk=ticket_pk)

        user = self.request.user
        if is_platform_admin(user):
            return queryset # Platform admins see all comments

        # For tenant-level users, ensure they can only see comments for tickets they can access
        # This implicitly filters by the Ticket's permissions
        if hasattr(user, 'tenant') and user.tenant:
            q_filter = Q(ticket__tenant=user.tenant) | Q(ticket__creator=user, ticket__ticket_type=Ticket.TicketType.PLATFORM)
            queryset = queryset.filter(q_filter).distinct()
        else:
            queryset = queryset.filter(ticket__creator=user)
        
        # Hide internal comments from customers
        if is_customer(user):
            queryset = queryset.filter(is_internal=False)

        return queryset


    def perform_create(self, serializer):
        ticket_pk = self.kwargs.get('ticket_pk')
        try:
            ticket = Ticket.objects.get(pk=ticket_pk)
        except Ticket.DoesNotExist:
            raise status.HTTP_404_NOT_FOUND

        # Author is automatically set to the requesting user
        serializer.save(ticket=ticket, author=self.request.user)


class TicketTemplateViewSet(viewsets.ModelViewSet):
    """
    API endpoint for managing ticket templates.
    Platform admins can see all templates. Tenant users see their own + platform-wide templates.
    """
    queryset = TicketTemplate.objects.all()
    serializer_class = TicketTemplateSerializer
    permission_classes = [IsAuthenticated]
    filter_backends = [OrderingFilter, SearchFilter]
    ordering_fields = ['created_at', 'name']
    ordering = ['ticket_type', 'name']
    search_fields = ['name', 'description']

    def get_queryset(self):
        """
        Filter templates based on user role.
        - Platform admins see all templates
        - Tenant users see their own templates + platform-wide templates (tenant=null)
        """
        user = self.request.user
        queryset = super().get_queryset()

        if is_platform_admin(user):
            return queryset

        if hasattr(user, 'tenant') and user.tenant:
            # Tenant users see their own templates + platform-wide templates
            return queryset.filter(Q(tenant=user.tenant) | Q(tenant__isnull=True))
        else:
            # Users without a tenant can only see platform-wide templates
            return queryset.filter(tenant__isnull=True)

    def perform_create(self, serializer):
        # Tenant is automatically set by the serializer
        serializer.save()


class CannedResponseViewSet(viewsets.ModelViewSet):
    """
    API endpoint for managing canned responses.
    Platform admins can see all responses. Tenant users see their own + platform-wide responses.
    """
    queryset = CannedResponse.objects.all().select_related('tenant', 'created_by')
    serializer_class = CannedResponseSerializer
    permission_classes = [IsAuthenticated]
    filter_backends = [OrderingFilter, SearchFilter]
    ordering_fields = ['created_at', 'use_count', 'title']
    ordering = ['-use_count', 'title']
    search_fields = ['title', 'content']

    def get_queryset(self):
        """
        Filter canned responses based on user role.
        - Platform admins see all responses
        - Tenant users see their own responses + platform-wide responses (tenant=null)
        """
        user = self.request.user
        queryset = super().get_queryset()

        if is_platform_admin(user):
            return queryset

        if hasattr(user, 'tenant') and user.tenant:
            # Tenant users see their own responses + platform-wide responses
            return queryset.filter(Q(tenant=user.tenant) | Q(tenant__isnull=True))
        else:
            # Users without a tenant can only see platform-wide responses
            return queryset.filter(tenant__isnull=True)

    def perform_create(self, serializer):
        # Tenant and created_by are automatically set by the serializer
        serializer.save()

    @action(detail=True, methods=['post'], permission_classes=[IsAuthenticated])
    def use(self, request, pk=None):
        """
        Increment the use_count for a canned response.
        URL: /api/canned-responses/{id}/use/
        """
        canned_response = self.get_object()
        canned_response.use_count += 1
        canned_response.save(update_fields=['use_count'])
        serializer = self.get_serializer(canned_response)
        return Response(serializer.data)


class IsPlatformAdmin(IsAuthenticated):
    """Permission class that only allows platform administrators."""

    def has_permission(self, request, view):
        if not super().has_permission(request, view):
            return False
        return is_platform_admin(request.user)


class IncomingTicketEmailViewSet(viewsets.ReadOnlyModelViewSet):
    """
    API endpoint for viewing incoming email records (audit log).
    Only accessible by platform administrators.
    """
    queryset = IncomingTicketEmail.objects.all().select_related('ticket', 'matched_user')
    permission_classes = [IsPlatformAdmin]
    filter_backends = [OrderingFilter, SearchFilter]
    ordering_fields = ['received_at', 'email_date', 'processing_status']
    ordering = ['-received_at']
    search_fields = ['from_address', 'subject', 'from_name']

    def get_serializer_class(self):
        if self.action == 'list':
            return IncomingTicketEmailListSerializer
        return IncomingTicketEmailSerializer

    def get_queryset(self):
        """Apply filters from query parameters."""
        queryset = super().get_queryset()

        # Filter by processing status
        status_filter = self.request.query_params.get('status')
        if status_filter:
            queryset = queryset.filter(processing_status=status_filter)

        # Filter by ticket
        ticket_id = self.request.query_params.get('ticket')
        if ticket_id:
            queryset = queryset.filter(ticket_id=ticket_id)

        return queryset

    @action(detail=True, methods=['post'])
    def reprocess(self, request, pk=None):
        """
        Attempt to reprocess a failed incoming email.
        URL: /api/incoming-emails/{id}/reprocess/
        """
        incoming_email = self.get_object()

        if incoming_email.processing_status == IncomingTicketEmail.ProcessingStatus.PROCESSED:
            return Response({
                'success': False,
                'message': 'Email was already processed successfully',
            }, status=status.HTTP_400_BAD_REQUEST)

        # Reset status to pending and try again
        incoming_email.processing_status = IncomingTicketEmail.ProcessingStatus.PENDING
        incoming_email.error_message = ''
        incoming_email.save()

        # Try to reprocess
        from .email_receiver import TicketEmailReceiver
        receiver = TicketEmailReceiver()

        # Manually process this email
        try:
            ticket = receiver._find_matching_ticket({
                'from_address': incoming_email.from_address,
                'headers': incoming_email.raw_headers,
                'ticket_id': incoming_email.ticket_id_from_email,
            })

            if not ticket:
                incoming_email.mark_no_match()
                return Response({
                    'success': False,
                    'message': 'Could not find matching ticket',
                })

            user = receiver._find_user_by_email(incoming_email.from_address)
            if not user:
                if ticket.creator and ticket.creator.email.lower() == incoming_email.from_address.lower():
                    user = ticket.creator
                elif ticket.assignee and ticket.assignee.email.lower() == incoming_email.from_address.lower():
                    user = ticket.assignee

            if not user:
                incoming_email.mark_failed('Could not match sender to a user')
                return Response({
                    'success': False,
                    'message': 'Could not match sender to a user',
                })

            # Create comment
            comment = TicketComment.objects.create(
                ticket=ticket,
                author=user,
                comment_text=incoming_email.extracted_reply or incoming_email.body_text,
                is_internal=False,
                source=TicketComment.Source.EMAIL,
                incoming_email=incoming_email,
            )

            incoming_email.mark_processed(ticket=ticket, user=user)

            return Response({
                'success': True,
                'message': f'Successfully created comment on ticket #{ticket.id}',
                'comment_id': comment.id,
                'ticket_id': ticket.id,
            })

        except Exception as e:
            incoming_email.mark_failed(str(e))
            return Response({
                'success': False,
                'message': f'Error reprocessing: {str(e)}',
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


# Email provider database for auto-detection
EMAIL_PROVIDERS = {
    # Gmail
    'gmail.com': {
        'provider': 'google',
        'display_name': 'Gmail',
        'imap_host': 'imap.gmail.com',
        'imap_port': 993,
        'smtp_host': 'smtp.gmail.com',
        'smtp_port': 587,
        'oauth_supported': True,
    },
    'googlemail.com': {
        'provider': 'google',
        'display_name': 'Gmail',
        'imap_host': 'imap.gmail.com',
        'imap_port': 993,
        'smtp_host': 'smtp.gmail.com',
        'smtp_port': 587,
        'oauth_supported': True,
    },
    # Microsoft
    'outlook.com': {
        'provider': 'microsoft',
        'display_name': 'Outlook.com',
        'imap_host': 'outlook.office365.com',
        'imap_port': 993,
        'smtp_host': 'smtp.office365.com',
        'smtp_port': 587,
        'oauth_supported': True,
    },
    'hotmail.com': {
        'provider': 'microsoft',
        'display_name': 'Hotmail',
        'imap_host': 'outlook.office365.com',
        'imap_port': 993,
        'smtp_host': 'smtp.office365.com',
        'smtp_port': 587,
        'oauth_supported': True,
    },
    'live.com': {
        'provider': 'microsoft',
        'display_name': 'Live',
        'imap_host': 'outlook.office365.com',
        'imap_port': 993,
        'smtp_host': 'smtp.office365.com',
        'smtp_port': 587,
        'oauth_supported': True,
    },
    'msn.com': {
        'provider': 'microsoft',
        'display_name': 'MSN',
        'imap_host': 'outlook.office365.com',
        'imap_port': 993,
        'smtp_host': 'smtp.office365.com',
        'smtp_port': 587,
        'oauth_supported': True,
    },
    # Yahoo
    'yahoo.com': {
        'provider': 'yahoo',
        'display_name': 'Yahoo Mail',
        'imap_host': 'imap.mail.yahoo.com',
        'imap_port': 993,
        'smtp_host': 'smtp.mail.yahoo.com',
        'smtp_port': 587,
        'oauth_supported': False,
    },
    'yahoo.co.uk': {
        'provider': 'yahoo',
        'display_name': 'Yahoo Mail UK',
        'imap_host': 'imap.mail.yahoo.com',
        'imap_port': 993,
        'smtp_host': 'smtp.mail.yahoo.com',
        'smtp_port': 587,
        'oauth_supported': False,
    },
    # Apple iCloud
    'icloud.com': {
        'provider': 'apple',
        'display_name': 'iCloud Mail',
        'imap_host': 'imap.mail.me.com',
        'imap_port': 993,
        'smtp_host': 'smtp.mail.me.com',
        'smtp_port': 587,
        'oauth_supported': False,
    },
    'me.com': {
        'provider': 'apple',
        'display_name': 'iCloud Mail',
        'imap_host': 'imap.mail.me.com',
        'imap_port': 993,
        'smtp_host': 'smtp.mail.me.com',
        'smtp_port': 587,
        'oauth_supported': False,
    },
    'mac.com': {
        'provider': 'apple',
        'display_name': 'iCloud Mail',
        'imap_host': 'imap.mail.me.com',
        'imap_port': 993,
        'smtp_host': 'smtp.mail.me.com',
        'smtp_port': 587,
        'oauth_supported': False,
    },
    # AOL
    'aol.com': {
        'provider': 'aol',
        'display_name': 'AOL Mail',
        'imap_host': 'imap.aol.com',
        'imap_port': 993,
        'smtp_host': 'smtp.aol.com',
        'smtp_port': 587,
        'oauth_supported': False,
    },
    # Zoho
    'zoho.com': {
        'provider': 'zoho',
        'display_name': 'Zoho Mail',
        'imap_host': 'imap.zoho.com',
        'imap_port': 993,
        'smtp_host': 'smtp.zoho.com',
        'smtp_port': 587,
        'oauth_supported': False,
    },
    # ProtonMail (Bridge required)
    'protonmail.com': {
        'provider': 'protonmail',
        'display_name': 'ProtonMail',
        'imap_host': '127.0.0.1',
        'imap_port': 1143,
        'smtp_host': '127.0.0.1',
        'smtp_port': 1025,
        'oauth_supported': False,
        'notes': 'Requires ProtonMail Bridge application',
    },
    'proton.me': {
        'provider': 'protonmail',
        'display_name': 'Proton Mail',
        'imap_host': '127.0.0.1',
        'imap_port': 1143,
        'smtp_host': '127.0.0.1',
        'smtp_port': 1025,
        'oauth_supported': False,
        'notes': 'Requires ProtonMail Bridge application',
    },
}


def detect_provider_from_mx(domain: str) -> dict | None:
    """
    Detect email provider from MX records for custom domains.
    Used to identify Google Workspace or Microsoft 365 hosted domains.
    """
    try:
        mx_records = dns.resolver.resolve(domain, 'MX')
        mx_hosts = [str(record.exchange).lower() for record in mx_records]

        # Check for Google Workspace
        for mx in mx_hosts:
            if 'google' in mx or 'googlemail' in mx:
                return {
                    'provider': 'google',
                    'display_name': 'Google Workspace',
                    'imap_host': 'imap.gmail.com',
                    'imap_port': 993,
                    'smtp_host': 'smtp.gmail.com',
                    'smtp_port': 587,
                    'oauth_supported': True,
                    'detected_via': 'mx_record',
                }

        # Check for Microsoft 365
        for mx in mx_hosts:
            if 'outlook' in mx or 'microsoft' in mx or 'office365' in mx:
                return {
                    'provider': 'microsoft',
                    'display_name': 'Microsoft 365',
                    'imap_host': 'outlook.office365.com',
                    'imap_port': 993,
                    'smtp_host': 'smtp.office365.com',
                    'smtp_port': 587,
                    'oauth_supported': True,
                    'detected_via': 'mx_record',
                }

        # Check for Zoho
        for mx in mx_hosts:
            if 'zoho' in mx:
                return {
                    'provider': 'zoho',
                    'display_name': 'Zoho Mail',
                    'imap_host': 'imap.zoho.com',
                    'imap_port': 993,
                    'smtp_host': 'smtp.zoho.com',
                    'smtp_port': 587,
                    'oauth_supported': False,
                    'detected_via': 'mx_record',
                }

        # Check for Yahoo/AT&T (they use Yahoo infrastructure)
        for mx in mx_hosts:
            if 'yahoodns' in mx or 'yahoo' in mx:
                return {
                    'provider': 'yahoo',
                    'display_name': 'Yahoo Mail',
                    'imap_host': 'imap.mail.yahoo.com',
                    'imap_port': 993,
                    'smtp_host': 'smtp.mail.yahoo.com',
                    'smtp_port': 587,
                    'oauth_supported': False,
                    'detected_via': 'mx_record',
                }

        return None

    except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer, dns.resolver.NoNameservers):
        return None
    except Exception:
        return None


class EmailProviderDetectView(APIView):
    """
    API endpoint to detect email provider settings from an email address.
    Used by the email configuration wizard for auto-detection.

    POST /api/tickets/email-settings/detect/
    Body: { "email": "support@company.com" }

    Returns detected provider info and suggested IMAP/SMTP settings.
    """
    permission_classes = [IsPlatformAdmin]

    def post(self, request):
        email = request.data.get('email', '').strip().lower()

        if not email or '@' not in email:
            return Response({
                'success': False,
                'error': 'Valid email address required',
            }, status=status.HTTP_400_BAD_REQUEST)

        # Extract domain from email
        try:
            domain = email.split('@')[1]
        except IndexError:
            return Response({
                'success': False,
                'error': 'Invalid email format',
            }, status=status.HTTP_400_BAD_REQUEST)

        # First check known providers
        provider_info = EMAIL_PROVIDERS.get(domain)

        if provider_info:
            return Response({
                'success': True,
                'email': email,
                'domain': domain,
                'detected': True,
                'detected_via': 'domain_lookup',
                **provider_info,
            })

        # For custom domains, try MX record lookup
        mx_provider = detect_provider_from_mx(domain)

        if mx_provider:
            return Response({
                'success': True,
                'email': email,
                'domain': domain,
                'detected': True,
                **mx_provider,
            })

        # Unknown provider - return generic settings hint
        return Response({
            'success': True,
            'email': email,
            'domain': domain,
            'detected': False,
            'provider': 'unknown',
            'display_name': 'Custom/Unknown',
            'oauth_supported': False,
            'message': 'Could not auto-detect provider. Please enter IMAP/SMTP settings manually.',
            # Provide common default port suggestions
            'suggested_imap_port': 993,
            'suggested_smtp_port': 587,
        })


class TicketEmailAddressViewSet(viewsets.ModelViewSet):
    """
    ViewSet for managing ticket email addresses.
    Business owners and managers can manage their own email addresses.
    Platform admins can view all email addresses.
    """
    serializer_class = TicketEmailAddressSerializer
    permission_classes = [IsTenantUser]
    filter_backends = [SearchFilter, OrderingFilter]
    search_fields = ['display_name', 'email_address']
    ordering_fields = ['display_name', 'email_address', 'is_default', 'created_at']
    ordering = ['-is_default', 'display_name']

    def get_queryset(self):
        user = self.request.user

        # Platform users see platform-wide email addresses (tenant=null)
        if is_platform_admin(user):
            return TicketEmailAddress.objects.filter(tenant__isnull=True).select_related('tenant')

        # Business users see only their own email addresses
        if hasattr(user, 'tenant') and user.tenant:
            # Only owners and managers can view/manage email addresses
            if user.role in [User.Role.TENANT_OWNER, User.Role.TENANT_MANAGER]:
                return TicketEmailAddress.objects.filter(tenant=user.tenant)

        return TicketEmailAddress.objects.none()

    def get_serializer_class(self):
        if self.action == 'list':
            return TicketEmailAddressListSerializer
        return TicketEmailAddressSerializer

    def perform_create(self, serializer):
        # Set tenant based on user type
        user = self.request.user
        if is_platform_admin(user):
            # Platform admins create platform-wide email addresses (tenant=None)
            serializer.save(tenant=None)
        elif hasattr(user, 'tenant') and user.tenant:
            # Business users create email addresses for their business
            serializer.save(tenant=user.tenant)
        else:
            # Should not happen - validation should catch this
            serializer.save()

    @action(detail=True, methods=['post'])
    def test_imap(self, request, pk=None):
        """Test IMAP connection for this email address."""
        email_address = self.get_object()

        # Import here to avoid circular imports
        from .email_receiver import TicketEmailReceiver

        try:
            receiver = TicketEmailReceiver(email_address)
            if receiver.connect():
                receiver.disconnect()
                return Response({
                    'success': True,
                    'message': 'IMAP connection successful'
                })
            else:
                return Response({
                    'success': False,
                    'message': 'Failed to connect to IMAP server'
                }, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return Response({
                'success': False,
                'message': f'IMAP connection failed: {str(e)}'
            }, status=status.HTTP_400_BAD_REQUEST)

    @action(detail=True, methods=['post'])
    def test_smtp(self, request, pk=None):
        """Test SMTP connection for this email address."""
        email_address = self.get_object()

        # Import here to avoid circular imports
        from .email_notifications import TicketEmailService

        try:
            service = TicketEmailService()
            # Test connection using this email address's settings
            success = service._test_smtp_connection(email_address)
            if success:
                return Response({
                    'success': True,
                    'message': 'SMTP connection successful'
                })
            else:
                return Response({
                    'success': False,
                    'message': 'Failed to connect to SMTP server'
                }, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return Response({
                'success': False,
                'message': f'SMTP connection failed: {str(e)}'
            }, status=status.HTTP_400_BAD_REQUEST)

    @action(detail=True, methods=['post'])
    def fetch_now(self, request, pk=None):
        """Manually trigger email fetch for this address."""
        email_address = self.get_object()

        # Import here to avoid circular imports
        from .email_receiver import TicketEmailReceiver

        try:
            receiver = TicketEmailReceiver(email_address)
            processed = receiver.fetch_and_process_emails()
            return Response({
                'success': True,
                'message': f'Fetched {processed} emails',
                'processed': processed,
                'errors': 0
            })
        except Exception as e:
            return Response({
                'success': False,
                'message': f'Failed to fetch emails: {str(e)}'
            }, status=status.HTTP_400_BAD_REQUEST)

    @action(detail=True, methods=['post'])
    def set_as_default(self, request, pk=None):
        """Set this email address as the default for the business."""
        email_address = self.get_object()

        # Set this as default and unset all others for this tenant
        TicketEmailAddress.objects.filter(
            tenant=email_address.tenant,
            is_default=True
        ).exclude(pk=email_address.pk).update(is_default=False)

        email_address.is_default = True
        email_address.save()

        return Response({
            'success': True,
            'message': f'{email_address.display_name} is now the default email address'
        })


class RefreshTicketEmailsView(APIView):
    """
    POST /api/tickets/refresh-emails/
    Manually trigger a check for new incoming emails.
    Platform admins only.
    """
    permission_classes = [IsAuthenticated]

    def post(self, request):
        if not is_platform_admin(request.user):
            return Response(
                {'error': 'Only platform administrators can refresh emails'},
                status=status.HTTP_403_FORBIDDEN
            )

        from .email_receiver import PlatformEmailReceiver
        from smoothschedule.platform.admin.models import PlatformEmailAddress

        results = []
        total_processed = 0

        # Check default platform email address
        try:
            default_email = PlatformEmailAddress.objects.filter(
                is_active=True,
                is_default=True
            ).first()

            if default_email:
                receiver = PlatformEmailReceiver(default_email)
                processed = receiver.fetch_and_process_emails()
                total_processed += processed
                results.append({
                    'address': default_email.email_address,
                    'display_name': default_email.display_name,
                    'processed': processed,
                    'status': 'success',
                    'last_check_at': default_email.last_check_at.isoformat() if default_email.last_check_at else None,
                })
            else:
                results.append({
                    'address': None,
                    'status': 'no_default',
                    'message': 'No default platform email address configured'
                })
        except Exception as e:
            results.append({
                'address': 'platform',
                'status': 'error',
                'error': str(e)
            })

        return Response({
            'success': True,
            'processed': total_processed,
            'results': results,
        })