"""Gemini-powered assistant grounded on the Sphereflux website knowledge base."""

from __future__ import annotations

import logging
import re

from django.conf import settings

from .knowledge import (
    HANDOFF_TOKEN,
    SYSTEM_INSTRUCTIONS,
    build_knowledge_base,
    wants_human_handoff,
)

logger = logging.getLogger(__name__)

HANDOFF_REPLY = (
    "I am connecting you to our Sphereflux sales team for a proper quotation — "
    "we do not issue prices in chat.\n\n"
    "Please share your name, phone/WhatsApp or email, and a short project note "
    "in the form below. Sales will follow up from sales@sphereflux.co.ke "
    "(or WhatsApp 0718 679 683)."
)


def _strip_handoff_token(text: str) -> tuple[str, bool]:
    if not text:
        return '', False
    found = HANDOFF_TOKEN in text
    cleaned = text.replace(HANDOFF_TOKEN, '').strip()
    cleaned = re.sub(r'\n{3,}', '\n\n', cleaned)
    return cleaned, found


def generate_reply(user_message: str, history: list[dict] | None = None) -> dict:
    """
    Return {'reply': str, 'handoff': bool, 'reason': str}.
    Handoff is true when the visitor should be routed to a human (e.g. quotation).
    """
    message = (user_message or '').strip()
    if not message:
        return {
            'reply': 'Please share a question about our services, and I will help.',
            'handoff': False,
            'reason': '',
        }

    keyword_handoff = wants_human_handoff(message)

    if not settings.GEMINI_API_KEY:
        if keyword_handoff:
            return {
                'reply': HANDOFF_REPLY,
                'handoff': True,
                'reason': 'quotation_or_human_request',
            }
        return {
            'reply': (
                'Our chat assistant is almost ready. Meanwhile WhatsApp 0718 679 683, '
                'email sales@sphereflux.co.ke, or use the Contact page.'
            ),
            'handoff': False,
            'reason': '',
        }

    try:
        import google.generativeai as genai

        genai.configure(api_key=settings.GEMINI_API_KEY)
        model = genai.GenerativeModel(
            model_name=settings.GEMINI_MODEL,
            system_instruction=(
                f'{SYSTEM_INSTRUCTIONS}\n\n'
                f'=== WEBSITE KNOWLEDGE BASE ===\n{build_knowledge_base()}\n'
                '=== END KNOWLEDGE BASE ==='
            ),
        )

        chat_history = []
        for turn in (history or [])[-12:]:
            role = turn.get('role')
            text = (turn.get('content') or '').strip()
            if not text or role not in ('user', 'assistant'):
                continue
            chat_history.append({
                'role': 'user' if role == 'user' else 'model',
                'parts': [text],
            })

        prompt = message
        if keyword_handoff:
            prompt = (
                f'{message}\n\n'
                '[System note: This message looks like a quotation / human handoff request. '
                f'Confirm handoff briefly and include {HANDOFF_TOKEN}.]'
            )

        chat = model.start_chat(history=chat_history)
        response = chat.send_message(prompt)
        raw = (getattr(response, 'text', None) or '').strip()
        reply, token_handoff = _strip_handoff_token(raw)

        handoff = keyword_handoff or token_handoff
        if handoff and not reply:
            reply = HANDOFF_REPLY
        elif handoff and HANDOFF_TOKEN not in raw and 'sales' not in reply.lower():
            reply = f'{reply}\n\n{HANDOFF_REPLY}'.strip() if reply else HANDOFF_REPLY

        if not reply:
            reply = (
                'I could not draft a reply just now. Please try again, or reach '
                'sales@sphereflux.co.ke / WhatsApp 0718 679 683.'
            )

        return {
            'reply': reply,
            'handoff': handoff,
            'reason': 'quotation_or_human_request' if handoff else '',
        }
    except Exception:
        logger.exception('Gemini assistant failed')
        if keyword_handoff:
            return {
                'reply': HANDOFF_REPLY,
                'handoff': True,
                'reason': 'quotation_or_human_request',
            }
        return {
            'reply': (
                'I hit a temporary issue reaching the assistant. Please try again shortly, '
                'or contact sales@sphereflux.co.ke / WhatsApp 0718 679 683.'
            ),
            'handoff': False,
            'reason': '',
        }
