"""AI Assistant — Google Gemini integration for Bobi with Persian personality."""
from __future__ import annotations

import logging
from typing import Optional

from google import genai
from google.genai import types
from openai import AsyncOpenAI
from telegram import Update
from telegram.constants import ParseMode
from telegram.ext import ContextTypes

from bot import db
from bot.config import OPENROUTER_API_KEY, OPENROUTER_MODEL
from bot.core.tasks import run_guarded
from bot.decorators import sudo_only
from bot.persian_router import register_mixed
from bot.services.emotion import build_emotion_instruction, detect_emotion
from bot.services.learning_runtime import learning_instruction
from bot.services.memory_graph import memory_graph_context
from bot.services.persona import persona_instruction
from bot.services.personality import build_personality_context, remember_user
from bot.services.conversation import conversation_context, touch_conversation
from bot.services.social import (
    build_relationship_context,
    get_group_mood,
    recall_memory,
    social_summary,
    timeline_memory,
)

logger = logging.getLogger(__name__)

_client: Optional[genai.Client] = None
_openrouter_client: Optional[AsyncOpenAI] = None

SYSTEM_PROMPT = (
    "تو یه ربات تلگرامی به اسم 'bobi' (بابی) هستی که با پایتون نوشته شده. "
    "شخصیت تو: دوستانه، بامزه، کمی شوخ‌طبع، و خون‌گرم. "
    "با کاربرا مثل دوست حرف میزنی، نه مثل یه دستیار رسمی. "
    "قوانین:\n"
    "1. فقط به فارسی روان و محاوره‌ای جواب بده\n"
    "2. جواب‌ها مختصر باشه (حداکثر ۳-۴ خط)\n"
    "3. از کلمات خودمونی و غیررسمی استفاده کن\n"
    "4. اگه سوال انگلیسی هم باشه، به فارسی جواب بده\n"
    "5. می‌تونی از ایموجی استفاده کنی، ولی نه بیش از حد\n"
    "6. اگه چیزی رو بلد نیستی، بگو 'نمی‌دونم' صادقانه\n"
    "7. اگه کاربر ناراحته، باهاش همدردی کن\n"
    "8. هیچ وقت ادعای انسان بودن نکن - تو یه رباتی"
)


def _init_gemini() -> bool:
    """Initialize Google Gemini client via google.genai. Returns True if available."""
    global _client
    if _client is not None:
        return True
    try:
        from bot.config import os as config_os
        api_key = config_os.getenv("GEMINI_API_KEY", "")
        if not api_key:
            logger.warning("GEMINI_API_KEY not set — AI assistant disabled")
            _client = False  # type: ignore
            return False
        _client = genai.Client(api_key=api_key)
        return True
    except Exception as e:
        logger.warning("Gemini init failed: %s", e)
        _client = False  # type: ignore
        return False


def _init_openrouter() -> bool:
    global _openrouter_client

    if _openrouter_client is not None:
        return True

    if not OPENROUTER_API_KEY:
        logger.warning("OPENROUTER_API_KEY missing")
        return False

    _openrouter_client = AsyncOpenAI(
        base_url="https://openrouter.ai/api/v1",
        api_key=OPENROUTER_API_KEY,
    )

    logger.info("OpenRouter initialized")

    return True


async def _ask_openrouter(prompt: str, chat_id: int = 0, user_id: int = 0) -> Optional[str]:
    if not _init_openrouter():
        return None

    emotion = detect_emotion(prompt)
    group_mood = get_group_mood(chat_id)

    messages = [
        {
            "role": "system",
            "content": (
                SYSTEM_PROMPT
                + "\n\n"
                + persona_instruction()
                + "\n\n"
                + learning_instruction()
                + "\n\n"
                + memory_graph_context(user_id)
                + "\n\n"
                + build_personality_context(user_id)
                + "\n\n"
                + build_relationship_context(chat_id, user_id)
                + "\n\n"
                + recall_memory(chat_id, user_id)
                + "\n\n"
                + await timeline_memory(chat_id, user_id)
                + "\n\n"
                + social_summary(chat_id)
                + "\n\n"
                + conversation_context(chat_id)
                + "\n\n"
                + f"حال و هوای فعلی گروه: {group_mood}\n\n"
                + build_emotion_instruction(emotion)
            ),
        }
    ]

    if chat_id:
        try:
            ctx = await db.get_context(chat_id)

            for m in ctx[-8:]:
                messages.append(
                    {
                        "role": m.get("role", "user"),
                        "content": m.get("text", ""),
                    }
                )
        except Exception as e:
            logger.warning("Context loading failed: %s", e)

    messages.append(
        {
            "role": "user",
            "content": prompt,
        }
    )

    response = await _openrouter_client.chat.completions.create(
        model=OPENROUTER_MODEL,
        messages=messages,
        temperature=0.8,
        max_tokens=1200,
    )

    if not response.choices:
        return None

    return response.choices[0].message.content


async def _ask_gemini(prompt: str, chat_id: int = 0, use_context: bool = True) -> Optional[str]:
    """Send a prompt to Gemini with optional conversation context and return Persian response."""
    if not _client and not _init_gemini():
        return None
    try:
        full_prompt = SYSTEM_PROMPT + "\n\n"

        if use_context and chat_id:
            ctx = await db.get_context(chat_id)
            if ctx:
                full_prompt += "گفتگوی اخیر:\n"
                for m in ctx:
                    role = "کاربر" if m.get("role") == "user" else "بابی"
                    full_prompt += f"{role}: {m['text']}\n"
                full_prompt += "\n"

        full_prompt += f"کاربر:\n{prompt}\n\nبابی:"

        resp = await _client.aio.models.generate_content(
            model="gemini-2.0-flash",
            contents=full_prompt,
            config=types.GenerateContentConfig(
                temperature=0.7,
                max_output_tokens=1024,
            ),
        )
        return resp.text.strip() if resp and resp.text else None
    except Exception as e:
        logger.error("Gemini API error: %s", e)
        return None


async def ai_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Ask the AI assistant a question (supports conversation context)."""
    message = update.message
    if not message:
        return
    text = message.text or ""
    parts = text.split(maxsplit=1)
    chat_id = update.effective_chat.id if update.effective_chat else 0
    user_id = update.effective_user.id if update.effective_user else 0

    if len(parts) < 2:
        await message.reply_text(
            "🤖 <b>دستیار هوش مصنوعی bobi</b>\n\n"
            "از من هوش مصنوعی سوال بپرس!\n\n"
            "مثال: <code>/ai بهترین زبان برنامه‌نویسی چیست؟</code>\n"
            "فارسی: <code>هوش مصنوعی هوای امروز چطوره؟</code>\n"
            "✓ از تاریخچه گفتگو هم استفاده می‌کنم!",
            parse_mode=ParseMode.HTML,
        )
        return
    prompt = parts[1]

    remember_user(
        user_id,
        update.effective_user.first_name if update.effective_user else None,
        prompt,
    )

    if not _init_openrouter() and not _init_gemini():
        await message.reply_text(
            "❌ AI provider فعال نیست.",
            parse_mode=ParseMode.HTML,
        )
        return

    await db.remember_message(chat_id, user_id, prompt)

    status = await message.reply_text("🤖 در حال فکر کردن...")
    try:
        answer = await run_guarded(
            "openrouter.request",
            _ask_openrouter(prompt, chat_id=chat_id, user_id=user_id),
            timeout=35,
        )

        if not answer:
            answer = await run_guarded(
                "gemini.request",
                _ask_gemini(prompt, chat_id=chat_id, use_context=True),
                timeout=25,
            )

        if answer:
            touch_conversation(chat_id, user_id, prompt)

            if len(answer) > 4000:
                answer = answer[:4000] + "\n\n..."
            await status.edit_text(
                f"🤖 <b>پاسخ:</b>\n\n{answer}",
                parse_mode=ParseMode.HTML,
            )
        else:
            await status.edit_text("❌ AI timeout یا پاسخ خالی دریافت شد.")
    except Exception as e:
        logger.exception("AI error: %s", e)
        await status.edit_text(f"⚠️ خطا: {e}")


async def ask_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Alias for /ai with Persian command."""
    await ai_cmd(update, context)


@sudo_only
async def aistatus_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Check AI assistant status."""
    available = _init_openrouter() or _init_gemini()

    if available:
        await update.message.reply_text(
            f"🤖 <b>وضعیت هوش مصنوعی</b>\n\n✅ فعال\n🧠 مدل: <code>{OPENROUTER_MODEL}</code>",
            parse_mode=ParseMode.HTML,
        )
    else:
        await update.message.reply_text(
            "❌ <b>وضعیت هوش مصنوعی</b>\n\nغیرفعال — GEMINI_API_KEY را تنظیم کنید.",
            parse_mode=ParseMode.HTML,
        )


def register(app) -> None:
    register_mixed(
        app,
        {
            "ai": ai_cmd,
            "ask": ai_cmd,
            "gemini": ai_cmd,
            "aistatus": aistatus_cmd,
        },
        {
            "هوش مصنوعی": ai_cmd,
            "سوال": ai_cmd,
            "سوال کن": ai_cmd,
            "بپرس": ai_cmd,
            "هوش": ai_cmd,
            "AI": ai_cmd,
            "وضعیت هوش": aistatus_cmd,
            "وضعیت AI": aistatus_cmd,
        },
    )
