#!/usr/bin/env python3
import os
import json
import logging
import requests
from datetime import datetime
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler, MessageHandler, Filters

# ============ تنظیمات ============
TOKEN = "8575116565:AAGmfMUyJGcB9Fb02KhqxIg108AiBumrMCA"
ADMIN_ID = 8438594855

# API Key OpenRouter
OPENROUTER_API_KEY = "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"
OPENROUTER_URL = "https://openrouter.ai/api/v1/chat/completions"

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# ============ منو ============
def menu():
    kb = [
        [InlineKeyboardButton("💬 چت با هوش مصنوعی", callback_data="chat")],
        [InlineKeyboardButton("📜 تاریخچه", callback_data="history")],
        [InlineKeyboardButton("🗑️ پاک کردن تاریخچه", callback_data="clear_history")],
        [InlineKeyboardButton("❓ راهنما", callback_data="help")]
    ]
    return InlineKeyboardMarkup(kb)

def start(update, context):
    uid = update.effective_user.id
    
    if uid != ADMIN_ID:
        update.message.reply_text("❌ شما دسترسی به این ربات ندارید!")
        return
    
    if 'chat_history' not in context.user_data:
        context.user_data['chat_history'] = []
    
    update.message.reply_text(
        "🤖 **ربات هوش مصنوعی DeepSeek**\n\n"
        "🔹 با هوش مصنوعی DeepSeek\n"
        "🔹 قابلیت چت و مکالمه\n\n"
        "📌 یکی از گزینه‌های زیر را انتخاب کنید:",
        reply_markup=menu(),
        parse_mode='Markdown'
    )

# ============ چت با هوش مصنوعی ============
def chat(update, context):
    q = update.callback_query
    q.answer()
    
    uid = q.from_user.id
    if uid != ADMIN_ID:
        q.edit_message_text("❌ شما دسترسی به این بخش ندارید!")
        return
    
    if 'chat_history' not in context.user_data:
        context.user_data['chat_history'] = []
    
    q.edit_message_text(
        "💬 **حالت چت فعال شد**\n\n"
        "پیام خود را ارسال کنید.\n"
        "هوش مصنوعی DeepSeek به شما پاسخ خواهد داد.\n\n"
        "🔙 برای بازگشت روی دکمه زیر کلیک کنید.",
        reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🔙 بازگشت", callback_data="back")]]),
        parse_mode='Markdown'
    )
    context.user_data['chat_mode'] = True

def handle_chat(update, context):
    uid = update.effective_user.id
    if uid != ADMIN_ID:
        return
    
    if not context.user_data.get('chat_mode'):
        return
    
    user_message = update.message.text
    
    loading_msg = update.message.reply_text("⏳ در حال پردازش...")
    
    history = context.user_data.get('chat_history', [])
    history.append({"role": "user", "content": user_message})
    
    if len(history) > 20:
        history = history[-20:]
    
    try:
        # فقط از مدل DeepSeek استفاده کن
        model = "deepseek/deepseek-chat"
        
        response = requests.post(
            OPENROUTER_URL,
            headers={
                "Authorization": f"Bearer {OPENROUTER_API_KEY}",
                "Content-Type": "application/json",
                "HTTP-Referer": "https://t.me/YourBot",
                "X-Title": "AI Bot"
            },
            json={
                "model": model,
                "messages": history,
                "max_tokens": 1000,
                "temperature": 0.7
            },
            timeout=30
        )
        
        if response.status_code == 200:
            data = response.json()
            ai_response = data["choices"][0]["message"]["content"]
            
            history.append({"role": "assistant", "content": ai_response})
            context.user_data['chat_history'] = history
            
            loading_msg.delete()
            update.message.reply_text(
                f"🤖 **پاسخ DeepSeek:**\n\n{ai_response}",
                parse_mode='Markdown'
            )
        else:
            error_msg = response.json().get('error', {}).get('message', 'نامشخص')
            loading_msg.edit_text(
                f"❌ خطا در ارتباط با هوش مصنوعی!\n\n"
                f"📌 دلیل: {error_msg}\n\n"
                f"💡 راه‌حل:\n"
                f"1️⃣ چند دقیقه دیگر تلاش کنید\n"
                f"2️⃣ یا از مدل جایگزین استفاده کنید\n\n"
                f"برای استفاده از مدل جایگزین، دستور `/switch` را بزنید."
            )
            
    except requests.exceptions.Timeout:
        loading_msg.edit_text("❌ زمان پاسخ‌دهی به پایان رسید! دوباره تلاش کنید.")
    except Exception as e:
        loading_msg.edit_text(f"❌ خطا: {str(e)}")

# ============ تغییر مدل ============
def switch_model(update, context):
    uid = update.effective_user.id
    if uid != ADMIN_ID:
        update.message.reply_text("❌ شما دسترسی ندارید!")
        return
    
    models = [
        "deepseek/deepseek-chat",
        "google/gemini-flash-1.5",
        "microsoft/phi-3-mini-128k-instruct:free",
        "meta-llama/llama-3.2-3b-instruct:free"
    ]
    
    kb = []
    for model in models:
        kb.append([InlineKeyboardButton(model, callback_data=f"model_{model}")])
    kb.append([InlineKeyboardButton("🔙 بازگشت", callback_data="back")])
    
    update.message.reply_text(
        "🔀 **انتخاب مدل هوش مصنوعی**\n\n"
        "مدل مورد نظر خود را انتخاب کنید:",
        reply_markup=InlineKeyboardMarkup(kb),
        parse_mode='Markdown'
    )

def select_model(update, context):
    q = update.callback_query
    q.answer()
    
    uid = q.from_user.id
    if uid != ADMIN_ID:
        q.edit_message_text("❌ شما دسترسی به این بخش ندارید!")
        return
    
    model = q.data.replace("model_", "")
    context.user_data['selected_model'] = model
    
    q.edit_message_text(
        f"✅ **مدل تغییر کرد!**\n\n"
        f"🔹 مدل جدید: `{model}`\n\n"
        f"📌 حالا می‌توانید ادامه دهید.",
        reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("💬 چت", callback_data="chat")]]),
        parse_mode='Markdown'
    )

# ============ تاریخچه ============
def show_history(update, context):
    q = update.callback_query
    q.answer()
    
    uid = q.from_user.id
    if uid != ADMIN_ID:
        q.edit_message_text("❌ شما دسترسی به این بخش ندارید!")
        return
    
    history = context.user_data.get('chat_history', [])
    
    if not history:
        q.edit_message_text(
            "📜 **تاریخچه**\n\n"
            "📭 هنوز هیچ پیامی ارسال نشده است!",
            reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🔙 بازگشت", callback_data="back")]]),
            parse_mode='Markdown'
        )
        return
    
    text = "📜 **تاریخچه مکالمات**\n\n"
    for i, msg in enumerate(history[-10:]):
        role = "👤 شما" if msg["role"] == "user" else "🤖 ربات"
        content = msg["content"][:100] + "..." if len(msg["content"]) > 100 else msg["content"]
        text += f"{i+1}. {role}: {content}\n\n"
    
    kb = [
        [InlineKeyboardButton("🗑️ پاک کردن تاریخچه", callback_data="clear_history")],
        [InlineKeyboardButton("🔙 بازگشت", callback_data="back")]
    ]
    q.edit_message_text(text, reply_markup=InlineKeyboardMarkup(kb), parse_mode='Markdown')

def clear_history(update, context):
    q = update.callback_query
    q.answer()
    
    uid = q.from_user.id
    if uid != ADMIN_ID:
        q.edit_message_text("❌ شما دسترسی به این بخش ندارید!")
        return
    
    context.user_data['chat_history'] = []
    q.edit_message_text(
        "🗑️ **تاریخچه با موفقیت پاک شد!**",
        reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("🔙 بازگشت", callback_data="back")]]),
        parse_mode='Markdown'
    )

# ============ راهنما ============
def help_cmd(update, context):
    q = update.callback_query
    q.answer()
    
    text = (
        "📌 **راهنمای استفاده**\n\n"
        "💬 **چت با هوش مصنوعی:**\n"
        "   سوالات خود را بپرسید و پاسخ دریافت کنید.\n\n"
        "📜 **تاریخچه:**\n"
        "   مشاهده مکالمات قبلی.\n\n"
        "🔀 **تغییر مدل:**\n"
        "   با دستور `/switch` مدل را عوض کنید.\n\n"
        "🔹 **مدل‌های موجود:**\n"
        "   • DeepSeek Chat\n"
        "   • Google Gemini\n"
        "   • Microsoft Phi\n"
        "   • Meta Llama\n\n"
        "⚠️ همه مدل‌ها رایگان هستند"
    )
    
    kb = [[InlineKeyboardButton("🔙 بازگشت", callback_data="back")]]
    q.edit_message_text(text, reply_markup=InlineKeyboardMarkup(kb), parse_mode='Markdown')

def back(update, context):
    q = update.callback_query
    q.answer()
    
    context.user_data['chat_mode'] = False
    context.user_data['image_mode'] = False
    
    q.edit_message_text(
        "🏠 **منوی اصلی**",
        reply_markup=menu(),
        parse_mode='Markdown'
    )

# ============ اجرا ============
def main():
    updater = Updater(TOKEN, use_context=True)
    dp = updater.dispatcher
    
    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(CommandHandler("switch", switch_model))
    
    dp.add_handler(CallbackQueryHandler(chat, pattern="^chat$"))
    dp.add_handler(CallbackQueryHandler(show_history, pattern="^history$"))
    dp.add_handler(CallbackQueryHandler(clear_history, pattern="^clear_history$"))
    dp.add_handler(CallbackQueryHandler(help_cmd, pattern="^help$"))
    dp.add_handler(CallbackQueryHandler(back, pattern="^back$"))
    dp.add_handler(CallbackQueryHandler(select_model, pattern="^model_"))
    
    dp.add_handler(MessageHandler(Filters.text & ~Filters.command, handle_chat))
    
    logger.info("🤖 ربات هوش مصنوعی DeepSeek راه‌اندازی شد!")
    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()