import requests
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.conf import settings
from tickets.models import Ticket
from django.utils import timezone


# Campaign routing map from PowerPoint diagram
CAMPAIGN_ROUTING = {
    'SBB':   {'flow': 'inbound',  'node': 'B', 'priority': Ticket.MEDIUM},
    'RAPID': {'flow': 'inbound',  'node': 'B', 'priority': Ticket.MEDIUM},
}

DISPOSITION_ROUTING = {
    'SALE':       {'subject_prefix': 'Sale',           'priority': Ticket.LOW,    'node': 'C'},
    'REFUND':     {'subject_prefix': 'Refund Request', 'priority': Ticket.MEDIUM, 'node': 'C'},
    'PROMOTE':    {'subject_prefix': 'Promotion',      'priority': Ticket.LOW,    'node': 'C'},
    'ESCALATE':   {'subject_prefix': 'Escalation',     'priority': Ticket.HIGH,   'node': 'D'},
    'RESOLUTION': {'subject_prefix': 'Resolution',     'priority': Ticket.MEDIUM, 'node': 'B'},
    'ACCEPT':     {'subject_prefix': 'Accepted',       'priority': Ticket.LOW,    'node': 'B'},
    'FACEBOOK':   {'subject_prefix': 'Facebook',       'priority': Ticket.LOW,    'node': 'A'},
    'INSTAGRAM':  {'subject_prefix': 'Instagram',      'priority': Ticket.LOW,    'node': 'A'},
    'VIBER':      {'subject_prefix': 'Viber',          'priority': Ticket.LOW,    'node': 'A'},
    'WHATSAPP':   {'subject_prefix': 'WhatsApp',       'priority': Ticket.LOW,    'node': 'A'},
}


class VICIDialStatusView(APIView):
    def get(self, request):
        url = getattr(settings, 'VICIDIAL_URL', None)
        if not url:
            return Response({'error': 'VICIdial not configured'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)
        try:
            resp = requests.get(
                f"{url}/vicidial/non_agent_api.php",
                params={
                    'source': 'altria_crm',
                    'user': getattr(settings, 'VICIDIAL_USER', ''),
                    'pass': getattr(settings, 'VICIDIAL_PASS', ''),
                    'function': 'agent_status',
                    'campaign': request.query_params.get('campaign', ''),
                },
                timeout=10,
            )
            return Response({'raw': resp.text, 'status_code': resp.status_code})
        except Exception as e:
            return Response({'error': str(e)}, status=status.HTTP_503_SERVICE_UNAVAILABLE)


class VICIDialCallPopView(APIView):
    permission_classes = []

    def post(self, request):
        data = request.data
        phone        = data.get('phone_number', '')
        agent_ext    = data.get('agent_user', '')
        call_id      = data.get('call_id', '')
        campaign_id  = (data.get('campaign_id', '') or '').upper()
        disposition  = (data.get('disposition', '') or '').upper()
        call_type    = (data.get('call_type', 'inbound') or 'inbound').lower()
        channel_src  = (data.get('channel', '') or '').upper()

        from core.models import User
        from clients.models import Client

        agent = User.objects.filter(vicidial_user=agent_ext).first() if agent_ext else None

        # Match client by campaign ID via ClientConfiguration.vicidial_campaigns
        client = None
        if campaign_id:
            from clients.models import ClientConfiguration
            for cfg in ClientConfiguration.objects.select_related('client').filter(client__is_active=True):
                campaigns = [c.strip().upper() for c in cfg.vicidial_campaigns.split(',') if c.strip()]
                if campaign_id in campaigns:
                    client = cfg.client
                    break
        if not client:
            client = Client.objects.filter(is_active=True).first()

        if not client:
            return Response({'error': 'No active client configured'}, status=status.HTTP_400_BAD_REQUEST)

        routing = (
            DISPOSITION_ROUTING.get(disposition)
            or DISPOSITION_ROUTING.get(channel_src)
            or CAMPAIGN_ROUTING.get(campaign_id)
            or {'subject_prefix': 'Call', 'priority': Ticket.MEDIUM, 'node': 'B'}
        )

        subject_prefix = routing.get('subject_prefix', 'Call')
        priority = routing.get('priority', Ticket.MEDIUM)
        node = routing.get('node', 'B')

        if channel_src in ('FACEBOOK', 'INSTAGRAM', 'VIBER', 'WHATSAPP'):
            ticket_channel = 'social_media'
        else:
            ticket_channel = 'vicidial'

        description_lines = [
            f"VICIdial Call Pop — Campaign: {campaign_id or 'N/A'}",
            f"Call Type: {call_type.title()}",
            f"Disposition: {disposition or 'N/A'}",
            f"Routing Node: {node}",
            f"Phone: {phone}",
            f"Agent: {agent_ext or 'Unassigned'}",
            f"Call ID: {call_id}",
            f"Received: {timezone.now().strftime('%Y-%m-%d %H:%M:%S')}",
        ]
        if channel_src:
            description_lines.insert(2, f"Source Channel: {channel_src.title()}")

        ticket = Ticket.objects.create(
            client=client,
            customer_name=data.get('customer_name', f'Caller {phone}'),
            customer_phone=phone,
            customer_email=data.get('email', ''),
            customer_account=data.get('lead_id', ''),
            subject=f"{subject_prefix} — {phone or campaign_id}",
            description='\n'.join(description_lines),
            channel=ticket_channel,
            priority=priority,
            assigned_agent=agent,
            vicidial_call_id=call_id,
        )

        return Response({
            'ticket_id': ticket.id,
            'ticket_number': ticket.ticket_number,
            'routing_node': node,
            'priority': priority,
            'status': 'created',
        }, status=status.HTTP_201_CREATED)


class VICIDialDispositionView(APIView):
    permission_classes = []

    def post(self, request):
        data = request.data
        call_id     = data.get('call_id', '')
        disposition = (data.get('disposition', '') or '').upper()
        notes       = data.get('agent_notes', '')

        try:
            ticket = Ticket.objects.get(vicidial_call_id=call_id)
        except Ticket.DoesNotExist:
            return Response({'error': 'No ticket found for this call'}, status=status.HTTP_404_NOT_FOUND)

        routing = DISPOSITION_ROUTING.get(disposition, {})
        if routing.get('priority'):
            ticket.priority = routing['priority']

        if disposition == 'ESCALATE':
            ticket.status = 'escalated'

        if notes:
            ticket.description += f"\n\n[Agent Notes — {timezone.now().strftime('%H:%M')}]\n{notes}"

        ticket.save(update_fields=['priority', 'status', 'description'])

        return Response({
            'ticket_number': ticket.ticket_number,
            'updated_priority': ticket.priority,
            'routing_node': routing.get('node', 'B'),
        })


class VICIDialRecordingView(APIView):
    def post(self, request):
        ticket_id     = request.data.get('ticket_id')
        call_id       = request.data.get('call_id')
        recording_url = request.data.get('recording_url', '')

        try:
            ticket = (
                Ticket.objects.get(id=ticket_id) if ticket_id
                else Ticket.objects.get(vicidial_call_id=call_id)
            )
            ticket.vicidial_recording_url = recording_url
            ticket.save(update_fields=['vicidial_recording_url'])
            return Response({'detail': 'Recording linked', 'ticket_number': ticket.ticket_number})
        except Ticket.DoesNotExist:
            return Response({'error': 'Ticket not found'}, status=status.HTTP_404_NOT_FOUND)


class VICIDialConfigView(APIView):
    def get(self, request):
        domain = getattr(settings, 'DOMAIN', request.get_host())
        configured = bool(getattr(settings, 'VICIDIAL_URL', None))
        return Response({
            'configured': configured,
            'vicidial_url': getattr(settings, 'VICIDIAL_URL', ''),
            'campaigns': ['SBB', 'RAPID'],
            'webhook_urls': {
                'call_pop':    f"https://{domain}/api/vicidial/call-pop/",
                'disposition': f"https://{domain}/api/vicidial/disposition/",
                'recording':   f"https://{domain}/api/vicidial/recording/",
                'status':      f"https://{domain}/api/vicidial/status/",
            },
            'routing_nodes': {
                'A': 'Social Media Inbound (Facebook, Instagram, Viber, WhatsApp)',
                'B': 'Inbound Campaigns — Accept / Escalate / Resolution',
                'C': 'Outbound Sales — Sales / Promote / Refund Request',
                'D': 'Outbound Escalation — Escalate',
            },
        })


_CATEGORY_TO_TYPE = {
    'billing':    'billing',
    'technical':  'technical',
    'complaint':  'complaint',
    'inquiry':    'inquiry',
    'escalation': 'escalation',
    'network':    'network',
    'social':     'social',
    'hr':         'hr',
    'general':    'general',
}


def _assign_sla(ticket, client, priority, category):
    """Find the best matching SLA policy and set deadlines on the ticket."""
    import datetime
    from sla.models import SLAPolicy

    valid_categories = {c[0] for c in SLAPolicy.CATEGORY_CHOICES}
    sla_category = category if category in valid_categories else 'general'

    policy = (
        SLAPolicy.objects.filter(client=client, priority=priority, category=sla_category, is_active=True).first()
        or SLAPolicy.objects.filter(client=client, priority=priority, is_active=True).first()
        or SLAPolicy.objects.filter(client=client, is_active=True).first()
    )
    if not policy:
        return None

    now = timezone.now()
    ticket.sla_policy = policy
    ticket.first_response_due = now + datetime.timedelta(minutes=policy.first_response_minutes)
    ticket.resolution_due = now + datetime.timedelta(minutes=policy.resolution_minutes)
    ticket.save(update_fields=['sla_policy', 'first_response_due', 'resolution_due'])
    return policy


class WebhookInboundEmailView(APIView):
    permission_classes = []

    @staticmethod
    def _record_network_alert(client, network, subject, body):
        """Store a pfSense gateway up/down event against its network."""
        import re as _re
        from clients.models import NetworkAlert
        from django.utils import timezone

        from clients.models import network_for_gateway
        kind = NetworkAlert.UP if subject.startswith('[NETWORK UP]') else NetworkAlert.DOWN
        m = _re.search(r'Gateway\s+([^\s]+)', subject) or _re.search(r'Gateway:\s*([^\s\\]+)', body or '')
        gateway = (m.group(1) if m else '')[:120]

        # The monitor key identifies the client; the gateway name identifies
        # which of its lines went down.
        network = network_for_gateway(client.pk, gateway) or network

        alert = NetworkAlert.objects.create(
            client=client, network=network, kind=kind, gateway=gateway,
            message=subject[:500], detail=(body or '')[:5000],
        )
        # Close the matching outage so the UI can show how long it lasted.
        if kind == NetworkAlert.UP and gateway:
            NetworkAlert.objects.filter(
                client=client, gateway=gateway, kind=NetworkAlert.DOWN, resolved_at__isnull=True
            ).update(resolved_at=timezone.now())
        return alert

    def post(self, request):
        import hmac
        import json
        import anthropic
        from clients.models import Client
        from notifications.models import Notification
        from core.models import User
        from django.conf import settings

        # Shared-secret auth between email server and CRM
        secret = getattr(settings, 'EMAIL_WEBHOOK_SECRET', '')
        if secret:
            sig = request.headers.get('X-Webhook-Secret', '')
            if not hmac.compare_digest(sig, secret):
                return Response({'error': 'Unauthorized'}, status=status.HTTP_401_UNAUTHORIZED)

        data = request.data
        subject    = data.get('subject', 'Email Inquiry')
        from_email = data.get('from', '')
        from_name  = data.get('from_name', from_email)
        body       = data.get('body', '')
        email_id   = data.get('email_id', '')
        source     = data.get('source', 'email')

        # Route to the RIGHT client. An on-premise monitor (pfSense) identifies
        # itself with the monitor_key baked into its install script; without this
        # every alert landed on whichever client sorted first, so one client saw
        # another's network tickets. A supplied-but-unknown key is rejected
        # outright rather than silently falling back to the wrong client.
        from clients.models import ClientNetwork
        monitor_key = (data.get('client_key') or
                       request.headers.get('X-Monitor-Key', '')).strip()
        network = None
        if monitor_key:
            network = (ClientNetwork.objects.select_related('client')
                       .filter(monitor_key=monitor_key).first())
            if not network:
                return Response({'error': 'Unknown monitor key'},
                                status=status.HTTP_401_UNAUTHORIZED)
            client = network.client
        else:
            # Senders that predate monitor keys (call/social triage) keep the
            # original single-client behaviour.
            client = Client.objects.filter(is_active=True).first()
        if not client:
            return Response({'error': 'No client'}, status=status.HTTP_400_BAD_REQUEST)

        # pfSense gateway alerts are infrastructure telemetry, not customer
        # tickets. Filing them in the queue buried real tickets — a flapping WAN
        # alone can produce dozens a day. They sync into the network's own
        # record instead, shown in Configuration alongside the pfSense setup.
        if data.get('_ai_category') == 'network' or subject.startswith(('[NETWORK DOWN]', '[NETWORK UP]')):
            alert = self._record_network_alert(client, network, subject, body)
            return Response({'action': 'network_alert', 'alert_id': alert.id,
                             'kind': alert.kind}, status=status.HTTP_201_CREATED)

        # Use pre-computed AI fields or classify now
        if data.get('_ai_action'):
            ai_result = {
                'action':        data.get('_ai_action', 'ticket'),
                'priority':      data.get('_ai_priority', 'medium'),
                'sentiment':     data.get('_ai_sentiment', 'neutral'),
                'category':      data.get('_ai_category', 'general'),
                'summary':       data.get('_ai_summary', ''),
                'alert_message': data.get('_ai_alert_message', ''),
            }
        else:
            ai_result = _classify_email_with_ai(subject, from_email, from_name, body, client.name)

        action    = ai_result.get('action', 'ticket')
        priority  = ai_result.get('priority', 'low')
        sentiment = ai_result.get('sentiment', 'neutral')
        summary   = ai_result.get('summary', '')
        category  = ai_result.get('category', 'general')
        alert_msg = ai_result.get('alert_message', '')

        if action == 'alert':
            recipients = User.objects.filter(
                is_active=True,
                role__name__in=['admin', 'team_leader', 'supervisor', 'Admin', 'Supervisor', 'Team Leader'],
            )
            if not recipients.exists():
                recipients = User.objects.filter(is_active=True, is_staff=True)
            if not recipients.exists():
                recipients = User.objects.filter(is_active=True)

            title = f"Email Alert: {subject[:100]}"
            message = alert_msg or f"Inbound email from {from_name} <{from_email}>:\n\n{summary or body[:500]}"

            for user in recipients:
                Notification.objects.create(
                    recipient=user,
                    notification_type='system',
                    title=title,
                    message=message,
                    channel='in_app',
                )

            return Response({
                'action': 'alert',
                'alerts_created': recipients.count(),
                'summary': summary,
            }, status=status.HTTP_201_CREATED)

        # Default: create ticket with AI-derived type and SLA
        safe_priority = priority if priority in ('critical', 'high', 'medium', 'low') else Ticket.LOW
        ticket_type   = _CATEGORY_TO_TYPE.get(category, 'general')
        channel       = 'vicidial' if source == 'vicidial' else 'email'

        ticket = Ticket.objects.create(
            client=client,
            customer_name=from_name,
            customer_email=from_email,
            subject=subject[:500],
            description=body,
            channel=channel,
            priority=safe_priority,
            ticket_type=ticket_type,
            ai_summary=summary,
            ai_sentiment=sentiment,
            ai_suggested_category=category,
            # Name the specific link the alert came from (e.g. "PLDT Backup"),
            # so a client with several networks can tell them apart.
            channel_source=(network.name if network else ''),
        )

        # Auto-assign SLA policy and calculate deadlines
        sla_policy = _assign_sla(ticket, client, safe_priority, category)

        response_data = {
            'action': 'ticket',
            'ticket_number': ticket.ticket_number,
            'priority': safe_priority,
            'ticket_type': ticket_type,
            'sentiment': sentiment,
            'summary': summary,
            'sla_policy': sla_policy.name if sla_policy else None,
            'first_response_due': ticket.first_response_due.isoformat() if ticket.first_response_due else None,
            'resolution_due': ticket.resolution_due.isoformat() if ticket.resolution_due else None,
        }
        return Response(response_data, status=status.HTTP_201_CREATED)


def _classify_email_with_ai(subject, from_email, from_name, body, client_name):
    """Use Claude to classify an inbound email as a ticket or alert and extract metadata."""
    import json
    import anthropic
    from django.conf import settings

    api_key = getattr(settings, 'ANTHROPIC_API_KEY', '')
    if not api_key:
        return {'action': 'ticket', 'priority': 'low', 'sentiment': 'neutral', 'summary': '', 'category': ''}

    prompt = f"""You are a CRM triage assistant for {client_name}. Analyze this inbound email and classify it.

From: {from_name} <{from_email}>
Subject: {subject}
Body:
{body[:3000]}

Respond ONLY with valid JSON (no markdown, no extra text):
{{
  "action": "ticket" or "alert",
  "priority": "critical" | "high" | "medium" | "low",
  "sentiment": "positive" | "neutral" | "negative" | "angry",
  "category": "billing" | "technical" | "complaint" | "inquiry" | "escalation" | "network" | "social" | "hr" | "general",
  "summary": "1-2 sentence summary of the email",
  "alert_message": "only if action=alert: brief alert for supervisors"
}}

Rules:
- Use "alert" for: automated reports, spam, out-of-office replies, system notifications, internal team messages — anything that does NOT need an agent to respond.
- Use "ticket" for: customer complaints, service requests, billing questions, technical problems, anything needing a human response.
- priority: critical=outage/legal, high=strong frustration/hard deadline, medium=standard issue, low=general inquiry.
- category must be exactly one of the values listed above."""

    try:
        client = anthropic.Anthropic(api_key=api_key)
        message = client.messages.create(
            model='claude-haiku-4-5-20251001',
            max_tokens=256,
            messages=[{'role': 'user', 'content': prompt}],
        )
        text = message.content[0].text.strip()
        return json.loads(text)
    except Exception:
        return {'action': 'ticket', 'priority': 'low', 'sentiment': 'neutral', 'summary': '', 'category': ''}


class WebhookSocialMediaView(APIView):
    permission_classes = []

    def post(self, request):
        import hmac
        import hashlib
        from clients.models import Client
        from notifications.models import Notification
        from core.models import User

        secret = getattr(settings, 'EMAIL_WEBHOOK_SECRET', '')
        if secret:
            sig = request.headers.get('X-Webhook-Secret', '')
            if not hmac.compare_digest(sig, secret):
                return Response({'error': 'Unauthorized'}, status=status.HTTP_401_UNAUTHORIZED)

        data        = request.data
        platform    = (data.get('platform', 'social') or '').lower()
        sender      = data.get('sender_name', data.get('from', 'Unknown'))
        message     = data.get('message', data.get('text', ''))
        phone       = data.get('phone', '')
        conv_id     = data.get('conversation_id', '')
        action      = data.get('_ai_action', 'ticket')
        priority    = data.get('_ai_priority', 'low')
        sentiment   = data.get('_ai_sentiment', 'neutral')
        category    = data.get('_ai_category', 'general')
        summary     = data.get('_ai_summary', '')
        alert_msg   = data.get('_ai_alert_message', '')

        client = Client.objects.filter(is_active=True).first()
        if not client:
            return Response({'error': 'No client'}, status=status.HTTP_400_BAD_REQUEST)

        if action == 'alert':
            recipients = User.objects.filter(
                is_active=True,
                role__name__in=['admin', 'team_leader', 'supervisor', 'Admin', 'Supervisor', 'Team Leader'],
            )
            if not recipients.exists():
                recipients = User.objects.filter(is_active=True, is_staff=True)
            if not recipients.exists():
                recipients = User.objects.filter(is_active=True)

            title = f"{platform.title()} Alert — {sender}"
            msg_text = alert_msg or f"Social media message from {sender} ({platform}):\n\n{summary or message[:500]}"
            for user in recipients:
                Notification.objects.create(
                    recipient=user,
                    notification_type='system',
                    title=title,
                    message=msg_text,
                    channel='in_app',
                )
            return Response({
                'action': 'alert',
                'alerts_created': recipients.count(),
            }, status=status.HTTP_201_CREATED)

        description_lines = [
            f"[Social Media Inbound — {platform.title()}]",
            f"Sender: {sender}",
        ]
        if conv_id:
            description_lines.append(f"Conversation ID: {conv_id}")
        if summary:
            description_lines.append(f"Summary: {summary}")
        description_lines.append('')
        description_lines.append(message)

        ticket = Ticket.objects.create(
            client=client,
            customer_name=sender,
            customer_phone=phone,
            subject=f"[{platform.title()}] {sender} — {category.title()}",
            description='\n'.join(description_lines),
            channel='social_media',
            priority=priority if priority in ('critical', 'high', 'medium', 'low') else Ticket.LOW,
            ai_summary=summary,
            ai_sentiment=sentiment,
            ai_suggested_category=category,
        )
        return Response({
            'ticket_number': ticket.ticket_number,
            'action': 'ticket',
            'priority': priority,
        }, status=status.HTTP_201_CREATED)
