import sys
import json
import os
import requests
from bs4 import BeautifulSoup

mtn_balance = 0
def resource_path(relative_path):
    try:
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.dirname(__file__)
    return os.path.join(base_path, relative_path)

sources_data_path = resource_path('sources-data.json')

# قراءة الملفات
with open(sources_data_path, 'r', encoding='utf-8') as sources_file:
    sources = json.load(sources_file)

def print_to_file(txt):
    original_stdout = sys.stdout  # حفظ التدفق الأصلي (الشاشة)
    try:
        with open(resource_path('Log.txt'), 'a', encoding='utf-8') as f:
            sys.stdout = f
            print(txt)
    except Exception as ex:
        sys.stdout = original_stdout  # إعادة توجيه sys.stdout إلى الشاشة
        print(f"Error writing to log file: {ex}", file=sys.stderr)
    finally:
        sys.stdout = original_stdout  # إعادة التوجيه إلى الأصل دائمًا
def sendtMsg(tmessage):
    # """
    # دالة لإرسال رسالة نصية إلى مجموعة على Telegram.
    # """
    try:
        token = sources['telegram']['token']
        groupId = sources['telegram']['groupId']
        # print_to_file(f"groupId : {groupId} -- token : {token}")
        # إعداد عنوان URL لواجهة Telegram Bot API مع تضمين الرسالة النصية
        url = f'https://api.telegram.org/bot{token}/sendMessage'
        params = {
            'chat_id': f'{groupId}',  # معرف المجموعة
            'text': tmessage           # النص المراد إرساله
        }
        
        # إرسال الطلب باستخدام مكتبة requests
        resp = requests.post(url, data=params)
        
        # التحقق من حالة الاستجابة
        if resp.status_code == 200:
            print_to_file("تم إرسال الرسالة بنجاح.")  # نجاح الإرسال
        else:
            print_to_file(f"فشل الإرسال: {resp.status_code}, {resp.text}")  # خطأ أثناء الإرسال
    except Exception as e:
        # التعامل مع أي خطأ يحدث أثناء العملية
        print_to_file(f"حدث خطأ: {e}")

def extract_result(page_content):
    try:
        # تحليل محتوى الصفحة باستخدام BeautifulSoup
        soup = BeautifulSoup(page_content, 'html.parser')

        def dump_unexpected_page(reason):
            try:
                clean_text = soup.get_text(" ", strip=True)
                clean_text_short = clean_text[:3000] if clean_text else ""

                print_to_file("========== MTN RESULT PAGE UNEXPECTED ==========")
                print_to_file(f"[UNEXPECTED_REASON] {reason}")
                print_to_file(f"[PAGE_LENGTH] {len(page_content) if page_content else 0}")
                print_to_file(f"[PAGE_TITLE] {soup.title.get_text(strip=True) if soup.title else 'NO_TITLE'}")
                print_to_file(f"[PAGE_TEXT_FIRST_3000] {clean_text_short}")
                print_to_file(f"[PAGE_HTML_FIRST_5000] {(page_content or '')[:5000]}")
                print_to_file("========== END MTN RESULT PAGE UNEXPECTED ==========")

                dump_path = resource_path('unexpected_mtn_result.html')
                with open(dump_path, 'w', encoding='utf-8') as f:
                    f.write(page_content or '')

                print_to_file(f"[UNEXPECTED_HTML_SAVED] {dump_path}")
            except Exception as dump_error:
                print_to_file(f"[ERROR] فشل حفظ/طباعة الصفحة غير المتوقعة: {dump_error}")

        def parse_new_mtn_result_table():
            try:
                for idx, candidate_table in enumerate(soup.find_all("table")):
                    table_text = candidate_table.get_text(" ", strip=True)

                    if not (
                        "رقم العملية" in table_text
                        and "نوع العملية" in table_text
                        and "الحالة" in table_text
                        and "التاريخ" in table_text
                    ):
                        continue

                    rows = candidate_table.find_all("tr")
                    for row in rows:
                        columns = row.find_all("td")
                        if len(columns) < 10:
                            continue

                        values = [col.get_text(" ", strip=True) for col in columns]

                        transaction_id = values[0]
                        transaction_type = values[1]
                        from_number = values[2]
                        to_number = values[3]
                        account_type = values[4]
                        amount = values[5]
                        status = values[8]
                        date = values[9]

                        if not transaction_id or not status:
                            continue

                        result = {
                            "transaction_id": transaction_id,
                            "transaction_type": transaction_type,
                            "from_number": from_number,
                            "to_number": to_number,
                            "account_type": account_type,
                            "amount": amount,
                            "status": status,
                            "date": date,
                        }

                        print_to_file(f"[INFO] تم استخراج نتيجة MTN من الجدول الجديد رقم: {idx}")
                        print_to_file(f"[INFO] MTN new parsed result: {result}")
                        return result

                return None
            except Exception as new_table_error:
                print_to_file(f"[ERROR] فشل استخراج نتيجة MTN من الجدول الجديد: {new_table_error}")
                return None

        # العثور على الجدول باستخدام المعرف الخاص به
        table = soup.find("table", {"id": "dataTable-1"})

        if not table:
            # ثانياً: البحث عن رسالة الخطأ إذا لم يكن الجدول موجوداً
            error_message = soup.find("div", {"class": "error"})
            if error_message:
                return {"status": "error", "message": error_message.text.strip()}

            # الحالة الجديدة: صفحة MTN تعرض جدول النتيجة بدون id=dataTable-1
            new_table_result = parse_new_mtn_result_table()
            if new_table_result:
                return new_table_result

            # إذا لم يوجد جدول قديم ولا رسالة خطأ ولا جدول جديد قابل للقراءة، اطبع الصفحة واحفظها للمراجعة
            dump_unexpected_page("لم يتم العثور على جدول dataTable-1 ولا div.error ولا جدول نتيجة جديد قابل للقراءة")
            return {
                "status": "fail",
                "message": "نتيجة غير متوقعة من موقع MTN: لا يوجد جدول نتيجة ولا رسالة خطأ واضحة"
            }

        tbody = table.find("tbody")
        if not tbody:
            dump_unexpected_page("تم العثور على جدول dataTable-1 لكن بدون tbody")
            return {
                "status": "fail",
                "message": "جدول النتيجة لا يحتوي على tbody"
            }

        # استخراج الصف الأول (النتيجة الأولى)
        first_row = tbody.find("tr")
        if not first_row:
            dump_unexpected_page("تم العثور على tbody لكن بدون أي tr")
            return {"status": "fail", "message": "الجدول لا يحتوي على أي بيانات."}

        # استخراج القيم من الأعمدة
        columns = first_row.find_all("td")
        if len(columns) < 10:
            dump_unexpected_page(f"عدد الأعمدة أقل من المتوقع: {len(columns)}")
            return {"status": "fail", "message": f"عدد الأعمدة أقل من المتوقع: {len(columns)}"}

        # استخراج التفاصيل
        transaction_id = columns[0].text.strip()
        transaction_type = columns[1].text.strip()
        from_number = columns[2].text.strip()
        to_number = columns[3].text.strip()
        account_type = columns[4].text.strip()
        amount = columns[5].text.strip()
        status = columns[8].text.strip()
        date = columns[9].text.strip()

        # طباعة النتيجة
        result = {
            "transaction_id": transaction_id,
            "transaction_type": transaction_type,
            "from_number": from_number,
            "to_number": to_number,
            "account_type": account_type,
            "amount": amount,
            "status": status,
            "date": date,
        }
        return result

    except Exception as e:
        print_to_file(f"[ERROR] حدث خطأ أثناء استخراج النتيجة: {e}")
        try:
            print_to_file("========== MTN RESULT PAGE EXCEPTION ==========")
            print_to_file(f"[EXCEPTION_PAGE_LENGTH] {len(page_content) if page_content else 0}")
            print_to_file(f"[EXCEPTION_PAGE_HTML_FIRST_5000] {(page_content or '')[:5000]}")
            print_to_file("========== END MTN RESULT PAGE EXCEPTION ==========")

            dump_path = resource_path('unexpected_mtn_result_exception.html')
            with open(dump_path, 'w', encoding='utf-8') as f:
                f.write(page_content or '')

            print_to_file(f"[EXCEPTION_HTML_SAVED] {dump_path}")
        except Exception as dump_error:
            print_to_file(f"[ERROR] فشل حفظ صفحة الخطأ: {dump_error}")

        return {"status": "fail", "message": f"حدث خطأ أثناء استخراج النتيجة: {e}"}

def is_bills(sentence):
    """
    تتحقق إذا كانت الجملة تحتوي على كلمة 'فاتورة' أو 'فواتير'.

    Args:
        sentence (str): الجملة المراد التحقق منها.

    Returns:
        bool: True إذا احتوت الجملة على الكلمة المطلوبة، False خلاف ذلك.
    """
    keywords = ["فاتورة", "فواتير"]
    return any(keyword in sentence for keyword in keywords)

def is_bulk(sentence):
    """
    تتحقق إذا كانت الجملة تحتوي على كلمة '[جملة]' أو '.

    Args:
        sentence (str): الجملة المراد التحقق منها.

    Returns:
        bool: True إذا احتوت الجملة على الكلمة المطلوبة، False خلاف ذلك.
    """
    keywords = ["جملة", "جمله", "رصيد الكتروني"]
    return any(keyword in sentence for keyword in keywords)

def is_units(sentence):
    """
    تتحقق إذا كانت الجملة تحتوي على كلمة '[وحدات]' أو '.

    Args:
        sentence (str): الجملة المراد التحقق منها.

    Returns:
        bool: True إذا احتوت الجملة على الكلمة المطلوبة، False خلاف ذلك.
    """
    keywords = ["وحدات"]
    return any(keyword in sentence for keyword in keywords)

def is_cash(sentence):
    """
    تتحقق إذا كانت الجملة تحتوي على كلمة '[كاش]' أو '.

    Args:
        sentence (str): الجملة المراد التحقق منها.

    Returns:
        bool: True إذا احتوت الجملة على الكلمة المطلوبة، False خلاف ذلك.
    """
    keywords = ["كاش"]
    return any(keyword in sentence for keyword in keywords)

def build_low_balance_message(product_name=None, city_name=None, current_balance=None):
    """
    يبني رسالة تلغرام واضحة عند انخفاض/عدم كفاية رصيد MTN.
    يتجاهل أي قيمة غير موجودة حتى لا تفشل العملية بسبب نقص بيانات الرسالة.
    """
    service_parts = ["ام تي ان"]

    if product_name:
        if is_bills(product_name):
            service_parts.append("فواتير")
        elif is_units(product_name):
            service_parts.append("وحدات")
        elif is_cash(product_name):
            service_parts.append("كاش")

    if city_name:
        service_parts.append(str(city_name).strip())

    lines = ["رصيد " + " ".join(part for part in service_parts if part) + " منخفض"]

    if current_balance not in (None, "", "N/A"):
        try:
            balance_number = float(current_balance)
            if balance_number > 0:
                balance_text = str(current_balance).rstrip('0').rstrip('.') if '.' in str(current_balance) else str(current_balance)
                lines.append(f"الرصيد الحالي: {balance_text}")
        except (TypeError, ValueError):
            lines.append(f"الرصيد الحالي: {current_balance}")

    lines.append("يرجى التعبئة")
    return "\n".join(lines)

def process_order(data):
    """
    معالجة بيانات الطلب.
    """
    try:
        # استخراج البيانات
        order_id = data.get('order_id')
        product_name = data.get('product_name')
        phone_num = data.get('phone_num')
        city_name = data.get('cityName')
        quantity = data.get('quantity')
        supplier_code = data.get('supplier_code')
        password = data.get('password')
        username = data.get('username')
        # تسجيل البيانات
        print_to_file(f"Processing order: {order_id}")
        print_to_file(f"Product: {product_name}")
        print_to_file(f"Phone: {phone_num}")
        print_to_file(f"City Name: {city_name}")
        print_to_file(f"Quantity: {quantity}")
        print_to_file(f"Supplier Code: {supplier_code}")
        print_to_file(f"Supplier Code: {username}")
        print_to_file(f"Supplier Code: {password}")
        #البدء بعملية تحضير الجلسة
        session = requests.Session()
        base_url = "https://services.mtnsyr.com:56303/EXTERNAL_WEB"
        
        try:
            # الخطوة 1: فتح صفحة تسجيل الدخول
            print_to_file("[INFO] فتح صفحة تسجيل الدخول...")
            response = session.get(f"{base_url}/login", headers = {
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
                "Content-Type": "application/x-www-form-urlencoded",
                "Referer": "https://services.mtnsyr.com:56303/EXTERNAL_WEB/login",
                "Origin": "https://services.mtnsyr.com:56303",
                "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
                "Accept-Encoding": "gzip, deflate, br, zstd",
                "Accept-Language": "ar-AE,ar;q=0.9",
                "Cache-Control": "max-age=0",
                "Connection": "keep-alive",
                "Upgrade-Insecure-Requests": "1",
                "Sec-Fetch-Dest": "document",
                "Sec-Fetch-Mode": "navigate",
                "Sec-Fetch-Site": "same-origin",
                "Sec-Fetch-User": "?1",
            })
            response.raise_for_status()
            print_to_file(f"[SUCCESS] تم فتح صفحة تسجيل الدخول. الحالة: {response.status_code}")
        except Exception as e:
            print_to_file(f"[ERROR] حدث خطأ أثناء فتح صفحة تسجيل الدخول: {e} رقم الاوردر : {order_id}")
            return {
                "success": False,
                "num": 0,
                "message": f"مشكلة مؤقتة في موقع ام تي ان1"
            }
        
        try:
            # الخطوة 2: تسجيل الدخول
            print_to_file("[INFO] تسجيل الدخول...")
            login_data = {
                "username": username,
                "password": password
            }
            headers = {
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
                "Content-Type": "application/x-www-form-urlencoded",
                "Referer": "https://services.mtnsyr.com:56303/EXTERNAL_WEB/login",
                "Origin": "https://services.mtnsyr.com:56303",
                "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
                "Accept-Encoding": "gzip, deflate, br, zstd",
                "Accept-Language": "ar-AE,ar;q=0.9",
                "Cache-Control": "max-age=0",
                "Connection": "keep-alive",
                "Upgrade-Insecure-Requests": "1",
                "Sec-Fetch-Dest": "document",
                "Sec-Fetch-Mode": "navigate",
                "Sec-Fetch-Site": "same-origin",
                "Sec-Fetch-User": "?1",
            }
            login_response = session.post(f"{base_url}/login", data=login_data, headers=headers)
            login_response.raise_for_status()
            location2 = login_response.headers.get('Location')
            print_to_file(f"location2 : {location2}")
            print_to_file(f"[SUCCESS] تسجيل الدخول تم بنجاح. الحالة: {login_response.status_code}")
        except Exception as e:
            print_to_file(f"[ERROR] حدث خطأ أثناء تسجيل الدخول: {e} رقم الاوردر : {order_id}")
            return {
                "success": False,
                "num": 0,
                "message": f"مشكلة مؤقتة في موقع ام تي ان2"
            }
        
        try:
            # الخطوة 3: الانتقال إلى الصفحة الرئيسية
            print_to_file("[INFO] الانتقال إلى الصفحة الرئيسية...")
            main_page_response = session.get(f"{base_url}")
            main_page_response.raise_for_status()
            print_to_file(f"[SUCCESS] تم الوصول إلى الصفحة الرئيسية. الحالة: {main_page_response.status_code}")
        except Exception as e:
            print_to_file(f"[ERROR] حدث خطأ أثناء الانتقال إلى الصفحة الرئيسية: {e} رقم الاوردر : {order_id}")
            return {
                "success": False,
                "num": 0,
                "message": f"مشكلة مؤقتة في موقع ام تي ان3"
            }
        try:
            # الخطوة 4: فتح صفحة المستخدم وطباعة المحتوى
            print_to_file("[INFO] فتح صفحة المستخدم...")
            user_page_response = session.get(f"{base_url}/user/index")
            user_page_response.raise_for_status()
            print_to_file(f"[SUCCESS] تم فتح صفحة المستخدم. الحالة: {user_page_response.status_code}")
            # print(user_page_response.text)
        except Exception as e:
            print_to_file(f"[ERROR] حدث خطأ أثناء فتح صفحة المستخدم: {e}")
            return {
                "success": False,
                "num": 0,
                "message": f"مشكلة مؤقتة في موقع ام تي ان4"
            }
        if "تسجيل الخروج" in user_page_response.text:
            try:
                # الانتقال إلى الصفحة التالية
                print_to_file("[INFO] الانتقال إلى صفحة تعبئة الرصيد...")
                next_page_response = session.get(f"{base_url}/Transaction/topupPrepaid")
                next_page_response.raise_for_status()
                print_to_file(f"[SUCCESS] تم فتح صفحة تعبئة الرصيد. الحالة: {next_page_response.status_code}")
                # print(next_page_response.text)
                    # استخدام BeautifulSoup لاستخراج قيمة _csrf
                soup = BeautifulSoup(next_page_response.text, 'html.parser')
                csrf_token = soup.find("input", {"name": "_csrf"})["value"]
                print_to_file(f"[INFO] تم استخراج قيمة _csrf: {csrf_token}")
            except Exception as e:
                print_to_file(f"[ERROR] حدث خطأ أثناء فتح صفحة المستخدم: {e}")
                return {
                    "success": False,
                    "num": 0,
                    "message": f"مشكلة مؤقتة في موقع ام تي ان5"
                }
        else:
            print_to_file("[ERROR] تسجيل الدخول فشل، العناصر المطلوبة غير موجودة.")
            return {
                "success": False,
                "num": 0,
                "message": f"مشكلة مؤقتة في موقع ام تي ان6"
            }
        #البدء بعملية التحويل
        if is_units(product_name) and not is_bulk(product_name):
            print_to_file(f"وحدات مفرق")
            try:
                # الخطوة 4: إرسال طلب تعبئة الرصيد
                print_to_file("[INFO] إرسال طلب تعبئة الرصيد...")
                topup_data = {
                    "_csrf": csrf_token,
                    "reseller_id": username,
                    "lang": "ar",
                    "gsm": phone_num,
                    "Amount": quantity,
                }
                headers.update({
                    "Referer": f"{base_url}/Transaction/topupPrepaid",
                })
                topup_response = session.post(f"{base_url}/Transaction/submittopupPrepaid", data=topup_data, headers=headers)
                topup_response.raise_for_status()
                print_to_file(f"[SUCCESS] تم إرسال طلب وحدات مفرق. الحالة: {topup_response.status_code}")
                location = topup_response.headers.get('Location')
                if location:
                    print_to_file(f"location : {location}")
                    # متابعة إعادة التوجيه للحصول على النتيجة
                    result_url = f"https://services.mtnsyr.com:56303{location}"
                    result_response = session.get(result_url)
                    result_response.raise_for_status()
                    result_content = result_response.text
                else:
                    result_content = topup_response.text

                result = extract_result(result_content)
                print_to_file(result)
                if result["status"] == "success" or result["status"] == "نجاح" or result["status"] == "Success":
                    print_to_file(f"عملية ناجحة: {result}")
                    # sendtMsg(f"عملية ناجحة: {result}")
                    return {
                        "success": True,
                        "message": "تم بنجاح",
                        "mtn_balance": mtn_balance,
                        "quantity": quantity
                    }
                elif result["status"] == "fail":
                    print_to_file(f"عملية للمراجعة: {result}")
                    sendtMsg(f" اوردر للمراجعة : {order_id} result : {result}")
                    return {
                        "success": True,
                        "message": "تم بنجاح",
                        "mtn_balance": mtn_balance,
                        "quantity": quantity
                    }
                else:
                    print_to_file(f"خطأ: {result['message']}")
                    sendtMsg(f" عملية فاشلة اذا بتحب تعمل نظرة : {order_id} result : {result}")
                    return {
                        "success": False,
                        "message": result["message"]
                    }
            except Exception as e:
                print_to_file(f"[ERROR] حدث خطأ أثناء إرسال طلب تعبئة الرصيد أو استلام النتيجة: {e}")
                sendtMsg(f" اوردر للمراجعة : {order_id} result : {result}")
                return {
                    "success": True,
                    "message": "تم بنجاح",
                    "mtn_balance": mtn_balance,  # قيمة رصيد المصدر الافتراضية
                    "quantity": quantity
                }
        elif is_units(product_name) and is_bulk(product_name):
            print_to_file(f"وحدات جملة")
            try:
                # الخطوة 4: إرسال طلب تعبئة الرصيد
                print_to_file("[INFO] إرسال طلب تعبئة تحويل جملة...")
                headers.update({
                    "Referer": f"{base_url}/api/submitTransfer",
                })
                amount = quantity
                Agent = supplier_code
                topup_response = session.get(f"{base_url}/api/submitTransfer?FromAgent=&AccountTypeId=1&ToAgent={Agent}&select=1&notification=1&amount={amount}&memo=undefined&ref=undefined&commentt=undefined&lang=ar", headers=headers)
                topup_response.raise_for_status()
                print_to_file(f"[SUCCESS] تم إرسال طلب وحدات جملة. الحالة: {topup_response.status_code}")
                if topup_response.status_code == 200:
                    result_content = topup_response.text
                    result_content_json = json.loads(result_content)
                    print_to_file(f"نتيجة الاوردر : {order_id} هي : {result_content}")
                    #topup_response : {"o_RESULT_CODE":403003,"o_RESULT_DESC":"لا يوجد خط تحويل بهذا المعرف","o_TRANSFER_ID":null,"o_RESULT_MSG":"Agent with this ID does not exist"}
                    #topup_response : {"o_RESULT_CODE":103000,"o_RESULT_DESC":"نجاح","o_TRANSFER_ID":250117226535,"o_RESULT_MSG":"Success"}
                    if result_content_json.get("o_RESULT_DESC") in ["نجاح", "Success"] or result_content_json.get("o_RESULT_MSG") == "Success":
                        print_to_file(f"عملية ناجحة: {result_content_json}")
                        return {
                            "success": True,
                            "message": "تم بنجاح",
                            "mtn_balance": mtn_balance,
                            "quantity": quantity
                        }
                    else:
                        print_to_file(f"خطأ: {result_content_json.get('o_RESULT_DESC', 'خطأ غير معروف')}")
                        sendtMsg(f" اوردر للمراجعة : {order_id} result : {result_content_json}")
                        return {
                            "success": False,
                            "message": result_content_json.get("o_RESULT_DESC", "خطأ غير معروف")
                        }
                else:
                    sendtMsg(f" اوردر للمراجعة : {order_id} result : {topup_response.text}")
                    return {
                            "success": True,
                            "message": "تم بنجاح",
                            "mtn_balance": mtn_balance,
                            "quantity": quantity
                        }
            except Exception as e:
                print_to_file(f"[ERROR] حدث خطأ أثناء إرسال طلب تعبئة الرصيد أو استلام النتيجة: {e}")
                sendtMsg(f" اوردر للمراجعة : {order_id} المشكلة : {e}")
                return {
                            "success": True,
                            "message": "تم بنجاح",
                            "mtn_balance": mtn_balance,
                            "quantity": quantity
                        }
        elif is_bills(product_name) and not is_bulk(product_name):
            print_to_file(f"فواتير مفرق")
            try:
                # الخطوة 4: إرسال طلب تعبئة الرصيد
                print_to_file("[INFO] إرسال طلب تعبئة فواتير مفرق...")
                topup_data = {
                    "_csrf": csrf_token,
                    "reseller_id": username,
                    "lang": "ar",
                    "gsm": phone_num,
                    "Amount": quantity,
                }
                headers.update({
                    "Referer": f"{base_url}/Transaction/submittopupPostpaid",
                })
                topup_response = session.post(f"{base_url}/Transaction/submittopupPostpaid", data=topup_data, headers=headers)
                topup_response.raise_for_status()
                print_to_file(f"[SUCCESS] تم إرسال طلب فواتير مفرق. الحالة: {topup_response.status_code}")
                location = topup_response.headers.get('Location')
                if location:
                    print_to_file(f"location : {location}")
                    # متابعة إعادة التوجيه للحصول على النتيجة
                    result_url = f"https://services.mtnsyr.com:56303{location}"
                    result_response = session.get(result_url)
                    result_response.raise_for_status()
                    result_content = result_response.text
                else:
                    result_content = topup_response.text
                result = extract_result(result_content)
                print_to_file(f"نتيجة الاوردر : {order_id} هي : {result}")
                if result["status"] == "success" or result["status"] == "نجاح" or result["status"] == "Success":
                    print_to_file(f"عملية ناجحة: {result}")
                    return {
                        "success": True,
                        "message": "تم بنجاح",
                        "mtn_balance": mtn_balance,
                        "quantity": quantity
                    }
                elif result["status"] == "fail":
                    print_to_file(f"عملية للمراجعة: {result}")
                    sendtMsg(f" اوردر للمراجعة : {order_id} result : {result}")
                    return {
                        "success": True,
                        "message": "تم بنجاح",
                        "mtn_balance": mtn_balance,
                        "quantity": quantity
                    }
                else:
                    print_to_file(f"خطأ: {result['message']}")
                    if "رصيد" in result["message"] or "كافي" in result["message"]:
                        message = "موقع ام تي ان متوقف مؤقتا"
                        low_balance_message = build_low_balance_message(
                            product_name=product_name,
                            city_name=city_name,
                            current_balance=mtn_balance
                        )
                        sendtMsg(low_balance_message)
                    else:
                        message = result["message"]
                        sendtMsg(f" عملية فاشلة اذا بتحب تعمل نظرة : {order_id} result : {result}")
                    return {
                        "success": False,
                        "message": message
                    }
            except Exception as e:
                print_to_file(f"[ERROR] حدث خطأ أثناء إرسال طلب تعبئة الرصيد أو استلام النتيجة: {e} رقم الاوردر : {order_id}")
                return {
                        "success": False,
                        "message": f" مشكلة غير معروفة"
                    }
        elif is_bills(product_name) and is_bulk(product_name):
            print_to_file(f"فواتير جملة")
            try:
                # الخطوة 4: إرسال طلب تعبئة الرصيد
                print_to_file("[INFO] إرسال طلب تعبئة تحويل جملة...")
                headers.update({
                    "Referer": f"{base_url}/api/submitTransfer",
                })
                
                amount = quantity
                Agent = supplier_code
                topup_response = session.get(f"{base_url}/api/submitTransfer?FromAgent=&AccountTypeId=2&ToAgent={Agent}&select=1&notification=1&amount={amount}&memo=undefined&ref=undefined&commentt=undefined&lang=ar", headers=headers)
                topup_response.raise_for_status()
                print_to_file(f"[SUCCESS] تم إرسال طلب فواتير جملة. الحالة: {topup_response.status_code}")
                if topup_response.status_code == 200:
                    result_content = topup_response.text
                    result_content_json = json.loads(result_content)
                    print_to_file(f"نتيجة الاوردر : {order_id} هي : {result_content}")
                    #topup_response : {"o_RESULT_CODE":403003,"o_RESULT_DESC":"لا يوجد خط تحويل بهذا المعرف","o_TRANSFER_ID":null,"o_RESULT_MSG":"Agent with this ID does not exist"}
                    #topup_response : {"o_RESULT_CODE":103000,"o_RESULT_DESC":"نجاح","o_TRANSFER_ID":250117226535,"o_RESULT_MSG":"Success"}
                    if result_content_json.get("o_RESULT_DESC") in ["نجاح", "Success"] or result_content_json.get("o_RESULT_MSG") == "Success":
                        print_to_file(f"عملية ناجحة: {result_content_json}")
                        return {
                            "success": True,
                            "message": "تم بنجاح",
                            "mtn_balance": mtn_balance,
                            "quantity": quantity
                        }
                    else:
                        print_to_file(f"خطأ: {result_content_json.get('o_RESULT_DESC', 'خطأ غير معروف')}")
                        sendtMsg(f" اوردر للمراجعة : {order_id} result : {result_content_json}")
                        return {
                            "success": False,
                            "message": result_content_json.get("o_RESULT_DESC", "خطأ غير معروف")
                        }
                else:
                    sendtMsg(f" اوردر للمراجعة : {order_id} result : {topup_response.text}")
                    return {
                            "success": True,
                            "message": "تم بنجاح",
                            "mtn_balance": mtn_balance,
                            "quantity": quantity
                        }
            except Exception as e:
                print_to_file(f"[ERROR] حدث خطأ أثناء إرسال طلب تعبئة الرصيد أو استلام النتيجة: {e}")
                sendtMsg(f" اوردر للمراجعة : {order_id} المشكلة : {e}")
                return {
                            "success": True,
                            "message": "تم بنجاح",
                            "mtn_balance": mtn_balance,
                            "quantity": quantity
                        }
        elif is_cash(product_name) and is_bulk(product_name):
            print_to_file(f"كاش جملة")
        elif is_cash(product_name) and not is_bulk(product_name):
            print_to_file(f"كاش مفرق")
        else:
            print_to_file(f"الخدمة غير معرفة")
    except Exception as e:
        return {
            "success": False,
            "num": 500,
            "message": f"Error processing order: {str(e)}"
        }
if __name__ == "__main__":
    try:
        # فك المدخلات
        input_data = json.loads(sys.argv[1])
        print_to_file(f"Received input: {sys.argv[1]}")
        # معالجة البيانات
        response = process_order(input_data)
        # طباعة JSON فقط
        print(json.dumps(response, ensure_ascii=False))
    except Exception as e:
        error_response = {
            "success": False,
            "num": 500,
            "message": f"An error occurred: {str(e)}"
        }
        print(json.dumps(error_response, ensure_ascii=False))



# {'transaction_id': '250117222608', 'transaction_type': 'شحن لاحق الدفع', 'from_number': '963954648967', 'to_number': '963942000232', 'account_type': 'لاحق الدفع', 'amount': '100', 'status': 'نجاح', 'date': '2025-01-17 22:15:53.0'}
#نتيجة تحويل جملة فاشلة
#topup_response : {"o_RESULT_CODE":403003,"o_RESULT_DESC":"لا يوجد خط تحويل بهذا المعرف","o_TRANSFER_ID":null,"o_RESULT_MSG":"Agent with this ID does not exist"}
#topup_response : {"o_RESULT_CODE":103000,"o_RESULT_DESC":"نجاح","o_TRANSFER_ID":250117226535,"o_RESULT_MSG":"Success"}
