import sys
import json
import re
import difflib

def normalize_arabic(text):
    # Text normalization
    text = str(text)
    
    # Transliterate English letters to Arabic to allow matching english words to arabic db entries
    if re.search(r'[a-zA-ZöäüßÖÄÜ]', text):
        text = text.lower()
        digraphs = {
            'sch': 'ش',
            'ch': 'خ', # default ch to خ for dutch/german cities
            'sh': 'ش',
            'th': 'ث',
            'ph': 'ف',
            'ou': 'و',
            'oo': 'و',
            'ee': 'ي',
            'ea': 'ي',
            'ie': 'ي',
            'ei': 'ي',
            'eu': 'وي',
            'au': 'او'
        }
        mapping = {
            'a': 'ا', 'b': 'ب', 'c': 'ك', 'd': 'د', 'e': '', 'f': 'ف', 'g': 'غ', 
            'h': 'ه', 'i': 'ي', 'j': 'ج', 'k': 'ك', 'l': 'ل', 'm': 'م', 'n': 'ن', 
            'o': 'و', 'p': 'ب', 'q': 'ق', 'r': 'ر', 's': 'س', 't': 'ت', 'u': 'و', 
            'v': 'ف', 'w': 'و', 'x': 'كس', 'y': 'ي', 'z': 'ز',
            'ö': 'و', 'ä': 'ا', 'ü': 'و', 'ß': 'س', 'ï': 'ي'
        }
        for dig, ar in digraphs.items():
            text = text.replace(dig, ar)
        res = ''
        for char in text:
            res += mapping.get(char, char)
        text = res
        
    # 1. Convert Arabic-Indic numerals
    arabic_indic = '٠١٢٣٤٥٦٧٨٩'
    arabic_std   = '0123456789'
    trans_table = str.maketrans(arabic_indic, arabic_std)
    text = text.translate(trans_table)

    # 2. Normalize characters
    text = re.sub(r'[أإآا]', 'ا', text)
    text = re.sub(r'ة', 'ه', text)
    text = re.sub(r'ى', 'ي', text)
    text = re.sub(r'ؤ', 'و', text)
    text = re.sub(r'ئ', 'ي', text)
    text = re.sub(r'[\u064B-\u0652]', '', text)
    
    # 3. Deduplicate consecutive identical characters (e.g. ميوووونخ -> ميونخ)
    text = re.sub(r'(.)\1+', r'\1', text)
    
    return text

EXCLUDED_DEST_WORDS = {
    # 1. Remittance & Money Transfer
    'حواله', 'حوالة', 'راجع', 'الراجع', 'مستفيد', 'المستفيد', 'مرسل', 'المرسل', 
    'اجور', 'الاجور', 'اجرة', 'الاجرة', 'عمولة', 'العمولة', 'عموله', 'العموله',
    'رسوم', 'الرسوم', 'تكلفة', 'التكلفة', 'تكلفه', 'التكلفه', 'مبلغ', 'المبلغ',
    'دفعة', 'الدفعة', 'دفعه', 'الدفعه', 'تسليم', 'التسليم', 'استلام', 'الاستلام',
    'مقبوضات', 'المقبوضات', 'مدفوعات', 'المدفوعات', 'صرف', 'الصرف', 'مصاري',
    'فلوس', 'قروش', 'نقد', 'نقدي', 'كاش', 'رصيد', 'الرصيد', 'حساب', 'الحساب',
    'صندوق', 'الصندوق', 'بنك', 'البنك', 'مصرف', 'المصرف', 'شركة', 'الشركة',
    'شركه', 'الشركه', 'مكتب', 'المكتب', 'فرع', 'الفرع', 'وكيل', 'الوكيل',
    'زبون', 'الزبون', 'عميل', 'العميل', 'مورد', 'المورد', 'تاجر', 'التاجر',
    'تحويل', 'التحويل', 'شحن', 'الشحن', 'تعبئة', 'تعبيه', 'تجميد', 'تصفية',
    'تصفيه', 'خصم', 'الخصم', 'ايداع', 'الايداع', 'سحب', 'السحب', 'قبض', 'القبض',
    'دفع', 'الدفع', 'سند', 'السند', 'فاتورة', 'الفاتورة', 'فاتوره', 'الفاتوره',
    'ايصال', 'الايصال', 'وصل', 'الوصل', 'باقي', 'الباقي', 'متبقي', 'المتبقي',
    
    # 2. Currencies
    'دولار', 'الدولار', 'يورو', 'اليورو', 'ليرة', 'الليرة', 'ليره', 'الليره',
    'تركي', 'التركي', 'سوري', 'السوري', 'دينار', 'الدينار', 'درهم', 'الدرهم',
    'ريال', 'الريال', 'سنت', 'السنت', 'قرش', 'القرش', 'فلس', 'الفلس',
    
    # 3. Prepositions & Connection Words
    'من', 'الى', 'إلى', 'على', 'في', 'عن', 'طريق', 'بواسطة', 'بواسطه', 'لصالح',
    'حسب', 'بخصوص', 'مشان', 'علشان', 'لجل', 'منشان', 'مع', 'بدون', 'غير',
    'سوى', 'فقط', 'بس', 'حتى', 'بين', 'ضمن', 'تبع', 'حق', 'مال', 'تبعون',
    
    # 4. People & Titles
    'شخص', 'اخ', 'أخ', 'اخو', 'اخت', 'أخت', 'اب', 'أب', 'ابو', 'ام', 'أم',
    'ابن', 'بنت', 'زوج', 'زوجة', 'زوجه', 'عائلة', 'عائله', 'عيله', 'قرابة',
    'قرابه', 'صديق', 'زميل', 'مدير', 'رئيس', 'مسؤول', 'مسؤل', 'معلم', 'استاذ',
    'محترم', 'كريم', 'باشا', 'بيك', 'بيغ', 'شيخ', 'حجي', 'حج', 'اخي', 'اختي',
    'ابوي', 'امي', 'خال', 'خالو', 'عم', 'عمو', 'شريك', 'شغيلة', 'شغيل', 'عامل',
    'صانع', 'محاسب', 'امين',
    
    # 5. Verbs & Actions
    'ارسل', 'ابعت', 'حول', 'سلم', 'ادفع', 'اقبض', 'اسحب', 'اودع', 'سجل', 'قيد',
    'الغ', 'الغي', 'امسح', 'عدل', 'صلح', 'تاكد', 'تأكد', 'شيك', 'دقق', 'وافق',
    'اعتمد', 'رفض', 'رجع', 'استرجع', 'خصم', 'ضيف', 'زود', 'نقص', 'احسب',
    'ابعث', 'اعطي', 'هات', 'خذ', 'خد', 'جيب', 'ودي', 'خلي', 'بقي', 'صفي',
    'طابق', 'سوي', 'اعمل', 'حط', 'شيل', 'ارفع', 'نزل', 'اكتب', 'سيف', 'احفظ',
    'استلم', 'سلمني', 'عطني', 'عطيني', 'حوّل',
    
    # 6. Time, Priority & Status
    'اليوم', 'اليم', 'امس', 'امبارح', 'مبارح', 'بكرة', 'بكرا', 'باكر', 'غدا',
    'الان', 'هلق', 'هسا', 'الحين', 'دحين', 'فورا', 'عاجل', 'ضروري', 'مستعجل',
    'سريع', 'بطيء', 'مؤجل', 'معلق', 'قيد', 'التنفيذ', 'مسبق', 'لاحق', 'شهري',
    'اسبوعي', 'يومي', 'سنوي', 'صباح', 'الصباح', 'صبح', 'مساء', 'المساء', 'مسا',
    'ظهر', 'الظهر', 'عصر', 'العصر', 'مغرب', 'عشاء', 'ليل', 'نهار', 'ساعة',
    'ساعه', 'دقيقة', 'دقيقه', 'ثانية', 'ثانيه', 'شهر', 'سنة', 'سنه', 'اسبوع',
    'تاريخ', 'وقت', 'موعد', 'مهلة', 'مهله',
    
    # 7. Greetings & Politeness
    'سلام', 'عليكم', 'مرحبا', 'مرحبة', 'هلا', 'اهلين', 'اهلًا', 'يعطيك',
    'العافية', 'العافيه', 'عافية', 'عافيه', 'شكرا', 'شكر', 'تفضل', 'لو',
    'سمحت', 'فضلك', 'رجاء', 'الرجاء', 'يرجى', 'بليز', 'عفوا', 'اسف', 'معلش',
    'طال', 'عمرك', 'حياك', 'الله', 'والله', 'بالله', 'بسم', 'الحمد', 'انشاء',
    'انشا', 'مشاء', 'ماشاء', 'يارب', 'ربنا',
    
    # 8. Accounting & Financial Specifics
    'دائن', 'مدين', 'ميزانية', 'ميزانيه', 'جرد', 'ارباح', 'خسائر', 'خساير',
    'صافي', 'اجمالي', 'ربح', 'خسارة', 'خساره', 'فائض', 'فايض', 'عجز',
    'ايرادات', 'مصاريف', 'نفقات', 'مشتريات', 'مبيعات', 'مخزون', 'بضاعة',
    'بضاعه', 'دفتر', 'يومية', 'يوميه', 'استاذ', 'ترحيل', 'مطابقة', 'مطابقه',
    'تسوية', 'تسويه', 'اصل', 'اصول', 'خصوم', 'التزام', 'التزامات', 'ممتلكات',
    'مادة', 'ماده', 'صنف', 'وحدة', 'وحده', 'حبة', 'حبه', 'كيلو', 'غرام', 'متر',
    'طن', 'لتر', 'علبة', 'علبه', 'كرتونة', 'كرتونه', 'باليت', 'شحن', 'نقل',
    'تخليص', 'جمرك', 'ضريبة', 'ضريبه', 'تامين', 'تأمين', 'طابع',
    'قائمة', 'قايمة', 'كشف', 'حركة', 'حركه', 'تفصيل', 'ملخص', 'تقرير',
    'رقيق', 'سميك', 'طويل', 'قصير',
    
    # 9. Amounts, Numbers and Quantities
    'الف', 'الاف', 'مليون', 'ملايين', 'مليار', 'بليون', 'مية', 'مئة', 'ميه',
    'نص', 'نصف', 'ربع', 'تلت', 'ثلث', 'خمس', 'سدس', 'سبع', 'ثمن', 'تسع', 'عشر', 'الفين',
    'صفر', 'واحد', 'اثنين', 'تنين', 'ثلاثة', 'تلاته', 'تلات', 'اربعة', 'اربعه',
    'اربع', 'خمسة', 'خمسه', 'ستة', 'سته', 'ست', 'سبعة', 'سبعه', 'سبع',
    'ثمانية', 'ثمانيه', 'تمانيه', 'تمان', 'تسعة', 'تسعه', 'تسع', 'عشرة',
    'عشره', 'عشرين', 'ثلاثين', 'تلاتين', 'اربعين', 'خمسين', 'ستين', 'سبعين',
    'ثمانين', 'تمانين', 'تسعين', 'ميتين', 'تلاتميه', 'اربعميه', 'خمسميه',
    'ستميه', 'سبعميه', 'تمانميه', 'تسعميه', 'شوية', 'شويه', 'كثير', 'كتير',
    'قليل', 'شقفة', 'شوي', 'حبه','الاف','بالالف','بالالف','تالاف',
    
    # 10. General Adjectives & Status
    'كبير', 'صغير', 'الكبير', 'الصغير', 'جديد', 'قديم', 'الجديد', 'القديم',
    'اول', 'ثاني', 'تاني', 'اخر', 'الاول', 'الثاني', 'التاني', 'الاخر',
    'كامل', 'ناقص', 'الكامل', 'الناقص', 'صح', 'غلط', 'الصح', 'الغلط',
    'تمام', 'ماشي', 'اوك', 'طيب', 'ممتاز', 'جيد', 'سيء', 'حلو', 'بشع',
    'مضبوط', 'مزبوظ', 'مزبوط', 'ملغى', 'ملغي', 'مرفوض', 'مقبول', 'جاهز',
    'خالص', 'منتهي', 'مقفول', 'مسكر', 'مفتوح',
    
    # 11. Transaction specific & Request Indicators
    'طلب', 'اريد', 'لزم', 'لازم', 'لازمني', 'يلزمني', 'مطلوب', 'بدي', 'بحتاج',
    'احتاج', 'عايز', 'ابغي', 'ابغا', 'محتاج', 'متوفر', 'عندي', 'موجود', 'معي',
    'عندك', 'معك', 'لكم', 'لنا', 'لهم', 'الي', 'الك', 'اله', 'الها', 'الهم',
    'علي', 'عليك', 'عليه', 'عليها', 'عليهم', 'مني', 'منك', 'منه', 'منها',
    'منهم', 'فيني', 'فينك', 'فيه', 'فيها', 'فيهم',
    
    # 12. Business & Commerece
    'بضائع', 'بضايع', 'شحنة', 'شحنه', 'طلبية', 'طلبيه', 'عربون', 'مقدم',
    'مؤخر', 'اقساط', 'قسط', 'تسديد', 'سداد', 'وفاء', 'دين', 'ديون', 'سلف',
    'شام', 'الشام', 'شامنا', 'غولد',
    'سلفة', 'سلفه', 'قرض', 'قروض', 'تمويل', 'استثمار', 'مساهمة', 'مساهمه',
    'شراكة', 'شراكه', 'عقد', 'اتفاق', 'صفقة', 'صفقه', 'مقاولة', 'مقاوله',
    'مناقصة', 'مناقصه', 'مزايدة', 'مزايده', 'ضمان', 'كفالة', 'كفاله', 'رهن',
    'تامينات', 'تأمينات', 'حجز', 'مخالفة', 'مخالفه', 'غرامة', 'غرامه', 'جزاء',
    
    # 13. System words and IT terms
    'نظام', 'سيستم', 'برنامج', 'تطبيق', 'موقع', 'رابط', 'ايميل', 'رسالة',
    'رساله', 'مسج', 'صورة', 'صوره', 'ملف', 'مستند', 'وثيقة', 'وثيقه', 'هوية',
    'هويه', 'جواز', 'سفر', 'رقم', 'كود', 'رمز', 'شفيرة', 'شفرة', 'شيفره',
    'باسورد', 'كلمة', 'مرور', 'سر', 'دخول', 'خروج', 'تحديث', 'تنزيل', 'تحميل',
    
    # 14. Locations/Places
    'بلد', 'دولة', 'دوله', 'مدينة', 'مدينه', 'قرية', 'قريه', 'شارع',
    'حارة', 'حاره', 'حي', 'منطقة', 'منطقه', 'محافظة', 'محافظه', 'عاصمة', 'عاصمه',
    'سوق', 'مول', 'مجمع', 'بناية', 'بنايه', 'عمارة', 'عماره', 'طابق', 'شقة', 'شقه',
    'مخزن', 'مستودع', 'ورشة', 'ورشه', 'مصنع', 'معمل',
    
    # 15. Directions
    'يمين', 'يسار', 'شمال', 'جنوب', 'شرق', 'غرب', 'فوق', 'تحت', 'امام', 'قدام',
    'خلف', 'ورا', 'وراء', 'جنب', 'جانب', 'حوالي', 'قريب', 'بعيد',
    
    # 16. Quantifiers and Qualifiers
    'كل', 'بعض', 'اي', 'أي', 'احد', 'أحد', 'الا', 'إلا', 'نفس', 'نفسه',
    'ذات', 'ذاته', 'بدل', 'عوض', 'مكان', 'مطرح', 'شبه', 'تقريبا',
    'بالضبط', 'تماما', 'أكيد', 'اكيد', 'طبعا', 'مستحيل', 'صعب', 'سهل'
}

NORM_EXCLUDED_DESTS = set(normalize_arabic(w) for w in EXCLUDED_DEST_WORDS)

def preprocess_message(text):
    # Remove decimal and thousand separators from numbers to ignore them
    text = re.sub(r'(?<=\d)[.,،٫٬](?=\d)', '', text)
    
    # Split words stuck to numbers like "50الف" or "يورو10500" or "10500دولار"
    text = re.sub(r'(\d+)(الف|مليون|ميه|مئة)', r'\1 \2', text)
    
    # Split currency names/symbols stuck to numbers (e.g. "يورو500" -> "يورو 500", "500دولار" -> "500 دولار")
    currency_words = r'(دولار|يورو|ليره|ليرة|دينار|درهم|ريال|جنيه|\$|€|₺)'
    text = re.sub(r'(' + currency_words[1:-1] + r')(\d)', r'\1 \2', text)
    text = re.sub(r'(\d)(' + currency_words[1:-1] + r')', r'\1 \2', text)
    
    return text

def parse_amount(text):
    mapping = {
        'ميه': 100, 'ميتين': 200, 'تلاتميه': 300, 'اربعميه': 400, 'خمسميه': 500,
        'ستميه': 600, 'سبعميه': 700, 'تمانميه': 800, 'تسعميه': 900, 'مائة': 100, 'مئة': 100,
        'خمستالاف': 5000, 'تلاتالاف': 3000, 'تلتالاف': 3000, 'ستالاف': 6000, 'سبعتالاف': 7000, 'تمانتالاف': 8000, 'تسعتالاف': 9000,
        'الفين': 2000, 'الف': 1000, 'الاف': 1000, 'نص': 0.5, 'ربع': 0.25, 'تلت': 0.33,
        'مليونين': 2000000, 'مليون': 1000000, 'ملايين': 1000000,
        'مليار': 1000000000, 'بليون': 1000000000,
        'واحد': 1, 'اثنين': 2, 'تنين': 2, 'تلاته': 3, 'تلات': 3, 'اربعه': 4, 'اربع': 4,
        'خمسه': 5, 'خمس': 5, 'سته': 6, 'ست': 6, 'سبعه': 7, 'سبع': 7, 'تمانيه': 8, 'تمان': 8, 'ثمانيه': 8, 'ثمان': 8,
        'تسعه': 9, 'تسع': 9, 'عشره': 10, 'عشر': 10,
        'عشرين': 20, 'تلاتين': 30, 'ثلاثين': 30, 'اربعين': 40, 'خمسين': 50, 'ستين': 60, 'سبعين': 70, 'تمانين': 80, 'ثمانين': 80, 'تسعين': 90
    }
    
    tokens = text.split()
    numbers = []
    
    for token in tokens:
        if re.match(r'^\d+(\.\d+)?$', token):
            numbers.append(float(token))
        else:
            match = re.match(r'^(\d+)(الف|مليون)$', token)
            if match:
                val = float(match.group(1))
                mult = 1000 if match.group(2) == 'الف' else 1000000
                numbers.append(val * mult)
                continue
                
            norm_token = normalize_arabic(token)
            if norm_token.startswith('و') and len(norm_token) > 1:
                norm_token = norm_token.lstrip('و')
            if norm_token in mapping:
                numbers.append(mapping[norm_token])
    
    if not numbers:
        match = re.search(r'\d+', text)
        if match:
            return float(match.group())
        return 0

    total = 0
    current_acc = 0
    for num in numbers:
        if num in [1000, 1000000]:
            if current_acc == 0:
                current_acc = 1
                current_acc *= num
            elif current_acc >= num:
                pass # Ignore redundant multiplier (e.g., '100.000 الف')
            else:
                current_acc *= num
                
            total += current_acc
            current_acc = 0
        else:
            current_acc += num
            
    total += current_acc
    return total

def find_best_match(word, candidates, cutoff=0.6):
    norm_word = normalize_arabic(word)
    
    # Currency symbols shortcut map
    sym_map = {'$': 'دولار', '€': 'يورو', 'tl': 'ليرة', '₺': 'ليرة', 'try': 'ليرة'}
    if norm_word.lower() in sym_map:
        norm_word = sym_map[norm_word.lower()]

    # Exact check
    for cand_id, cand_names in candidates.items():
        for cand_name in cand_names:
            if normalize_arabic(cand_name) == norm_word:
                return cand_id, cand_name, 1.0
                
    # Without common prefixes
    stripped_word = norm_word
    if norm_word.startswith('ب'):
        stripped_word = norm_word.lstrip('ب')
    elif norm_word.startswith('ال'):
        stripped_word = norm_word.lstrip('ال')
        
    for cand_id, cand_names in candidates.items():
        for cand_name in cand_names:
            if normalize_arabic(cand_name) == stripped_word:
                return cand_id, cand_name, 0.95

    # Fuzzy matching
    all_flat = []
    mapping = {}
    for cand_id, cand_names in candidates.items():
        for cand_name in cand_names:
            all_flat.append(cand_name)
            mapping[cand_name] = (cand_id, cand_name)
            norm_cand = normalize_arabic(cand_name)
            if norm_cand != cand_name:
                all_flat.append(norm_cand)
                mapping[norm_cand] = (cand_id, cand_name)
                
    matches = difflib.get_close_matches(norm_word, all_flat, n=1, cutoff=cutoff)
    if matches:
        score = difflib.SequenceMatcher(None, norm_word, matches[0]).ratio()
        if len(norm_word) >= 4 and len(matches[0]) >= 4 and norm_word[0] != matches[0][0]:
            score *= 0.8 # Penalty for first letter mismatch
        if score >= cutoff:
            return mapping[matches[0]][0], mapping[matches[0]][1], float(f"{score:.2f}")
        
    matches = difflib.get_close_matches(stripped_word, all_flat, n=1, cutoff=cutoff)
    if matches:
        score = difflib.SequenceMatcher(None, stripped_word, matches[0]).ratio()
        if len(stripped_word) >= 4 and len(matches[0]) >= 4 and stripped_word[0] != matches[0][0]:
            score *= 0.8
        score *= 0.95 # Apply slight penalty for stripped prefix matching via fuzzy
        if score >= cutoff:
            return mapping[matches[0]][0], mapping[matches[0]][1], float(f"{score:.2f}")
        
    return None, None, 0.0

def determine_action(text):
    norm_text = normalize_arabic(text)
    
    # Exact phrase overrides (highest priority)
    if 'بدي جيب' in norm_text:
        return 'available', 1.0
        
    words = norm_text.split()
    
    need_keywords = ['طلب','اريد','لزم','لازم', 'لازمني', 'يلزمني', 'مطلوب','بحتاج', 'احتاج', 'عايز', 'محتاج','بدي']
    avail_keywords = ['متوفر', 'عندي', 'موجود', 'جاهز', 'معي', 'عنا']
    
    # Exact word match first (safest, evaluate words sequentially for precedence)
    for word in words:
        if word in need_keywords:
            return 'need', 1.0
        if word in avail_keywords:
            return 'available', 1.0
            
    # Substring match (find earliest occurring keyword overall)
    earliest_idx = len(norm_text)
    best_action = 'unknown'
    best_score = 0.0
    
    for kw in need_keywords:
        idx = norm_text.find(kw)
        if idx != -1 and idx < earliest_idx:
            earliest_idx = idx
            best_action = 'need'
            best_score = 0.9
            
    for kw in avail_keywords:
        idx = norm_text.find(kw)
        if idx != -1 and idx < earliest_idx:
            earliest_idx = idx
            best_action = 'available'
            best_score = 0.9
            
    if best_action != 'unknown':
        return best_action, best_score
            
    # Fuzzy match action
    for word in words:
        for kw in need_keywords:
            if difflib.SequenceMatcher(None, kw, word).ratio() > 0.8:
                return 'need', 0.8
        for kw in avail_keywords:
            if difflib.SequenceMatcher(None, kw, word).ratio() > 0.8:
                return 'available', 0.8
            
    return 'unknown', 0.0

def main():
    try:
        sys.stdin.reconfigure(encoding='utf-8')
        sys.stdout.reconfigure(encoding='utf-8')
        input_data = json.loads(sys.stdin.read())
        message = input_data.get("message", "")
        
        if len(message.strip()) > 80:
            print(json.dumps({"error": "Message exceeds 80 characters limit"}))
            return
            
        db_dests = input_data.get("destinations", [])

        db_curs_list = input_data.get("currencies", [])
        
        # Format db_curs into {db_id: [name1, ...]}
        db_curs = {}
        for row in db_curs_list:
            c_id = str(row['id'])
            if c_id not in db_curs:
                db_curs[c_id] = []
            db_curs[c_id].append(row['name'])
        
        # Format db_dests into mapping
        dests_mapping = {}
        original_dest_names = {}
        def_currencies = {}
        for row in db_dests:
            d_id = str(row['id'])
            original_dest_names[d_id] = row['name']
            def_currencies[d_id] = str(row.get('defcurrency')) if row.get('defcurrency') else None
            
            if d_id not in dests_mapping:
                dests_mapping[d_id] = []
            parts = [p.strip() for p in row['name'].split(',')]
            dests_mapping[d_id].extend(parts)
        
        message = preprocess_message(message)
        
        action, action_score = determine_action(message)
        
        # Replace currency symbols with their Arabic names before tokenizing
        spaced_msg = message
        spaced_msg = spaced_msg.replace('$', ' دولار ')
        spaced_msg = spaced_msg.replace('€', ' يورو ')
        spaced_msg = spaced_msg.replace('₺', ' ليرة ')
        amount = parse_amount(spaced_msg)
        
        if amount > 100000:
            print(json.dumps({"error": "Amount exceeds 100,000 limit"}))
            return
            
        tokens = spaced_msg.split()
        
        best_cur_id = "unknown"
        best_dest_id = "unknown"
        best_dest_name = "unknown"
        cur_score = 0.0
        dest_score = 0.0
        
        for token in tokens:
            norm_tok = normalize_arabic(token)
            
            cur_match = find_best_match(token, db_curs, cutoff=0.7)
            if cur_match[0] and cur_match[2] > cur_score:
                best_cur_id = cur_match[0]
                cur_score = cur_match[2]
                    
            stripped_tok = norm_tok
            if norm_tok.startswith('ب') and len(norm_tok) > 1:
                stripped_tok = norm_tok[1:]
            elif norm_tok.startswith('ال') and len(norm_tok) > 2:
                stripped_tok = norm_tok[2:]
            elif norm_tok.startswith('بال') and len(norm_tok) > 3:
                stripped_tok = norm_tok[3:]
            elif norm_tok.startswith('ول') and len(norm_tok) > 2:
                stripped_tok = norm_tok[2:]
            elif norm_tok.startswith('وال') and len(norm_tok) > 3:
                stripped_tok = norm_tok[3:]

            if norm_tok in NORM_EXCLUDED_DESTS or stripped_tok in NORM_EXCLUDED_DESTS:
                continue
                
            dest_match = find_best_match(token, dests_mapping, cutoff=0.7)
            if dest_match[0] and dest_match[2] > dest_score:
                best_dest_id = dest_match[0]
                best_dest_name = original_dest_names[best_dest_id]
                dest_score = dest_match[2]
                    
        # Fallback to destination default currency if no currency was explicitly mentioned
        if best_cur_id == "unknown" and best_dest_id != "unknown":
            dest_def_cur = def_currencies.get(best_dest_id)
            if dest_def_cur and dest_def_cur != "None":
                best_cur_id = dest_def_cur
                cur_score = 0.9  # Confident fallback

        result = {
            "action": action,
            "amount": int(amount) if amount == int(amount) else amount,
            "currency": best_cur_id,
            "destination": {
                "id": best_dest_id,
                "name": best_dest_name
            },
            "scores": {
                "action": action_score,
                "currency": cur_score,
                "destination": dest_score
            }
        }
        print(json.dumps(result, ensure_ascii=False))
        
    except Exception as e:
        print(json.dumps({"error": str(e)}))

if __name__ == "__main__":
    main()
