import asyncio
import aiohttp
import json
import os
from rubka.asynco import Robot, Message
from rubka.button import InlineBuilder
from rubka import ChatKeypadBuilder

TOKEN = "CCBGID0MLATZVZNGAZIBYCPGGWYTXYYZOPHWOPFNYXXXRIHVYSKROUOYLGIJOFFP"
API_KEY = "sk-uwEKiIuWlzlpeop4F3gLgw5JQQ0T9oanQefg86nZZdK47o4l"
API_URL = "https://api.gapgpt.app/v1/chat/completions"
DATA_FILE = "chatg8pt_data.json"

bot = Robot(
    TOKEN,
    web_hook="https://smokk.subatlas.site/v.php"
)

# ========== 👑 جایگاه ادمین ==========
ADMINS_LIST = ["b0I13oU0yaJ03928c974c575867508ac"]
# ====================================

chat_active = {}

def load_data():
    if os.path.exists(DATA_FILE):
        with open(DATA_FILE, "r", encoding="utf-8") as f:
            return json.load(f)
    return {"users": []}

def save_data(data):
    with open(DATA_FILE, "w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=4)

def admin_panel_kb():
    kb = ChatKeypadBuilder()
    kb.row(kb.button("stats_btn", "📊 آمار کاربران"))
    return kb.build(resize_keyboard=True)

async def ask_ai(prompt):
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    }
    
    payload = {
        "model": "gpt-3.5-turbo",
        "messages": [
            {"role": "user", "content": prompt}
        ],
        "temperature": 0.7
    }
    
    try:
        async with aiohttp.ClientSession() as session:
            async with session.post(API_URL, headers=headers, json=payload, timeout=30) as response:
                if response.status == 200:
                    data = await response.json()
                    return data["choices"][0]["message"]["content"]
                else:
                    return f"❌ خطا: وضعیت {response.status}"
    except Exception as e:
        return f"❌ خطا: {str(e)}"

@bot.on_message(commands=['start'])
async def start_handler(bot: Robot, message: Message):
    uid = str(message.chat_id)
    data = load_data()
    
    if uid not in data["users"]:
        data["users"].append(uid)
        save_data(data)
    
    chat_active[uid] = False
    
    inline = (
        InlineBuilder()
        .row(
            InlineBuilder().button_simple("start_chat", "گفتگو CԋAƚGPT✨")
        )
        .build()
    )
    
    await message.reply(
        "<b>درود! به CԋAƚGPT خوش اومدید برای گفتگو با ربات روی دکمه زیر کلیک کنید 🌱</b>",
        inline_keypad=inline,
        parse_mode="HTML"
    )

@bot.on_callback('start_chat')
async def start_chat(bot: Robot, message: Message):
    uid = str(message.chat_id)
    chat_active[uid] = True
    await message.answer(
        "<b>سلام! وقت بخیر 😊</b>\n\n<b>چطور می‌تونم کمکت کنم؟</b>",
        parse_mode="HTML"
    )

@bot.on_message(commands=['id'])
async def id_handler(bot: Robot, message: Message):
    uid = str(message.chat_id)
    await message.reply(
        f"<b>🆔 شناسه شما:</b>\n<code>{uid}</code>",
        parse_mode="HTML"
    )

@bot.on_message(commands=['panel'])
async def panel_handler(bot: Robot, message: Message):
    uid = str(message.chat_id)
    if uid in ADMINS_LIST:
        await message.reply_keypad(
            "<b>👑 پنل ادمین</b>",
            keypad=admin_panel_kb(),
            parse_mode="HTML"
        )
    else:
        await message.reply("<b>❌ دسترسی ندارید!</b>", parse_mode="HTML")

@bot.on_callback('stats_btn')
async def stats_btn(bot: Robot, message: Message):
    uid = str(message.chat_id)
    if uid in ADMINS_LIST:
        data = load_data()
        total_users = len(data["users"])
        await message.answer(
            f"<b>📊 آمار کاربران</b>\n\n👥 تعداد کل کاربران: {total_users}",
            parse_mode="HTML"
        )

@bot.on_message()
async def chat_handler(bot: Robot, message: Message):
    uid = str(message.chat_id)
    user_text = message.text
    
    if user_text.startswith('/'):
        return
    
    if chat_active.get(uid, False):
        await message.reply("<b>درحال بررسی و پاسخ . . . ⚡</b>", parse_mode="HTML")
        reply = await ask_ai(user_text)
        
        final_reply = f"{reply}\n\n🥷🏻 https://chatgpt.subatlas.site/GPT.PHP"
        await message.reply(final_reply)

if __name__ == "__main__":
    print("🤖 ربات CԋAƚGPT روشن شد...")
    asyncio.run(bot.run())