"""AI-powered moderation — use Gemini for context-aware content analysis."""
from __future__ import annotations

import logging
from typing import Optional

from telegram import Update
from telegram.constants import ParseMode
from telegram.error import BadRequest, Forbidden
from telegram.ext import ContextTypes

from bot import db
from bot.persian_router import register_mixed

logger = logging.getLogger(__name__)

# Gemini client (lazy init)
_ai_client = None


def _get_ai_client():
    global _ai_client
    if _ai_client is None:
        try:
            from google import genai
            import os
            api_key = os.getenv("GEMINI_API_KEY", "")
            if api_key:
                _ai_client = genai.Client(api_key=api_key)
        except Exception as e:
            logger.warning(f"Gemini init failed: {e}")
    return _ai_client


async def analyze_toxicity(text: str) -> Optional[dict]:
    """Analyze text for toxicity using Gemini. Returns {is_toxic, score, reason} or None."""
    client = _get_ai_client()
    if not client:
        return None

    try:
        from google.genai import types
        response = client.models.generate_content(
            model="gemini-2.0-flash",
            contents=f"""Analyze this message for spam/toxicity/harassment.
Rate severity 0-10 (0=safe, 10=very toxic).
Respond in JSON format only:
{{"score": <number>, "category": "<spam|toxic|harassment|scam|safe>", "reason": "<brief reason in Persian>}}

Message: {text}""",
            config=types.GenerateContentConfig(
                max_output_tokens=100,
                temperature=0.1,
            ),
        )
        result_text = response.text.strip()

        # Parse JSON response
        import json
        # Try to extract JSON from response
        if "{" in result_text and "}" in result_text:
            json_str = result_text[result_text.index("{"):result_text.rindex("}") + 1]
            return json.loads(json_str)
    except Exception as e:
        logger.debug(f"AI toxicity analysis failed: {e}")
    return None


async def ai_moderate_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Analyze a message for toxicity: reply to a message and say 'تحلیل'"""
    if not update.message.reply_to_message:
        await update.message.reply_text("روی یه پیام ریپلای کن و بگو «تحلیل»")
        return

    target_msg = update.message.reply_to_message
    text = target_msg.text or target_msg.caption or ""
    if not text:
        await update.message.reply_text("این پیام متنی نداره.")
        return

    await update.message.reply_text("🔍 در حال تحلیل هوشمند...")

    result = await analyze_toxicity(text)
    if not result:
        await update.message.reply_text("❌ تحلیل هوش مصنوعی در دسترس نیست.")
        return

    score = result.get("score", 0)
    category = result.get("category", "safe")
    reason = result.get("reason", "بدون توضیح")

    category_fa = {
        "spam": "اسپم",
        "toxic": "توکسیک",
        "harassment": "آزار و اذیت",
        "scam": "کلاهبرداری",
        "safe": "امن",
    }

    if score >= 7:
        emoji = "🔴"
        verdict = "خطرناک"
    elif score >= 4:
        emoji = "🟡"
        verdict = "مشکوک"
    else:
        emoji = "🟢"
        verdict = "امن"

    text = (
        f"{emoji} <b>تحلیل هوشمند پیام</b>\n\n"
        f"📊 امتیاز: <b>{score}/10</b>\n"
        f"🏷 دسته: <b>{category_fa.get(category, category)}</b>\n"
        f"📝 توضیح: {reason}\n"
        f"⚖️ نتیجه: <b>{verdict}</b>"
    )
    await update.message.reply_text(text, parse_mode=ParseMode.HTML)


async def ai_warn_user(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Use AI to suggest appropriate moderation action."""
    if not update.message.reply_to_message:
        await update.message.reply_text("روی یه پیام ریپلای کن.")
        return

    target_msg = update.message.reply_to_message
    text = target_msg.text or target_msg.caption or ""
    if not text:
        await update.message.reply_text("این پیام متنی نداره.")
        return

    result = await analyze_toxicity(text)
    if not result:
        await update.message.reply_text("❌ تحلیل هوش مصنوعی در دسترس نیست.")
        return

    score = result.get("score", 0)
    category = result.get("category", "safe")

    if score >= 8:
        suggestion = "بن (خطرناک)"
        action = "ban"
    elif score >= 6:
        suggestion = "سکوت ۳۰ دقیقه"
        action = "mute"
    elif score >= 4:
        suggestion = "اخطار"
        action = "warn"
    else:
        suggestion = "نیازی به برخورد نیست"
        action = "none"

    text = (
        f"🤖 <b>پیشنهاد هوش مصنوعی:</b>\n\n"
        f"📊 امتیاز: {score}/10\n"
        f"🏷 دسته: {category}\n"
        f"⚖️ پیشنهاد: <b>{suggestion}</b>"
    )
    await update.message.reply_text(text, parse_mode=ParseMode.HTML)


def register(app) -> None:
    register_mixed(
        app,
        {
            "ai_mod": ai_moderate_cmd,
            "ai_warn": ai_warn_user,
        },
        {
            "تحلیل": ai_moderate_cmd,
            "تحلیل هوشمند": ai_moderate_cmd,
            "بررسی پیام": ai_moderate_cmd,
            "پیشنهاد برخورد": ai_warn_user,
        },
    )
