import telebot
from telebot import apihelper
import requests
import re
import main


TOKEN = '8933747378:AAEBXsgaJ9ktEYi5cwb_dCbqQgRyxDiUwjA'
# PROXY_IP = '127.0.0.1'
# PROXY_PORT = '63141'

# apihelper.proxy = {'https': f'http://{PROXY_IP}:{PROXY_PORT}'}

bot = telebot.TeleBot(TOKEN)

chatting_users = set()

@bot.message_handler(commands=['chatbot'])
def chat_bot_starter(message):

    bot.reply_to(message,
                 "🤖 سیستم چت‌بات فعال شد.\nلطفاً سوال خود را بپرسید (برای خروج کلمه 'exit' یا 'خروج' را بفرستید):")


    bot.register_next_step_handler(message, chat_loop)


def chat_loop(message):


    user_id = message.from_user.id
    chatting_users.add(user_id)
    user_query = message.text.strip()

    if user_query.lower() in ["exit", "quit", "خروج"]:
        chatting_users.remove(user_id)
        bot.reply_to(message, "خداحافظ! 👋 حالت چت‌بات غیرفعال شد. حالا می‌توانید قیمت‌ها را بپرسید.")
        return


    try:

        answer = main.rag_agent.answer(user_query)

        bot.reply_to(message, f"🤖 Agent's Answer:\n\n{answer}")

    except Exception as e:
        bot.reply_to(message, "❌ متاسفانه خطایی در پردازش سوال رخ داد.")
        print(f"Error: {e}")

    bot.register_next_step_handler(message, chat_loop)


@bot.message_handler(commands=['start'])
def send_welcome(message):
    bot.reply_to(message, '''
      
سلام. به ربات من خوش آمدید 👋            
          
🔍 اینجا می توانید به ساده ترین شکل از قیمت به روز انواع ارز،سکه و ارز دیجیتال با خبر شوید و همچنین می توانید تبدیل واحد ارز ها به تومان را انجام دهید.

 __________________________________________________________________
 
📒 برای انجام این کار، می توانید نام ارز دیجیتال مورد نظر خود که شامل 20 ارز دیجیتال کاربردی در crypto currency هست، 
 یا انواع سکه (اعم از: نیم سکه ، ربع سکه ، سکه بهار آزادی و ...) ، یا هر نوع طلا و حتی انس جهانی طلا
 و یا ارز مورد نظرتون که شامل پرکاربرد ترین ارز ها هستند( مانند: دلار ، یورو ، پوند و حتی افغانی و ...)
 را به فارسی ویا انگلیسی به ربات بدهید و قیمت لحظه ای آن را دریافت نمایید.
 
 __________________________________________________________________
 
  📘 برای مطلع شدن از قیمت انواع یک ارز یا طلا، یکی از نام های 'طلا' ، 'سکه' ، 'ارز' را بنویسید.
  
 __________________________________________________________________
 
  📗 همچنین برای تبدیل واحد یک ارز به تومان، می توانید مقدار مورد نظرتون و نام ارز را بنویسید. به طور مثال: '10 دلار'
  
    ''')

    print("Connecting to Telegram via Psiphon...")

    print(
        f"users first name is: {message.from_user.first_name} , and last name is : {message.from_user.last_name}. with username of : {message.from_user.username}. message content : {message.text} .")


try:

    bot.get_me()
    print("✅ Connection Successful! Bot is starting...")

except Exception as e:

    print(f"❌ Error: {e}")
    print("\nنکته مهم: اگر باز هم ارور داد، یعنی سایتون پورت را عوض کرده است.")
    print("دوباره لاگ سایتون را چک کنید و عدد جلوی HTTP proxy را در کد بالا عوض کنید.")

headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
    }
@bot.message_handler(func=lambda m: True)
def show_price(message):
    if message.from_user.id in chatting_users:
        return


    crp_response = requests.get('https://Api.BrsApi.ir/Market/Gold_Currency.php?key=BYkduFy69hniC41sg6PWvg84uehsg4tJ', headers=headers)
    crp_info = crp_response.json()

    print (f"first name is: {message.from_user.first_name} ,last name is : {message.from_user.last_name}. with username: {message.from_user.username}. message content : {message.text} .")

    speach = message.text

    found = False

    try:

        crp_response = requests.get('https://Api.BrsApi.ir/Market/Gold_Currency.php?key=BYkduFy69hniC41sg6PWvg84uehsg4tJ', headers=headers)
        data = crp_response.json()

        crp_info = data.get("cryptocurrency", [])
        cur_info = data.get("currency", [])
        met_coin_info = data.get("gold", [])

        speach = message.text.lower().replace(" ", "").replace("‌", "")
        speach = speach.translate(str.maketrans("۰۱۲۳۴۵۶۷۸۹", "0123456789"))

        currency_map = {
            'dollar': 'USD', 'دلار': 'USD', 'usdollar': 'USD',
            'tether': 'USDT_IRT', 'تتر': 'USDT_IRT',
            'euro': 'EUR', 'یورو': 'EUR',
            'pound': 'GBP', 'پوند': 'GBP',
            'dirham': 'AED', 'درهمامارات': 'AED', 'درهم': 'AED',
            'lir': 'TRY', 'لیر': 'TRY', 'لیرترکیه': 'TRY',
            'afgani': 'AFN', 'افغانی': 'AFN',
            'ruble': 'RUB', 'روبل': 'RUB', 'روبلروسیه': 'RUB', 'روبل': 'RUB',
            'yuan': 'CNY', 'یوان': 'CNY', 'chineseyuan': 'CNY'
        }

        metal_map = {
            'طلای18عیار': 'IR_GOLD_18K','طلا18عیار': 'IR_GOLD_18K','طلا18': 'IR_GOLD_18K','gold18': 'IR_GOLD_18K', 'طلای١٨عیار':'IR_GOLD_18K' ,
            'طلای24عیار': 'IR_GOLD_24K','طلا24عیار': 'IR_GOLD_24K','طلا24': 'IR_GOLD_24K','gold24': 'IR_GOLD_24K', 'طلا٢٤عیار':'IR_GOLD_24K' ,
            'طلایابشده': 'IR_GOLD_MELTED','طلاابشده': 'IR_GOLD_MELTED','meltedgold': 'IR_GOLD_MELTED', 'طلایآبشده':'IR_GOLD_MELTED' , 'طلاآبشده':'IR_GOLD_MELTED',
            'goldounce': 'XAUUSD','انسطلا': 'XAUUSD' , 'انسجهانیطلا':'XAUUSD'
        }

        coin_map = {
            'سکهیکگرمی':'IR_COIN_1G' , 'سکه1گرمی':'IR_COIN_1G' , 'سکهگرمی':'IR_COIN_1G' , 'سکهییکگرمی':'IR_COIN_1G' ,'1gramcoin':'IR_COIN_1G' ,
            'ربعسکه':'IR_COIN_QUARTER' , 'quartercoin':'IR_COIN_QUARTER' ,
            'نیمسکه': 'IR_COIN_HALF', 'نصفسکه': 'IR_COIN_HALF', 'halfcoin': 'IR_COIN_HALF' ,
            'سکهامامی':'IR_COIN_EMAMI' , 'emamicoin':'IR_COIN_EMAMI' ,
            'سکهبهارازادی': 'IR_COIN_BAHAR', 'سکهبهارآزادی': 'IR_COIN_BAHAR', 'سکهیبهارازادی': 'IR_COIN_BAHAR'

        }
        
        cur_display_names = {
            'USD': '💸 دلار',
            'USDT_IRT': '💸 تتر',
            'EUR': '💸 یورو',
            'GBP': '💸 پوند',
            'AED': '💸 درهم',
            'TRY': '💸 لیر',
            'AFN': '💸 افغانی',
            'RUB': '💸 روبل',
            'CNY': '💸 یوان'
        }

        coin_display_names = {
            'IR_COIN_1G': '✨ سکه یک گرمی',
            'IR_COIN_QUARTER': '✨ ربع سکه',
            'IR_COIN_HALF': '✨ نیم سکه',
            'IR_COIN_EMAMI': '✨ سکه امامی',
            'IR_COIN_BAHAR': '✨ سکه بهار آزادی'
        }

        met_display_names = {
            'IR_GOLD_18K': '✨ طلای ۱۸ عیار',
            'IR_GOLD_24K': '✨ طلای ۲۴ عیار',
            'IR_GOLD_MELTED': '✨ طلای آب‌شده',
            'XAUUSD': '🌍 انس جهانی طلا'
        }

        unit_map = {
            'دلار': 'USD',
            'پوند': 'GBP',
            'یورو': 'EUR',
            'روبل': 'RUB',
            'تتر': 'USDT_IRT',
            'درهم': 'AED',
            'لیر': 'TRY',
            'افغانی': 'AFN',
            'یوان': 'CNY',
        }

        ounce = ['goldounce','انسطلا','انسجهانیطلا']

        match = re.search(r"(\d+\.?\d*)\s*([^\d\s]+)", message.text.lower())

        if speach in metal_map :
            pass

        elif match:
            amount = float(match.group(1))
            unit_input = match.group(2).replace(" ", "")

            symbol = unit_map.get(unit_input)

            if symbol:
                item = next((x for x in cur_info if x['symbol'] == symbol), None)

                if item:
                    current_price = float(item['price'])
                    total = amount * current_price
                    unit_display = item.get('unit', 'تومان')

                    response = (
                        f"💱 **محاسبه نرخ تبدیل:**\n"
                        f"---------------------------------------------------\n"
                        f"🔹 مقدار: `{amount:,.2f}` {unit_input}\n"
                        f"🔸 قیمت واحد: `{current_price:,.0f}` {unit_display}\n"
                        f"💰 **مجموع: `{total:,.0f}` {unit_display}**"
                    )

                    bot.reply_to(message, response, parse_mode='Markdown')
                    found = True
                    return
                else:
                    bot.reply_to(message, "❌ قیمت این واحد یافت نشد.")
                    found = True
                    return
            else:
                bot.reply_to(message, "❌ واحد وارد شده را نمی‌شناسم. (مثال: 10 دلار)")
                found = True
                return

        if speach.lower() in currency_map:
            found = False

            target_cur_symbol = currency_map[speach.lower()]
            price = None

            for item in cur_info:
                if item['symbol'] == target_cur_symbol:
                    price = int(float(item['price']))
                    break

            if price is not None:
                name = cur_display_names.get(target_cur_symbol, target_cur_symbol)
                bot.reply_to(message, f"قیمت {name} : {price:,} تومان")

        elif speach.lower() in metal_map:

             target_met_symbol = metal_map[speach.lower()]
             met_price = None

             for item in met_coin_info:
                 if item['symbol'] == target_met_symbol:
                     met_price = int(float(item['price']))
                     break

             if met_price is not None:

                 if speach.lower() in ounce:
                    name_met = met_display_names.get(target_met_symbol, target_met_symbol)
                    bot.reply_to(message, f"قیمت {name_met} : {met_price:,} دلار ")
                 else:
                     name_met = met_display_names.get(target_met_symbol, target_met_symbol)
                     bot.reply_to(message, f"قیمت {name_met} : {met_price:,} تومان ")

        elif speach.lower() in coin_map:

             target_coin_symbol = coin_map[speach.lower()]
             coin_price = None

             for item in met_coin_info:
                 if item['symbol'] == target_coin_symbol:
                     coin_price = int(float(item['price']))
                     break

             if coin_price is not None:
                 name_coin = coin_display_names.get(target_coin_symbol, target_coin_symbol)
                 bot.reply_to(message, f"قیمت {name_coin} : {coin_price:,} تومان ")

        elif speach.lower() in ['طلا', 'قیمتطلا', 'قیمت_طلا']:

            gold_prices = []
            targets = ['IR_GOLD_18K', 'IR_GOLD_24K', 'IR_GOLD_MELTED', 'XAUUSD']

            for target in targets:

                item = next((x for x in met_coin_info if x['symbol'] == target), None)
                if item:
                    name = met_display_names[target]
                    price = int(float(item['price']))
                    unit = "دلار" if target == 'XAUUSD' else "تومان"
                    gold_prices.append(f"{name}: `{price:,}` {unit}")

            if gold_prices:

                date_text = ""
                if met_coin_info:
                    date_text = f"📅 {met_coin_info[0].get('date', '')} | {met_coin_info[0].get('time', '')}\n\n"

                response_text = (
                        "📋 **گزارش قیمت طلا:**\n" +
                        date_text +
                        "---------------------------------------------------\n" +
                        "\n".join(gold_prices)

                )

                bot.reply_to(message, response_text, parse_mode='Markdown')
            else:
                bot.reply_to(message, "❌ اطلاعات قیمت طلا یافت نشد.")

        elif speach.lower() in ['سکه', 'قیمتسکه', 'قیمت_سکه']:

            gen_coin_prices = []
            targets = ['IR_COIN_1G', 'IR_COIN_QUARTER', 'IR_COIN_HALF', 'IR_COIN_EMAMI' , 'IR_COIN_BAHAR']

            for target in targets:

                item = next((x for x in met_coin_info if x['symbol'] == target), None)
                if item:
                    name = coin_display_names[target]
                    price = int(float(item['price']))
                    unit = "دلار" if target == 'XAUUSD' else "تومان"
                    gen_coin_prices.append(f"{name}: `{price:,}` {unit}")

            if gen_coin_prices:

                date_text = ""
                if met_coin_info:
                    date_text = f"📅 {met_coin_info[0].get('date', '')} | {met_coin_info[0].get('time', '')}\n\n"

                response_text = (
                        "📋 **گزارش قیمت سکه:**\n" +
                        date_text +
                        "---------------------------------------------------\n" +
                        "\n".join(gen_coin_prices)

                )
                bot.reply_to(message, response_text, parse_mode='Markdown')


            else:
                bot.reply_to(message, "❌ اطلاعات قیمت سکه یافت نشد.")

        elif speach.lower() in ['ارز', 'قیمتارز', 'قیمت_ارز']:

            gen_cur_prices = []
            targets = ['USD', 'USDT_IRT', 'EUR', 'GBP' , 'AED' , 'TRY' , 'AFN' , 'RUB' , 'CNY']

            for target in targets:

                item = next((x for x in cur_info if x['symbol'] == target), None)
                if item:
                    name = cur_display_names[target]
                    price = int(float(item['price']))
                    unit = "دلار" if target == 'XAUUSD' else "تومان"
                    gen_cur_prices.append(f"{name}: `{price:,}` {unit}")

            if gen_cur_prices:

                date_text = ""
                if cur_info:
                    date_text = f"📅 {cur_info[0].get('date', '')} | {cur_info[0].get('time', '')}\n\n"

                response_text = (
                        "📋 **گزارش قیمت ارز:**\n" +
                        date_text +
                        "---------------------------------------------------\n" +
                        "\n".join(gen_cur_prices)

                )
                bot.reply_to(message, response_text, parse_mode='Markdown')
            else:
                bot.reply_to(message, "❌ اطلاعات قیمت ارز یافت نشد.")

        elif speach.lower() not in currency_map:

            found = False

            for crypto in crp_info:

                name_fa = crypto.get("name", "").replace(" ", "").replace("‌", "")
                name_en = crypto.get("name_en", "").lower().replace(" ", "").replace("‌", "")
                symbol = crypto.get("symbol", "").lower().replace(" ", "").replace("‌", "")

                if (name_fa in speach or
                        name_en in speach or
                        symbol in speach):

                    usd_price = 0
                    for cur in cur_info:
                        if cur.get("symbol") == "USD":
                            usd_price = cur.get("price", 0)
                            break

                    crypto_price_usd = float(crypto['price'])
                    toman_price = int(crypto_price_usd * usd_price)

                    response = (f"💰 ارز: {crypto['name']}\n"
                                f"💵 قیمت: {crypto_price_usd:,.2f} {crypto['unit']}\n"
                                f"💸 قیمت تومانی: {toman_price:,} تومان\n"
                                f"--------------------------------------------------"
                                f"📝 توضیحات: {crypto['description']}")

                    bot.reply_to(message, response)
                    found = True
                    return

            if not found:
                bot.reply_to(message, 'Hello, to start the bot, use the "/start" command.')

    except Exception as e:
        print(f"An error occurred: {e}")

bot.infinity_polling()


