import re
import json
from collections import Counter
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from tickets.models import Ticket
from audit.models import AuditLog


# ---------------------------------------------------------------------------
# Built-in AI Engine — no external API required
# ---------------------------------------------------------------------------

KEYWORDS = {
    'billing':    ['bill', 'invoice', 'charge', 'payment', 'refund', 'fee', 'price', 'cost', 'overcharge', 'credit', 'debit', 'subscription', 'plan', 'amount', 'due', 'paid', 'unpaid'],
    'technical':  ['error', 'bug', 'issue', 'problem', 'not working', 'broken', 'fail', 'crash', 'slow', 'down', 'outage', 'connect', 'login', 'password', 'reset', 'update', 'install', 'network', 'internet', 'access'],
    'complaint':  ['complain', 'upset', 'angry', 'frustrated', 'unacceptable', 'terrible', 'worst', 'horrible', 'disappointed', 'dissatisfied', 'rude', 'awful', 'useless', 'waste', 'demand'],
    'inquiry':    ['question', 'ask', 'how', 'what', 'when', 'where', 'info', 'information', 'know', 'understand', 'explain', 'clarify', 'detail', 'help', 'guide', 'policy'],
    'hr':         ['employee', 'staff', 'leave', 'salary', 'payroll', 'attendance', 'hr', 'human resource', 'hire', 'resign', 'terminate', 'contract', 'benefits', 'holiday', 'vacation'],
    'application': ['resume', 'cv', 'curriculum vitae', 'job application', 'apply', 'applying', 'applicant', 'position', 'years of experience', 'work experience', 'attached my resume', 'attached is my resume', 'career', 'opportunity', 'opening', 'hiring'],
    'escalation': ['escalate', 'manager', 'supervisor', 'urgent', 'asap', 'immediately', 'critical', 'emergency', 'priority', 'legal', 'lawyer', 'sue', 'court', 'threat'],
    'network':    ['gateway', 'wan', 'lan', 'ping', 'packet', 'loss', 'latency', 'bandwidth', 'router', 'firewall', 'vpn', 'dns', 'ip', 'pfsense', 'isp', 'fiber', 'cable'],
    'social':     ['facebook', 'instagram', 'twitter', 'whatsapp', 'viber', 'social', 'post', 'comment', 'message', 'dm', 'follower'],
}

SENTIMENT_POS = ['thank', 'great', 'excellent', 'perfect', 'good', 'happy', 'satisfied', 'appreciate', 'wonderful', 'amazing', 'love', 'helpful', 'resolved', 'solved']
SENTIMENT_NEG = ['angry', 'furious', 'upset', 'terrible', 'awful', 'worst', 'hate', 'useless', 'unacceptable', 'disgusting', 'horrible', 'disappointed', 'frustrated', 'disgusted']
SENTIMENT_NEU = ['okay', 'fine', 'alright', 'neutral', 'normal', 'average']

TONES_ALIAS = {
    'friendly':   'empathetic',
    'apologetic': 'empathetic',
    'firm':       'formal',
    'empathetic': 'empathetic',
    'professional': 'professional',
    'formal':     'formal',
}

REPLY_TEMPLATES = {
    'billing': {
        'professional': (
            "Thank you for reaching out regarding your billing concern. "
            "We sincerely apologize for any inconvenience this may have caused. "
            "Our billing team will review your account and ensure this is resolved promptly. "
            "You can expect an update within 24–48 business hours. "
            "If you have any additional questions, please don't hesitate to contact us."
        ),
        'empathetic': (
            "I completely understand how frustrating billing issues can be, and I'm sorry you're experiencing this. "
            "Please know that we take this seriously. Our billing team will thoroughly review your account "
            "and work to resolve this as quickly as possible. We'll keep you updated every step of the way."
        ),
        'formal': (
            "Dear Valued Customer,\n\nThank you for bringing this billing matter to our attention. "
            "We acknowledge your concern and assure you that our Finance Department will conduct "
            "a thorough review of your account. A resolution will be provided within 2 business days. "
            "\n\nWe appreciate your patience and understanding."
        ),
    },
    'technical': {
        'professional': (
            "Thank you for reporting this technical issue. We apologize for the inconvenience. "
            "Our technical team has been notified and is investigating the matter. "
            "In the meantime, please try clearing your browser cache or restarting the application. "
            "We will provide a status update within 4 hours."
        ),
        'empathetic': (
            "I understand how disruptive technical problems can be, and I'm sorry you're dealing with this. "
            "Our tech team is on it right now. While they work on a fix, you might want to try restarting "
            "your device or using a different browser. I'll personally follow up with you once resolved."
        ),
        'formal': (
            "Dear Customer,\n\nWe acknowledge receipt of your technical support request. "
            "Our engineering team has been assigned to investigate and resolve the reported issue. "
            "An estimated resolution timeline will be communicated within 4 business hours. "
            "\n\nThank you for your continued patience."
        ),
    },
    'complaint': {
        'professional': (
            "Thank you for bringing this to our attention. We sincerely apologize for the experience "
            "you've had — this is not the standard of service we strive to deliver. "
            "Your feedback has been escalated to our quality team. A senior representative will "
            "contact you within 24 hours to address your concern and make this right."
        ),
        'empathetic': (
            "I am truly sorry for the experience you've had. Your frustration is completely valid, "
            "and I want you to know we take this very seriously. I'm personally escalating your case "
            "to ensure it receives the attention it deserves. We will make this right for you."
        ),
        'formal': (
            "Dear Valued Customer,\n\nWe sincerely regret the inconvenience you have experienced. "
            "Your complaint has been formally logged and escalated to our Customer Experience Director. "
            "A senior representative will contact you within 24 hours. We are committed to resolving "
            "this matter to your satisfaction."
        ),
    },
    'inquiry': {
        'professional': (
            "Thank you for your inquiry. We're happy to assist you with this. "
            "Our team will review your question and provide a comprehensive response within 24 hours. "
            "If this is urgent, please let us know and we will prioritize accordingly."
        ),
        'empathetic': (
            "Great question! We're glad you reached out. We want to make sure we give you the most "
            "accurate and helpful information, so our team will follow up within 24 hours with a "
            "detailed answer. Feel free to ask anything else in the meantime!"
        ),
        'formal': (
            "Dear Customer,\n\nThank you for your inquiry. We will research your request and provide "
            "a comprehensive response within one business day. Should you require immediate assistance, "
            "please contact our support hotline.\n\nBest regards."
        ),
    },
    'network': {
        'professional': (
            "Thank you for reporting this network issue. Our Network Operations Center has been alerted "
            "and is actively investigating. Network engineers are working to restore full connectivity. "
            "We will provide updates every 30 minutes until the issue is resolved."
        ),
        'empathetic': (
            "We understand how critical network connectivity is to your operations, and we sincerely "
            "apologize for this disruption. Our team is working urgently on restoring service. "
            "We'll keep you informed with regular updates until everything is back to normal."
        ),
        'formal': (
            "Dear Customer,\n\nA network degradation incident has been identified and is being actively "
            "investigated by our Network Operations Center. Our engineering team is working to restore "
            "full service. Status updates will be provided every 30 minutes."
        ),
    },
    'application': {
        'professional': (
            "Thank you for your interest in joining our team and for submitting your application. "
            "We have received your resume and it will be reviewed by our HR department. "
            "Should your qualifications match our current openings, we will reach out to you to schedule an interview. "
            "We appreciate your time and wish you all the best."
        ),
        'empathetic': (
            "Thank you so much for reaching out and sharing your resume with us! "
            "We truly appreciate your interest in being part of our team. "
            "Our HR team will carefully review your application and get in touch if there is a suitable opportunity for you. "
            "We wish you the very best in your job search!"
        ),
        'formal': (
            "Dear Applicant,\n\nThank you for your interest in a position with our organization. "
            "We acknowledge receipt of your application and curriculum vitae. "
            "Our Human Resources Department will review your credentials and contact you if your qualifications align with our current staffing requirements.\n\n"
            "We appreciate your interest and thank you for considering us as a potential employer."
        ),
    },
    'general': {
        'professional': (
            "Thank you for contacting us. We've received your message and a member of our team "
            "will review it and respond within 24 business hours. "
            "We appreciate your patience."
        ),
        'empathetic': (
            "Thank you for reaching out! We're here to help and will make sure your concern is "
            "addressed as quickly as possible. Expect to hear from us within 24 hours."
        ),
        'formal': (
            "Dear Customer,\n\nThank you for contacting our support team. Your request has been "
            "received and will be assigned to the appropriate department. "
            "A response will be provided within one business day.\n\nBest regards."
        ),
    },
}

NEXT_ACTIONS = {
    'billing': [
        "Verify account billing records and transaction history",
        "Contact Finance team to review the disputed charge",
        "Send billing statement copy to customer via email",
        "Apply credit/adjustment if overcharge confirmed",
    ],
    'technical': [
        "Escalate to Level 2 Technical Support",
        "Request system logs or screenshots from customer",
        "Check if issue affects other customers (systemic vs isolated)",
        "Schedule remote troubleshooting session if needed",
    ],
    'complaint': [
        "Escalate immediately to Team Leader / Supervisor",
        "Document the full complaint details in the ticket",
        "Contact customer within 2 hours with acknowledgment",
        "Prepare incident report for Quality Assurance review",
    ],
    'network': [
        "Alert Network Operations Center (NOC) immediately",
        "Check gateway status on pfSense dashboard",
        "Verify with ISP if there is a regional outage",
        "Enable failover/backup gateway if available",
        "Send service status update to all affected customers",
    ],
    'escalation': [
        "Immediately notify Supervisor / Team Leader",
        "Flag ticket as CRITICAL priority",
        "Document all customer communications thoroughly",
        "Prepare escalation report with timeline of events",
    ],
    'inquiry': [
        "Research the customer's question thoroughly",
        "Consult knowledge base for relevant articles",
        "Prepare a detailed and accurate response",
        "Follow up to confirm customer satisfaction",
    ],
    'application': [
        "Forward resume to HR Department for review",
        "Log applicant details in the recruitment tracker",
        "Send acknowledgment email to the applicant",
        "Close ticket after acknowledgment — not a support request",
    ],
    'general': [
        "Review ticket details and assign to appropriate team",
        "Contact customer within SLA timeframe",
        "Document all actions taken in the ticket thread",
        "Update ticket status as work progresses",
    ],
}


def _tokenize(text):
    return re.sub(r'[^\w\s]', ' ', text.lower()).split()


def _classify_text(subject, description):
    text = f"{subject} {description}".lower()
    scores = {cat: 0 for cat in KEYWORDS}
    for cat, words in KEYWORDS.items():
        for word in words:
            if word in text:
                scores[cat] += 1
    best = max(scores, key=scores.get)
    return best if scores[best] > 0 else 'general'


def _detect_sentiment(text):
    text = text.lower()
    pos = sum(1 for w in SENTIMENT_POS if w in text)
    neg = sum(1 for w in SENTIMENT_NEG if w in text)
    if neg > pos:
        return 'negative' if neg < 3 else 'angry'
    if pos > neg:
        return 'positive'
    return 'neutral'


def _detect_priority(subject, description, category):
    text = f"{subject} {description}".lower()
    if any(w in text for w in ['urgent', 'asap', 'critical', 'emergency', 'immediately', 'down', 'outage', 'not working', 'sue', 'legal']):
        return 'critical'
    if any(w in text for w in ['escalat', 'angry', 'furious', 'unacceptable', 'demand', 'loss', 'losing']):
        return 'high'
    if category in ('complaint', 'escalation', 'network'):
        return 'high'
    if category in ('billing', 'technical'):
        return 'medium'
    return 'low'


def _summarize(subject, description, max_len=200):
    desc = re.sub(r'\s+', ' ', description).strip()
    if len(desc) <= max_len:
        return f"{subject}. {desc}"
    # Take first 2 sentences
    sentences = re.split(r'(?<=[.!?])\s+', desc)
    summary = ' '.join(sentences[:2])
    if len(summary) > max_len:
        summary = summary[:max_len].rsplit(' ', 1)[0] + '…'
    return f"{subject}. {summary}"


def _get_reply(category, tone, customer_name, ticket_subject):
    templates = REPLY_TEMPLATES.get(category, REPLY_TEMPLATES['general'])
    mapped = TONES_ALIAS.get(tone, 'professional')
    tone_key = mapped if mapped in templates else 'professional'
    reply = templates[tone_key]
    if customer_name:
        reply = f"Dear {customer_name},\n\n" + reply if tone == 'formal' else reply
    return reply


# ---------------------------------------------------------------------------
# Claude API helper
# ---------------------------------------------------------------------------

def _claude_generate(prompt, model=None):
    """Call the configured AI provider. Returns text or None (falls back to templates)."""
    try:
        from core.models import SystemConfig
        cfg = SystemConfig.get()
        if not cfg.ai_enabled:
            return None
        provider = cfg.ai_provider or 'gemini'
        keys = cfg.ai_keys or {}
        api_key = keys.get(provider, '') or cfg.ai_api_key or ''
        m = model or cfg.ai_model or 'gemini-1.5-flash'

        # ── Anthropic Claude ──
        if provider == 'anthropic':
            if not api_key:
                import os; api_key = os.environ.get('ANTHROPIC_API_KEY', '')
            if not api_key: return None
            import anthropic
            client = anthropic.Anthropic(api_key=api_key)
            msg = client.messages.create(model=m, max_tokens=1024,
                messages=[{'role': 'user', 'content': prompt}])
            return msg.content[0].text.strip()

        # ── Google Gemini ──
        elif provider == 'gemini':
            if not api_key: return None
            import urllib.request, json as _json
            url = f'https://generativelanguage.googleapis.com/v1beta/models/{m}:generateContent?key={api_key}'
            body = _json.dumps({'contents': [{'parts': [{'text': prompt}]}]}).encode()
            req = urllib.request.Request(url, data=body, headers={'Content-Type': 'application/json'})
            with urllib.request.urlopen(req, timeout=15) as resp:
                data = _json.loads(resp.read())
            return data['candidates'][0]['content']['parts'][0]['text'].strip()

        # ── Groq ──
        elif provider == 'groq':
            if not api_key: return None
            import urllib.request, json as _json
            url = 'https://api.groq.com/openai/v1/chat/completions'
            body = _json.dumps({'model': m, 'messages': [{'role': 'user', 'content': prompt}], 'max_tokens': 1024}).encode()
            req = urllib.request.Request(url, data=body, headers={'Content-Type': 'application/json', 'Authorization': f'Bearer {api_key}'})
            with urllib.request.urlopen(req, timeout=15) as resp:
                data = _json.loads(resp.read())
            return data['choices'][0]['message']['content'].strip()

        # ── OpenAI ──
        elif provider == 'openai':
            if not api_key: return None
            import urllib.request, json as _json
            url = 'https://api.openai.com/v1/chat/completions'
            body = _json.dumps({'model': m, 'messages': [{'role': 'user', 'content': prompt}], 'max_tokens': 1024}).encode()
            req = urllib.request.Request(url, data=body, headers={'Content-Type': 'application/json', 'Authorization': f'Bearer {api_key}'})
            with urllib.request.urlopen(req, timeout=15) as resp:
                data = _json.loads(resp.read())
            return data['choices'][0]['message']['content'].strip()

    except Exception:
        return None


# ---------------------------------------------------------------------------
# Views
# ---------------------------------------------------------------------------

class AIReplyLibraryView(APIView):
    """Search previously-generated AI replies. Never calls the AI.

    This is the whole point of the archive: an agent can find and reuse a reply
    the AI already wrote, with the AI Assistant switched off and no API key
    configured — the search is a plain database query and costs nothing.

    Pass ``ticket_id`` with no ``q`` and it suggests matches derived from the
    ticket's own wording — the agent doesn't have to invent search terms.
    """

    # Words too common to say anything about which reply is relevant.
    STOPWORDS = {
        're', 'fwd', 'fw', 'the', 'a', 'an', 'and', 'or', 'but', 'if', 'then',
        'for', 'to', 'of', 'in', 'on', 'at', 'by', 'is', 'are', 'was', 'were',
        'be', 'been', 'it', 'this', 'that', 'my', 'your', 'our', 'their', 'i',
        'we', 'you', 'they', 'me', 'us', 'them', 'no', 'not', 'with', 'from',
        'has', 'have', 'had', 'do', 'does', 'did', 'can', 'will', 'would',
        'about', 'please', 'hi', 'hello', 'thanks', 'thank', 'regards', 'dear',
        'customer', 'support', 'ticket', 'email', 'inquiry', 'wants', 'want',
    }

    def _suggest_for_ticket(self, qs, request):
        """Rank archived replies against a ticket, using only the database.

        Same category first, then keyword overlap, then replies that agents
        have actually reused. No AI call anywhere in here.
        """
        import re as _re
        from django.db.models import Case, When, IntegerField, Value, Q

        ticket = Ticket.objects.filter(pk=request.query_params.get('ticket_id')).first()
        if not ticket:
            return qs.none()
        # Never leak another client's replies via a ticket id.
        qs = qs.filter(client_id=ticket.client_id).exclude(ticket_id=ticket.pk)

        category = (ticket.ai_suggested_category or ticket.ticket_type or '').strip()
        text = ' '.join(filter(None, [ticket.subject, ticket.ai_summary,
                                      (ticket.description or '')[:400]])).lower()
        words = [w for w in _re.findall(r'[a-z]{4,}', text) if w not in self.STOPWORDS]
        # Longest words first — they carry the most meaning ("refund" over "order").
        keywords = sorted(set(words), key=len, reverse=True)[:6]

        match = Q()
        if category:
            match |= Q(category__iexact=category)
        for w in keywords:
            match |= Q(body__icontains=w) | Q(subject__icontains=w) | Q(concern__icontains=w)
        if not match:
            return qs.none()

        return qs.filter(match).annotate(
            # A sent reply on the same category is the strongest signal.
            rank=Case(
                When(category__iexact=category, kind='sent', then=Value(3)),
                When(category__iexact=category, then=Value(2)),
                When(kind='sent', then=Value(1)),
                default=Value(0), output_field=IntegerField(),
            )
        ).order_by('-rank', '-used_count', '-created_at')

    def get(self, request):
        from ai_services.models import AIReplyArchive
        from core.scoping import scope_to_client
        from django.db.models import Q

        qs = scope_to_client(
            AIReplyArchive.objects.select_related('ticket', 'agent'), request.user)

        q = (request.query_params.get('q') or '').strip()
        auto = False
        if q:
            qs = qs.filter(Q(body__icontains=q) | Q(subject__icontains=q) |
                           Q(concern__icontains=q) | Q(category__icontains=q))
        elif request.query_params.get('ticket_id'):
            # No query typed: suggest from the ticket itself, so the agent sees
            # relevant past replies without having to think of search terms.
            auto = True
            qs = self._suggest_for_ticket(qs, request)
        kind = (request.query_params.get('kind') or '').strip()
        if kind in (AIReplyArchive.SENT, AIReplyArchive.DRAFT):
            qs = qs.filter(kind=kind)
        category = (request.query_params.get('category') or '').strip()
        if category:
            qs = qs.filter(category__iexact=category)

        try:
            limit = min(int(request.query_params.get('limit', 20)), 100)
        except (TypeError, ValueError):
            limit = 20

        results = [{
            'id': r.id,
            'kind': r.kind,
            'subject': r.subject,
            'body': r.body,
            'concern': r.concern,
            'category': r.category,
            'tone': r.tone,
            'used_count': r.used_count,
            'agent': (r.agent.get_full_name() or r.agent.username) if r.agent else '',
            'ticket_number': r.ticket.ticket_number if r.ticket else '',
            'created_at': r.created_at,
        } for r in qs[:limit]]
        return Response({'count': qs.count(), 'auto': auto, 'results': results})

    def post(self, request):
        """Mark an archived reply as reused — surfaces what actually works."""
        from ai_services.models import AIReplyArchive
        from core.scoping import scope_to_client
        from django.db.models import F

        qs = scope_to_client(AIReplyArchive.objects.all(), request.user)
        updated = qs.filter(pk=request.data.get('id')).update(used_count=F('used_count') + 1)
        if not updated:
            return Response({'error': 'Not found'}, status=status.HTTP_404_NOT_FOUND)
        return Response({'ok': True})


class AIReplyAssistantView(APIView):
    def post(self, request):
        ticket_id = request.data.get('ticket_id')
        action    = request.data.get('action', 'suggest_reply')
        tone      = request.data.get('tone', 'professional')
        custom_context = request.data.get('context', '')

        try:
            # Accept full ticket number (TKT202607190044), numeric suffix, or DB id
            tkt_num = str(ticket_id).strip()
            if not tkt_num.startswith('TKT'):
                tkt_num = f'TKT{tkt_num}'
            ticket = (
                Ticket.objects.filter(ticket_number=tkt_num).first()
                or Ticket.objects.filter(id=ticket_id).first()
            )
            if not ticket:
                raise Ticket.DoesNotExist
        except (Ticket.DoesNotExist, ValueError):
            return Response({'error': 'Ticket not found'}, status=status.HTTP_404_NOT_FOUND)

        category = _classify_text(ticket.subject, ticket.description)
        recent_comments = list(ticket.comments.order_by('created_at')[:5].values_list('body', flat=True))
        convo = '\n'.join(f'- {b[:300]}' for b in recent_comments) if recent_comments else 'No replies yet.'

        if action == 'suggest_reply':
            claude_prompt = (
                f"You are a professional customer support agent. Write a {tone} reply to this ticket.\n\n"
                f"Customer: {ticket.customer_name or 'Customer'}\n"
                f"Subject: {ticket.subject}\n"
                f"Message:\n{ticket.description or '(no description)'}\n\n"
                f"Recent conversation:\n{convo}\n\n"
                f"Write only the reply text. Be concise, helpful, and {tone}."
            )
            result = _claude_generate(claude_prompt) or _get_reply(category, tone, ticket.customer_name, ticket.subject)
            # Bank the draft so the next agent with a similar ticket can search
            # and reuse it instead of paying for another generation.
            from ai_services.auto_reply import archive_reply, ArchiveKind
            archive_reply(ticket, result, ArchiveKind.DRAFT, category=category, tone=tone,
                          agent=request.user if request.user.is_authenticated else None)

        elif action == 'rewrite':
            text = custom_context or ticket.description or ''
            claude_prompt = (
                f"Rewrite the following customer support reply to be more {tone} and professional.\n\n"
                f"Original:\n{text}\n\nRewritten reply only, no explanation."
            )
            result = _claude_generate(claude_prompt)
            if not result:
                sentiment = _detect_sentiment(text)
                result = (
                    f"I understand your frustration and sincerely apologize for the inconvenience. "
                    f"{text.strip()} We are committed to resolving this for you promptly."
                ) if sentiment in ('negative', 'angry') else (
                    f"Thank you for your message. {text.strip()} Please let us know if you need any further assistance."
                )

        elif action == 'summarize':
            claude_prompt = (
                f"Summarize this customer support ticket in 2-3 sentences.\n\n"
                f"Subject: {ticket.subject}\nMessage: {ticket.description or ''}\n\nConversation:\n{convo}"
            )
            # Generate ONCE. The old code called the API a second time just to
            # test whether the first call worked, doubling the cost of every
            # summarize.
            ai_text = _claude_generate(claude_prompt)
            result = ai_text or _summarize(ticket.subject, ticket.description)
            if not ai_text:
                recent = ticket.comments.order_by('-created_at')[:3]
                if recent:
                    result += f" ({recent.count()} reply/replies on record.)"

        elif action == 'suggest_action':
            claude_prompt = (
                f"You are a CRM team leader. Suggest 4 specific next actions for this support ticket.\n\n"
                f"Subject: {ticket.subject}\nMessage: {ticket.description or ''}\n"
                f"Priority: {ticket.priority}\nStatus: {ticket.status}\n\n"
                f"Return a numbered list of 4 actions only."
            )
            actions = NEXT_ACTIONS.get(category, NEXT_ACTIONS['general'])
            result = _claude_generate(claude_prompt) or '\n'.join(f"• {a}" for a in actions)

        elif action == 'generate_closure':
            resolution = custom_context or 'Issue resolved satisfactorily'
            claude_prompt = (
                f"Write professional closure notes for this resolved support ticket.\n\n"
                f"Ticket: {ticket.ticket_number}\nSubject: {ticket.subject}\n"
                f"Resolution: {resolution}\nHandled by: {request.user.get_full_name() or request.user.username}\n\n"
                f"Write concise closure notes only."
            )
            result = _claude_generate(claude_prompt) or (
                f"Ticket {ticket.ticket_number} — CLOSED\n"
                f"Issue: {ticket.subject}\n"
                f"Resolution: {resolution}\n"
                f"Category: {category.title()}\n"
                f"Handled by: {request.user.get_full_name() or request.user.username}"
            )
        else:
            result = _claude_generate(
                f"You are a support agent. Respond {tone}ly to: Subject: {ticket.subject}\n{ticket.description or ''}"
            ) or _get_reply(category, tone, ticket.customer_name, ticket.subject)

        # auto_respond: save draft comment immediately and set status to waiting_customer
        if action == 'auto_respond':
            from tickets.models import TicketComment
            comment = TicketComment.objects.create(
                ticket=ticket,
                author=request.user,
                comment_type=TicketComment.PUBLIC,
                body=result,
                is_ai_generated=True,
            )
            if ticket.status in (Ticket.NEW, Ticket.OPEN):
                ticket.status = Ticket.WAITING_CUSTOMER
                ticket.save(update_fields=['status'])
            AuditLog.objects.create(
                user=request.user, action='ai_auto_respond',
                model_name='Ticket', object_id=str(ticket.id),
                object_repr=ticket.ticket_number,
                extra_data={'comment_id': comment.id, 'engine': 'builtin'},
            )
            return Response({'result': result, 'action': action, 'category': category, 'comment_id': comment.id, 'sent': True})

        AuditLog.objects.create(
            user=request.user,
            action='ai_reply_used',
            model_name='Ticket',
            object_id=str(ticket.id),
            object_repr=ticket.ticket_number,
            extra_data={'action': action, 'tone': tone, 'engine': 'builtin'},
        )

        return Response({'result': result, 'action': action, 'category': category})


class AIClassifyTicketView(APIView):
    def post(self, request):
        ticket_id = request.data.get('ticket_id')
        try:
            tkt_num = str(ticket_id).strip()
            if not tkt_num.startswith('TKT'):
                tkt_num = f'TKT{tkt_num}'
            ticket = (
                Ticket.objects.filter(ticket_number=tkt_num).first()
                or Ticket.objects.filter(id=ticket_id).first()
            )
            if not ticket:
                raise Ticket.DoesNotExist
        except (Ticket.DoesNotExist, ValueError):
            return Response({'error': 'Ticket not found'}, status=status.HTTP_404_NOT_FOUND)

        text      = f"{ticket.subject} {ticket.description}"
        category  = _classify_text(ticket.subject, ticket.description)
        sentiment = _detect_sentiment(text)
        priority  = _detect_priority(ticket.subject, ticket.description, category)
        summary   = _summarize(ticket.subject, ticket.description)

        urgency_map = {'critical': 'immediate', 'high': 'high', 'medium': 'normal', 'low': 'low'}
        dept_map = {
            'billing': 'Finance / Billing', 'technical': 'Technical Support',
            'complaint': 'Customer Experience', 'inquiry': 'Customer Support',
            'hr': 'Human Resources', 'escalation': 'Supervisor / Management',
            'network': 'Network Operations', 'social': 'Social Media Team',
        }

        result = {
            'category':             category.title(),
            'priority':             priority,
            'sentiment':            sentiment,
            'urgency':              urgency_map.get(priority, 'normal'),
            'language':             'English',
            'summary':              summary,
            'suggested_department': dept_map.get(category, 'Customer Support'),
        }

        ticket.ai_summary           = summary
        ticket.ai_sentiment         = sentiment
        ticket.ai_suggested_category = category
        ticket.save(update_fields=['ai_summary', 'ai_sentiment', 'ai_suggested_category'])

        return Response(result)


class AIQualityReviewView(APIView):
    def post(self, request):
        reply_text = request.data.get('reply_text', '')
        ticket_id  = request.data.get('ticket_id')

        if not reply_text:
            return Response({'error': 'reply_text required'}, status=status.HTTP_400_BAD_REQUEST)

        issues      = []
        suggestions = []
        risky       = []
        score       = 100

        # Length check
        words = reply_text.split()
        if len(words) < 15:
            issues.append("Reply is too short — add more detail")
            suggestions.append("Expand the reply to at least 2–3 sentences")
            score -= 20
        if len(words) > 300:
            issues.append("Reply may be too long")
            suggestions.append("Consider trimming to the key points")
            score -= 5

        # Greeting check
        lower = reply_text.lower()
        if not any(w in lower for w in ['dear', 'hello', 'hi ', 'thank', 'greet']):
            issues.append("Missing greeting or opening")
            suggestions.append("Start with 'Dear [Name],' or 'Thank you for contacting us.'")
            score -= 10

        # Closing check
        if not any(w in lower for w in ['regards', 'sincerely', 'thank you', 'best', 'let us know', 'feel free']):
            issues.append("Missing professional closing")
            suggestions.append("Add a closing line such as 'Please don't hesitate to contact us.'")
            score -= 10

        # Risky language
        risky_words = ['guarantee', 'promise', 'never happen', 'sue', 'legal', 'compensate', 'free of charge']
        for word in risky_words:
            if word in lower:
                risky.append(f"Risky statement detected: '{word}' — ensure this is approved")
                score -= 15

        # Caps / aggressive tone
        caps_ratio = sum(1 for c in reply_text if c.isupper()) / max(len(reply_text), 1)
        if caps_ratio > 0.3:
            issues.append("Excessive capitalization — may appear aggressive")
            suggestions.append("Use normal casing for a professional tone")
            score -= 10

        # Negative words
        for neg in ['unfortunately', 'sorry', 'apologize', 'regret']:
            if neg in lower:
                suggestions.append(f"Pair '{neg}' with a solution or positive follow-up")
                break

        score = max(score, 0)
        tone = 'excellent' if score >= 85 else 'good' if score >= 70 else 'needs_improvement' if score >= 50 else 'poor'
        completeness = 'complete' if len(words) >= 30 else 'partial' if len(words) >= 15 else 'incomplete'

        return Response({
            'score':            score,
            'grammar_ok':       True,
            'tone':             tone,
            'completeness':     completeness,
            'issues':           issues,
            'suggestions':      suggestions,
            'risky_statements': risky,
            'approved':         score >= 70 and not risky,
        })


class AIReportSummaryView(APIView):
    def post(self, request):
        report_type = request.data.get('report_type', 'daily')
        data        = request.data.get('data', {})

        total    = data.get('total_tickets', 0)
        resolved = data.get('resolved', 0)
        open_t   = data.get('open', 0)
        breaches = data.get('sla_breaches', 0)
        critical = data.get('critical', 0)

        rate = round(resolved / total * 100) if total else 0

        if report_type == 'daily':
            summary = (
                f"Daily Operations Summary: {total} tickets received today, "
                f"{resolved} resolved ({rate}% resolution rate), {open_t} still open. "
            )
            if critical:
                summary += f"{critical} critical ticket(s) require immediate attention. "
            if breaches:
                summary += f"SLA breached on {breaches} ticket(s) — review recommended. "
            else:
                summary += "All SLA targets met today. "
            summary += "Continue monitoring open tickets and prioritize any critical items before end of shift."

        elif report_type == 'weekly':
            summary = (
                f"Weekly Performance Report: {total} tickets handled this week with a {rate}% resolution rate. "
                f"{open_t} tickets remain open going into the next period. "
            )
            if breaches:
                summary += f"There were {breaches} SLA breach(es) this week — root cause analysis recommended. "
            summary += (
                "Team performance is within acceptable range. "
                "Focus areas for next week: reduce average handle time on technical tickets "
                "and ensure all critical items are resolved same-day."
            )

        elif report_type == 'sla_breach':
            summary = (
                f"SLA Breach Analysis: {breaches} breach(es) identified. "
                f"Common causes include high ticket volume during peak hours, "
                f"insufficient staffing for technical issues, and delayed escalations. "
                "Recommended actions: review staffing schedule, improve first-contact resolution training, "
                "and ensure escalation protocols are followed for high-priority tickets."
            )
        else:
            summary = f"Report generated. Total tickets: {total}. Resolved: {resolved}. Open: {open_t}."

        return Response({'summary': summary})


def _crm_snapshot():
    """A compact, read-only snapshot of live CRM data for the assistant prompt.
    Aggregates only (no raw records), so it's cheap and safe."""
    from django.utils import timezone
    from django.db.models import Count
    from clients.models import Client
    from core.models import User
    CLOSED = ['resolved', 'closed', 'cancelled']
    now = timezone.now()
    today = now.date()
    tickets = Ticket.objects.all()
    active = tickets.exclude(status__in=CLOSED)
    L = []
    L.append(f"As of {now.strftime('%Y-%m-%d %H:%M')}.")
    L.append(f"Total tickets: {tickets.count()}; active (not resolved/closed/cancelled): {active.count()}.")
    by_status = tickets.values('status').annotate(n=Count('id')).order_by('-n')
    L.append("By status: " + ", ".join(f"{r['status']}={r['n']}" for r in by_status) + ".")
    by_pri = active.values('priority').annotate(n=Count('id')).order_by('-n')
    L.append("Active by priority: " + ", ".join(f"{r['priority']}={r['n']}" for r in by_pri) + ".")
    L.append(f"Created today: {tickets.filter(created_at__date=today).count()}; "
             f"resolved today: {tickets.filter(resolved_at__date=today).count()}.")
    L.append(f"Overdue (past resolution due, still active): {active.filter(resolution_due__lt=now).count()}; "
             f"unassigned active: {active.filter(assigned_agent__isnull=True).count()}.")
    by_client = active.values('client__name').annotate(n=Count('id')).order_by('-n')[:8]
    parts = [f"{r['client__name']}={r['n']}" for r in by_client if r['client__name']]
    if parts:
        L.append("Active tickets by client (top): " + ", ".join(parts) + ".")
    crit = list(active.filter(priority='critical').order_by('-created_at')[:5])
    if crit:
        L.append("Recent critical active: " + " | ".join(f"{t.ticket_number} {t.subject[:50]}" for t in crit) + ".")
    L.append(f"Clients: {Client.objects.count()}; active users: {User.objects.filter(is_active=True).count()}.")
    return "\n".join(L)


class AIAssistantView(APIView):
    """Admin AI assistant. Multi-turn chat folded into a single prompt (works
    across every configured provider), with a live read-only CRM data snapshot
    so it can answer questions about tickets/clients/workload."""
    def post(self, request):
        message = (request.data.get('message') or '').strip()
        history = request.data.get('history') or []
        if not message:
            return Response({'error': 'Message is required.'}, status=status.HTTP_400_BAD_REQUEST)

        user = request.user
        name = user.get_full_name() or user.username
        role = getattr(getattr(user, 'role', None), 'display_name', '') or 'Admin'

        try:
            snapshot = _crm_snapshot()
        except Exception:
            snapshot = "(live data unavailable)"

        preamble = (
            "You are the Altria CRM assistant, helping a call-center admin. "
            "Be concise, professional, and practical. Use plain text (short paragraphs "
            "or bullet points). Answer questions about tickets, clients, priorities, SLA "
            "and workload using the LIVE CRM DATA below. If a specific detail isn't in the "
            "data, say what you can see and note the limit rather than inventing numbers.\n\n"
            f"=== LIVE CRM DATA ===\n{snapshot}\n=== END LIVE CRM DATA ===\n\n"
            f"You are talking to: {name} ({role}).\n\n"
        )
        convo = ""
        for turn in history[-10:]:
            r = 'User' if turn.get('role') == 'user' else 'Assistant'
            c = (turn.get('content') or '').strip()
            if c:
                convo += f"{r}: {c}\n"
        prompt = f"{preamble}Conversation so far:\n{convo}User: {message}\nAssistant:"

        reply = _claude_generate(prompt)
        if not reply:
            reply = ("The AI provider isn't configured or is unavailable right now. "
                     "Check Configuration → General Settings (AI provider + API key).")
        return Response({'reply': reply})


class AIOutboundDraftView(APIView):
    """Draft an outbound email for an agent. Never sends.

    This is the assistant behind the composer under Clients -> Users / Agents.
    It differs from AIReplyAssistantView in one important way: there is no
    ticket and no conversation history, because this is first contact. The agent
    supplies the intent in their own words ("tell them the refund cleared, ref
    8823") and gets back a subject and body they can edit before sending.

    Deliberately draft-only. The agent always presses Send, so a bad
    generation is a wasted draft rather than a customer-facing mistake.
    """
    permission_classes = [IsAuthenticated]

    TONES = {'professional', 'friendly', 'formal', 'apologetic', 'concise'}

    def post(self, request):
        from core.scoping import is_ticket_readonly, scope_to_client
        from clients.models import Client

        intent = (request.data.get('intent') or '').strip()
        if not intent:
            return Response(
                {'error': 'Tell the assistant what the email should say.'},
                status=status.HTTP_400_BAD_REQUEST,
            )

        mode  = request.data.get('mode', 'draft')       # draft | rewrite | shorten
        tone  = request.data.get('tone', 'professional')
        if tone not in self.TONES:
            tone = 'professional'
        customer_name = (request.data.get('customer_name') or '').strip()
        subject_hint  = (request.data.get('subject') or '').strip()
        existing_body = (request.data.get('body') or '').strip()

        # Company/brand context, scoped so a portal user cannot pull another
        # tenant's details into their prompt.
        client_name = ''
        client_id = request.data.get('client')
        if client_id:
            c = scope_to_client(Client.objects.all(), request.user, lookup='id').filter(
                id=client_id).first()
            if c:
                client_name = c.name
        elif getattr(request.user, 'client_id', None):
            c = Client.objects.filter(id=request.user.client_id).first()
            client_name = c.name if c else ''

        agent_name = request.user.get_full_name() or request.user.username
        who = f'You are {agent_name}, a customer support agent'
        who += f' at {client_name}.' if client_name else '.'
        addressee = customer_name or 'the customer'

        if mode == 'rewrite' and existing_body:
            prompt = (
                f'{who}\n\n'
                f'Rewrite the email below so it is clearer and more {tone}. '
                f'Keep every fact and commitment exactly as written — do not invent '
                f'order numbers, dates, amounts, or promises.\n\n'
                f'Email:\n{existing_body}\n\n'
                f'Return only the rewritten email body.'
            )
        elif mode == 'shorten' and existing_body:
            prompt = (
                f'{who}\n\n'
                f'Shorten the email below to its essential points while staying {tone}. '
                f'Do not drop any fact, number or commitment.\n\n'
                f'Email:\n{existing_body}\n\n'
                f'Return only the shortened email body.'
            )
        else:
            prompt = (
                f'{who}\n\n'
                f'Write a {tone} email to {addressee}. This is the first message in '
                f'the conversation, so open appropriately and do not refer to earlier '
                f'correspondence.\n\n'
                f'What the email needs to say:\n{intent}\n\n'
                f'Rules:\n'
                f'- Use only the facts given above. Never invent order numbers, '
                f'dates, amounts, ticket references or policy details.\n'
                f'- If something essential is missing, leave a short [bracketed '
                f'placeholder] for the agent to fill in.\n'
                f'- Sign off as {agent_name}'
                + (f' at {client_name}' if client_name else '') + '.\n'
                f'- No subject line in the body, no preamble, no explanation.\n\n'
                f'Return only the email body.'
            )

        body = _claude_generate(prompt)
        if not body:
            return Response(
                {'error': 'AI is not configured or unavailable. Check Settings -> AI, '
                          'or write the email manually.'},
                status=status.HTTP_503_SERVICE_UNAVAILABLE,
            )

        # A subject only when the agent has not written one, so we never
        # overwrite what they typed.
        subject = subject_hint
        if not subject and mode == 'draft':
            s = _claude_generate(
                f'Write one short email subject line (max 9 words) for this email. '
                f'Return only the subject, no quotes.\n\n{body[:800]}'
            )
            subject = (s or intent[:80]).strip().strip('"').replace('\n', ' ')[:200]

        return Response({
            'subject': subject,
            'body': body,
            'tone': tone,
            'mode': mode,
            'ai_assisted': True,
            'can_send': not is_ticket_readonly(request.user),
        })
