"""
وحدة نماذج الذكاء الاصطناعي المتكاملة
"""

import streamlit as st
import pandas as pd
import random
from datetime import datetime
import time

class AIModelsApp:
    """
    وحدة نماذج الذكاء الاصطناعي المتكاملة للنظام
    """
    
    def __init__(self):
        """
        تهيئة وحدة نماذج الذكاء الاصطناعي
        """
        # تهيئة حالة الجلسة الخاصة بنماذج الذكاء الاصطناعي إذا لم تكن موجودة
        if 'ai_models' not in st.session_state:
            # إنشاء بيانات تجريبية لنماذج الذكاء الاصطناعي
            st.session_state.ai_models = self._generate_sample_models()
        
        if 'api_keys' not in st.session_state:
            # إنشاء بيانات تجريبية لمفاتيح API
            st.session_state.api_keys = {
                'openai': 'sk-**************************',
                'huggingface': 'hf_**************************',
                'azure': 'az_**************************',
                'local': 'local_key_not_required'
            }
        
        if 'model_usage' not in st.session_state:
            # إنشاء بيانات تجريبية لاستخدام النماذج
            st.session_state.model_usage = self._generate_sample_usage()
    
    def run(self):
        """
        تشغيل وحدة نماذج الذكاء الاصطناعي
        """
        st.markdown("<h2 class='module-title'>وحدة نماذج الذكاء الاصطناعي</h2>", unsafe_allow_html=True)
        
        # إنشاء تبويبات لنماذج الذكاء الاصطناعي المختلفة
        tabs = st.tabs(["النماذج المتاحة", "استخدام النماذج", "إدارة API", "سجل الاستخدام"])
        
        with tabs[0]:
            self._render_available_models()
        
        with tabs[1]:
            self._render_model_usage()
        
        with tabs[2]:
            self._render_api_management()
        
        with tabs[3]:
            self._render_usage_history()
    
    def _render_available_models(self):
        """
        عرض النماذج المتاحة
        """
        st.markdown("### النماذج المتاحة")
        st.markdown("عرض نماذج الذكاء الاصطناعي المتاحة للاستخدام في النظام")
        
        # فلترة النماذج
        col1, col2 = st.columns(2)
        
        with col1:
            filter_type = st.multiselect(
                "نوع النموذج",
                options=["الكل", "تحليل نصوص", "استخراج بيانات", "تصنيف مستندات", "تلخيص", "ترجمة", "تنبؤ"],
                default=["الكل"]
            )
        
        with col2:
            filter_provider = st.multiselect(
                "مزود الخدمة",
                options=["الكل", "OpenAI", "HuggingFace", "Azure", "محلي"],
                default=["الكل"]
            )
        
        # تطبيق التصفية
        filtered_models = st.session_state.ai_models
        
        if "الكل" not in filter_type:
            filtered_models = [m for m in filtered_models if m['type'] in filter_type]
        
        if "الكل" not in filter_provider:
            filtered_models = [m for m in filtered_models if m['provider'] in filter_provider]
        
        # عرض النماذج
        if filtered_models:
            # تقسيم النماذج إلى صفوف
            for i in range(0, len(filtered_models), 3):
                cols = st.columns(3)
                for j in range(3):
                    if i + j < len(filtered_models):
                        model = filtered_models[i + j]
                        with cols[j]:
                            st.markdown(f"""
                            <div style="border: 1px solid #dee2e6; border-radius: 8px; padding: 15px; height: 100%;">
                                <h4 style="color: var(--primary-color);">{model['name']}</h4>
                                <p><strong>النوع:</strong> {model['type']}</p>
                                <p><strong>المزود:</strong> {model['provider']}</p>
                                <p><strong>الإصدار:</strong> {model['version']}</p>
                                <p><strong>الحالة:</strong> <span style="color: {'green' if model['status'] == 'متاح' else 'orange'};">{model['status']}</span></p>
                                <p>{model['description']}</p>
                            </div>
                            """, unsafe_allow_html=True)
        else:
            st.info("لا توجد نماذج تطابق معايير التصفية", icon="ℹ️")
    
    def _render_model_usage(self):
        """
        عرض واجهة استخدام النماذج
        """
        st.markdown("### استخدام نماذج الذكاء الاصطناعي")
        st.markdown("استخدام نماذج الذكاء الاصطناعي لمعالجة البيانات والمستندات")
        
        # اختيار النموذج
        model_names = [m['name'] for m in st.session_state.ai_models if m['status'] == 'متاح']
        selected_model = st.selectbox("اختر النموذج", options=model_names, key="selected_model")
        
        # الحصول على معلومات النموذج المحدد
        model_info = next((m for m in st.session_state.ai_models if m['name'] == selected_model), None)
        
        if model_info:
            st.markdown(f"""
            <div style="background-color: var(--gray-100); padding: 15px; border-radius: 8px; margin-bottom: 20px;">
                <h4 style="color: var(--primary-color);">{model_info['name']}</h4>
                <p><strong>النوع:</strong> {model_info['type']}</p>
                <p><strong>المزود:</strong> {model_info['provider']}</p>
                <p><strong>الوصف:</strong> {model_info['description']}</p>
            </div>
            """, unsafe_allow_html=True)
            
            # واجهة الاستخدام حسب نوع النموذج
            if model_info['type'] in ["تحليل نصوص", "تلخيص", "ترجمة"]:
                self._render_text_model_interface(model_info)
            elif model_info['type'] in ["استخراج بيانات", "تصنيف مستندات"]:
                self._render_document_model_interface(model_info)
            elif model_info['type'] == "تنبؤ":
                self._render_prediction_model_interface(model_info)
    
    def _render_text_model_interface(self, model_info):
        """
        عرض واجهة استخدام نماذج النصوص
        """
        # إدخال النص
        input_text = st.text_area(
            "أدخل النص",
            height=150,
            placeholder="أدخل النص للمعالجة...",
            key="model_input_text"
        )
        
        # خيارات النموذج
        st.markdown("#### خيارات النموذج")
        
        col1, col2, col3 = st.columns(3)
        
        with col1:
            temperature = st.slider("درجة الإبداعية", 0.0, 1.0, 0.7, 0.1, key="temperature")
        
        with col2:
            max_tokens = st.slider("الحد الأقصى للكلمات", 100, 2000, 500, 100, key="max_tokens")
        
        with col3:
            if model_info['type'] == "ترجمة":
                target_lang = st.selectbox(
                    "اللغة الهدف",
                    options=["الإنجليزية", "العربية", "الفرنسية", "الإسبانية", "الألمانية"],
                    key="target_lang"
                )
        
        # زر المعالجة
        if st.button("معالجة النص", key="process_text_btn"):
            if input_text:
                # محاكاة عملية المعالجة
                with st.spinner("جاري معالجة النص..."):
                    # محاكاة وقت المعالجة
                    time.sleep(2)
                    
                    # إنشاء نص ناتج تجريبي
                    if model_info['type'] == "تحليل نصوص":
                        output_text = f"تحليل النص:\n\n1. يحتوي النص على {len(input_text.split())} كلمة.\n2. الموضوع الرئيسي: مناقصات ومشاريع.\n3. المشاعر: محايدة.\n4. الكلمات المفتاحية: مشروع، مناقصة، تحليل، تسعير."
                    elif model_info['type'] == "تلخيص":
                        output_text = f"ملخص النص:\n\n{input_text.split('.')[0]}. " + "هذا ملخص تجريبي للنص المدخل يحتوي على أهم النقاط والمعلومات."
                    elif model_info['type'] == "ترجمة":
                        output_text = f"الترجمة إلى {target_lang}:\n\n" + "This is a sample translation of the input text. It contains the main points and information."
                    
                    # عرض النتيجة
                    st.markdown("#### نتيجة المعالجة")
                    st.text_area("النص الناتج", value=output_text, height=150, key="model_output_text")
                    
                    # إضافة الاستخدام إلى السجل
                    self._add_usage_to_history(model_info['name'], model_info['type'], len(input_text.split()))
            else:
                st.warning("يرجى إدخال نص للمعالجة", icon="⚠️")
    
    def _render_document_model_interface(self, model_info):
        """
        عرض واجهة استخدام نماذج المستندات
        """
        # رفع المستند
        uploaded_file = st.file_uploader(
            "اختر مستنداً للمعالجة",
            type=["pdf", "docx", "txt"],
            key="model_doc_upload"
        )
        
        # خيارات النموذج
        st.markdown("#### خيارات النموذج")
        
        col1, col2 = st.columns(2)
        
        with col1:
            if model_info['type'] == "استخراج بيانات":
                extraction_type = st.multiselect(
                    "نوع البيانات المستخرجة",
                    options=["جداول الكميات", "الأسعار", "المواصفات الفنية", "الشروط التعاقدية", "المعلومات العامة"],
                    default=["جداول الكميات", "الأسعار"],
                    key="extraction_type"
                )
            elif model_info['type'] == "تصنيف مستندات":
                classification_type = st.selectbox(
                    "نوع التصنيف",
                    options=["نوع المستند", "مجال المشروع", "مستوى المخاطر"],
                    key="classification_type"
                )
        
        with col2:
            confidence_threshold = st.slider("حد الثقة", 0.0, 1.0, 0.7, 0.1, key="confidence_threshold")
        
        # زر المعالجة
        if st.button("معالجة المستند", key="process_doc_btn"):
            if uploaded_file is not None:
                # محاكاة عملية المعالجة
                with st.spinner("جاري معالجة المستند..."):
                    # محاكاة وقت المعالجة
                    time.sleep(3)
                    
                    st.success("تمت معالجة المستند بنجاح!", icon="✅")
                    
                    # عرض النتائج حسب نوع النموذج
                    if model_info['type'] == "استخراج بيانات":
                        st.markdown("#### البيانات المستخرجة")
                        
                        # عرض بيانات تجريبية للجداول المستخرجة
                        if "جداول الكميات" in extraction_type:
                            st.markdown("##### جدول الكميات")
                            
                            # إنشاء بيانات تجريبية
                            quantities_data = []
                            for i in range(5):
                                quantities_data.append({
                                    "البند": f"بند {i+1}",
                                    "الوصف": f"وصف البند {i+1}",
                                    "الوحدة": random.choice(["متر", "متر مربع", "متر مكعب", "طن", "قطعة"]),
                                    "الكمية": random.randint(10, 1000),
                                    "السعر الوحدة": random.randint(100, 5000),
                                    "الإجمالي": 0
                                })
                                quantities_data[i]["الإجمالي"] = quantities_data[i]["الكمية"] * quantities_data[i]["السعر الوحدة"]
                            
                            # عرض الجدول
                            quantities_df = pd.DataFrame(quantities_data)
                            st.dataframe(quantities_df, use_container_width=True)
                        
                        if "الأسعار" in extraction_type:
                            st.markdown("##### ملخص الأسعار")
                            
                            # إنشاء بيانات تجريبية
                            price_summary = {
                                "إجمالي قيمة المشروع": f"{random.randint(1000000, 10000000)} ريال",
                                "مدة التنفيذ": f"{random.randint(6, 36)} شهر",
                                "قيمة الدفعة المقدمة": f"{random.randint(10, 30)}%",
                                "غرامة التأخير": f"{random.randint(1, 10)}% (بحد أقصى 10% من قيمة العقد)"
                            }
                            
                            # عرض الملخص
                            for key, value in price_summary.items():
                                st.markdown(f"**{key}:** {value}")
                    
                    elif model_info['type'] == "تصنيف مستندات":
                        st.markdown("#### نتائج التصنيف")
                        
                        if classification_type == "نوع المستند":
                            # إنشاء بيانات تجريبية
                            doc_types = [
                                {"نوع المستند": "كراسة شروط", "نسبة الثقة": 0.92},
                                {"نوع المستند": "عقد", "نسبة الثقة": 0.05},
                                {"نوع المستند": "مواصفات فنية", "نسبة الثقة": 0.02},
                                {"نوع المستند": "جدول كميات", "نسبة الثقة": 0.01}
                            ]
                            
                            # عرض النتائج
                            doc_types_df = pd.DataFrame(doc_types)
                            st.dataframe(doc_types_df, use_container_width=True)
                            
                            st.markdown(f"**التصنيف النهائي:** كراسة شروط (بثقة 92%)")
                    
                    # إضافة الاستخدام إلى السجل
                    self._add_usage_to_history(model_info['name'], model_info['type'], 1)
            else:
                st.warning("يرجى رفع مستند للمعالجة", icon="⚠️")
    
    def _render_prediction_model_interface(self, model_info):
        """
        عرض واجهة استخدام نماذج التنبؤ
        """
        # اختيار نوع التنبؤ
        prediction_type = st.selectbox(
            "نوع التنبؤ",
            options=["تنبؤ بتكلفة المشروع", "تنبؤ بمدة التنفيذ", "تنبؤ بالمخاطر"],
            key="prediction_type"
        )
        
        # إدخال البيانات حسب نوع التنبؤ
        if prediction_type == "تنبؤ بتكلفة المشروع":
            st.markdown("#### بيانات المشروع")
            
            col1, col2 = st.columns(2)
            
            with col1:
                project_type = st.selectbox(
                    "نوع المشروع",
                    options=["طرق وجسور", "مباني", "بنية تحتية", "مياه وصرف صحي", "كهرباء"],
                    key="project_type"
                )
                
                project_size = st.selectbox(
                    "حجم المشروع",
                    options=["صغير", "متوسط", "كبير", "ضخم"],
                    key="project_size"
                )
            
            with col2:
                project_location = st.selectbox(
                    "موقع المشروع",
                    options=["الرياض", "جدة", "الدمام", "مكة المكرمة", "المدينة المنورة", "تبوك", "أبها"],
                    key="project_location"
                )
                
                project_duration = st.slider("مدة التنفيذ (بالشهور)", 3, 60, 12, 3, key="project_duration")
        
        elif prediction_type == "تنبؤ بمدة التنفيذ":
            st.markdown("#### بيانات المشروع")
            
            col1, col2 = st.columns(2)
            
            with col1:
                project_type = st.selectbox(
                    "نوع المشروع",
                    options=["طرق وجسور", "مباني", "بنية تحتية", "مياه وصرف صحي", "كهرباء"],
                    key="duration_project_type"
                )
                
                project_budget = st.number_input(
                    "ميزانية المشروع (بالمليون ريال)",
                    min_value=1.0,
                    max_value=1000.0,
                    value=10.0,
                    step=1.0,
                    key="project_budget"
                )
            
            with col2:
                project_location = st.selectbox(
                    "موقع المشروع",
                    options=["الرياض", "جدة", "الدمام", "مكة المكرمة", "المدينة المنورة", "تبوك", "أبها"],
                    key="duration_project_location"
                )
                
                resources_level = st.selectbox(
                    "مستوى الموارد",
                    options=["منخفض", "متوسط", "عالي"],
                    key="resources_level"
                )
        
        elif prediction_type == "تنبؤ بالمخاطر":
            st.markdown("#### بيانات المشروع")
            
            col1, col2 = st.columns(2)
            
            with col1:
                project_type = st.selectbox(
                    "نوع المشروع",
                    options=["طرق وجسور", "مباني", "بنية تحتية", "مياه وصرف صحي", "كهرباء"],
                    key="risk_project_type"
                )
                
                project_complexity = st.selectbox(
                    "مستوى تعقيد المشروع",
                    options=["بسيط", "متوسط", "معقد", "معقد جداً"],
                    key="project_complexity"
                )
            
            with col2:
                project_location = st.selectbox(
                    "موقع المشروع",
                    options=["الرياض", "جدة", "الدمام", "مكة المكرمة", "المدينة المنورة", "تبوك", "أبها"],
                    key="risk_project_location"
                )
                
                previous_experience = st.selectbox(
                    "الخبرة السابقة",
                    options=["لا توجد خبرة", "خبرة محدودة", "خبرة متوسطة", "خبرة واسعة"],
                    key="previous_experience"
                )
        
        # زر التنبؤ
        if st.button("تنفيذ التنبؤ", key="predict_btn"):
            # محاكاة عملية التنبؤ
            with st.spinner("جاري تنفيذ التنبؤ..."):
                # محاكاة وقت المعالجة
                time.sleep(2)
                
                st.success("تم تنفيذ التنبؤ بنجاح!", icon="✅")
                
                # عرض النتائج حسب نوع التنبؤ
                if prediction_type == "تنبؤ بتكلفة المشروع":
                    st.markdown("#### نتائج التنبؤ بالتكلفة")
                    
                    # إنشاء بيانات تجريبية
                    base_cost = random.randint(5000000, 50000000)
                    min_cost = int(base_cost * 0.9)
                    max_cost = int(base_cost * 1.1)
                    
                    st.markdown(f"""
                    <div style="background-color: var(--gray-100); padding: 20px; border-radius: 8px; text-align: center;">
                        <h3 style="color: var(--primary-color);">{base_cost:,} ريال</h3>
                        <p>نطاق التكلفة المتوقع: {min_cost:,} - {max_cost:,} ريال</p>
                    </div>
                    """, unsafe_allow_html=True)
                    
                    # عرض تفاصيل التكلفة
                    st.markdown("##### تفاصيل التكلفة")
                    
                    cost_details = {
                        "المواد": int(base_cost * 0.6),
                        "العمالة": int(base_cost * 0.25),
                        "المعدات": int(base_cost * 0.1),
                        "أخرى": int(base_cost * 0.05)
                    }
                    
                    # عرض الرسم البياني
                    cost_df = pd.DataFrame({
                        "البند": list(cost_details.keys()),
                        "التكلفة": list(cost_details.values())
                    })
                    
                    st.bar_chart(cost_df.set_index("البند"))
                
                elif prediction_type == "تنبؤ بمدة التنفيذ":
                    st.markdown("#### نتائج التنبؤ بمدة التنفيذ")
                    
                    # إنشاء بيانات تجريبية
                    base_duration = random.randint(12, 36)
                    min_duration = int(base_duration * 0.9)
                    max_duration = int(base_duration * 1.2)
                    
                    st.markdown(f"""
                    <div style="background-color: var(--gray-100); padding: 20px; border-radius: 8px; text-align: center;">
                        <h3 style="color: var(--primary-color);">{base_duration} شهر</h3>
                        <p>نطاق المدة المتوقع: {min_duration} - {max_duration} شهر</p>
                    </div>
                    """, unsafe_allow_html=True)
                    
                    # عرض الجدول الزمني
                    st.markdown("##### الجدول الزمني التقديري")
                    
                    timeline_data = [
                        {"المرحلة": "التجهيز والتخطيط", "المدة (شهر)": int(base_duration * 0.1), "النسبة": "10%"},
                        {"المرحلة": "الأعمال الأولية", "المدة (شهر)": int(base_duration * 0.2), "النسبة": "20%"},
                        {"المرحلة": "الأعمال الرئيسية", "المدة (شهر)": int(base_duration * 0.5), "النسبة": "50%"},
                        {"المرحلة": "التشطيبات", "المدة (شهر)": int(base_duration * 0.15), "النسبة": "15%"},
                        {"المرحلة": "الاختبار والتسليم", "المدة (شهر)": int(base_duration * 0.05), "النسبة": "5%"}
                    ]
                    
                    timeline_df = pd.DataFrame(timeline_data)
                    st.dataframe(timeline_df, use_container_width=True)
                
                elif prediction_type == "تنبؤ بالمخاطر":
                    st.markdown("#### نتائج تحليل المخاطر")
                    
                    # إنشاء بيانات تجريبية للمخاطر
                    risks = [
                        {"المخاطرة": "تأخر التوريدات", "الاحتمالية": random.randint(30, 70), "التأثير": random.randint(30, 70)},
                        {"المخاطرة": "نقص العمالة", "الاحتمالية": random.randint(30, 70), "التأثير": random.randint(30, 70)},
                        {"المخاطرة": "تغيير المواصفات", "الاحتمالية": random.randint(30, 70), "التأثير": random.randint(30, 70)},
                        {"المخاطرة": "ظروف جوية", "الاحتمالية": random.randint(30, 70), "التأثير": random.randint(30, 70)},
                        {"المخاطرة": "مشاكل تمويلية", "الاحتمالية": random.randint(30, 70), "التأثير": random.randint(30, 70)}
                    ]
                    
                    # حساب درجة المخاطرة
                    for risk in risks:
                        risk_score = (risk["الاحتمالية"] * risk["التأثير"]) / 100
                        if risk_score < 30:
                            risk["المستوى"] = "منخفض"
                            risk["اللون"] = "green"
                        elif risk_score < 60:
                            risk["المستوى"] = "متوسط"
                            risk["اللون"] = "orange"
                        else:
                            risk["المستوى"] = "مرتفع"
                            risk["اللون"] = "red"
                    
                    # عرض جدول المخاطر
                    risks_df = pd.DataFrame([{k: v for k, v in risk.items() if k != "اللون"} for risk in risks])
                    st.dataframe(risks_df, use_container_width=True)
                    
                    # عرض خطة الاستجابة للمخاطر
                    st.markdown("##### خطة الاستجابة للمخاطر")
                    
                    for risk in risks:
                        if risk["المستوى"] == "مرتفع":
                            st.markdown(f"""
                            <div style="background-color: #f8d7da; padding: 10px; border-radius: 5px; margin-bottom: 10px;">
                                <strong>{risk['المخاطرة']} (مخاطرة مرتفعة):</strong> يجب وضع خطة استجابة فورية وتخصيص موارد إضافية للتعامل مع هذه المخاطرة.
                            </div>
                            """, unsafe_allow_html=True)
                
                # إضافة الاستخدام إلى السجل
                self._add_usage_to_history(model_info['name'], model_info['type'], 1)
    
    def _render_api_management(self):
        """
        عرض واجهة إدارة مفاتيح API
        """
        st.markdown("### إدارة مفاتيح API")
        st.markdown("إدارة مفاتيح API للوصول إلى خدمات الذكاء الاصطناعي")
        
        # عرض مفاتيح API الحالية
        st.markdown("#### مفاتيح API الحالية")
        
        for provider, key in st.session_state.api_keys.items():
            col1, col2, col3 = st.columns([3, 5, 2])
            
            with col1:
                st.markdown(f"**{provider.capitalize()}**")
            
            with col2:
                # عرض المفتاح بشكل آمن
                st.text_input(
                    f"مفتاح {provider}",
                    value=key,
                    type="password",
                    key=f"api_key_{provider}",
                    label_visibility="collapsed"
                )
            
            with col3:
                st.button("تحديث", key=f"update_{provider}_btn")
        
        # إضافة مفتاح API جديد
        st.markdown("#### إضافة مفتاح API جديد")
        
        col1, col2, col3 = st.columns([3, 5, 2])
        
        with col1:
            new_provider = st.text_input("اسم المزود", key="new_provider")
        
        with col2:
            new_key = st.text_input("مفتاح API", type="password", key="new_key")
        
        with col3:
            st.markdown("&nbsp;")  # فراغ للمحاذاة
            if st.button("إضافة", key="add_api_key_btn"):
                if new_provider and new_key:
                    st.success(f"تمت إضافة مفتاح API لـ {new_provider} بنجاح", icon="✅")
                else:
                    st.warning("يرجى إدخال اسم المزود ومفتاح API", icon="⚠️")
        
        # إعدادات الأمان
        st.markdown("#### إعدادات الأمان")
        
        st.checkbox("تشفير مفاتيح API في قاعدة البيانات", value=True, key="encrypt_api_keys")
        st.checkbox("تسجيل استخدام مفاتيح API", value=True, key="log_api_usage")
        st.checkbox("تحديد صلاحيات الوصول لمفاتيح API", value=False, key="api_access_control")
    
    def _render_usage_history(self):
        """
        عرض سجل استخدام النماذج
        """
        st.markdown("### سجل استخدام النماذج")
        st.markdown("عرض سجل استخدام نماذج الذكاء الاصطناعي مع إحصائيات الاستخدام")
        
        # عرض إحصائيات الاستخدام
        st.markdown("#### إحصائيات الاستخدام")
        
        col1, col2, col3, col4 = st.columns(4)
        
        with col1:
            st.metric("إجمالي الاستخدامات", len(st.session_state.model_usage))
        
        with col2:
            total_tokens = sum(usage['tokens'] for usage in st.session_state.model_usage)
            st.metric("إجمالي الرموز", f"{total_tokens:,}")
        
        with col3:
            unique_models = len(set(usage['model'] for usage in st.session_state.model_usage))
            st.metric("النماذج المستخدمة", unique_models)
        
        with col4:
            # حساب تكلفة تقديرية
            estimated_cost = total_tokens * 0.0001
            st.metric("التكلفة التقديرية", f"{estimated_cost:.2f} $")
        
        # عرض الرسم البياني للاستخدام
        st.markdown("#### استخدام النماذج حسب النوع")
        
        # تجميع البيانات حسب نوع النموذج
        usage_by_type = {}
        for usage in st.session_state.model_usage:
            if usage['type'] in usage_by_type:
                usage_by_type[usage['type']] += 1
            else:
                usage_by_type[usage['type']] = 1
        
        # تحويل البيانات إلى DataFrame
        usage_df = pd.DataFrame({
            "نوع النموذج": list(usage_by_type.keys()),
            "عدد الاستخدامات": list(usage_by_type.values())
        })
        
        # عرض الرسم البياني
        st.bar_chart(usage_df.set_index("نوع النموذج"))
        
        # عرض سجل الاستخدام
        st.markdown("#### سجل الاستخدام")
        
        # خيارات التصفية
        col1, col2 = st.columns(2)
        
        with col1:
            filter_model_type = st.multiselect(
                "نوع النموذج",
                options=["الكل"] + list(set(usage['type'] for usage in st.session_state.model_usage)),
                default=["الكل"]
            )
        
        with col2:
            date_range = st.selectbox(
                "النطاق الزمني",
                options=["الكل", "اليوم", "الأسبوع الماضي", "الشهر الماضي"]
            )
        
        # تطبيق التصفية
        filtered_usage = st.session_state.model_usage
        
        if "الكل" not in filter_model_type:
            filtered_usage = [u for u in filtered_usage if u['type'] in filter_model_type]
        
        # تحويل البيانات إلى DataFrame
        if filtered_usage:
            usage_df = pd.DataFrame(filtered_usage)
            usage_df = usage_df[['date', 'model', 'type', 'tokens', 'status']]
            usage_df.columns = ['التاريخ', 'النموذج', 'النوع', 'الرموز', 'الحالة']
            
            # عرض الجدول
            st.dataframe(usage_df, use_container_width=True)
        else:
            st.info("لا توجد بيانات استخدام تطابق معايير التصفية", icon="ℹ️")
    
    def _add_usage_to_history(self, model_name, model_type, tokens_count):
        """
        إضافة استخدام إلى سجل الاستخدام
        """
        new_usage = {
            'id': len(st.session_state.model_usage) + 1,
            'model': model_name,
            'type': model_type,
            'tokens': tokens_count,
            'date': datetime.now().strftime("%Y-%m-%d %H:%M"),
            'status': 'ناجح'
        }
        
        st.session_state.model_usage.insert(0, new_usage)
    
    def _generate_sample_models(self):
        """
        إنشاء بيانات تجريبية لنماذج الذكاء الاصطناعي
        """
        models = [
            {
                'id': 1,
                'name': 'GPT-4',
                'type': 'تحليل نصوص',
                'provider': 'OpenAI',
                'version': '4.0',
                'status': 'متاح',
                'description': 'نموذج لغوي متقدم لتحليل النصوص وفهم المحتوى بدقة عالية'
            },
            {
                'id': 2,
                'name': 'BERT-Arabic',
                'type': 'تحليل نصوص',
                'provider': 'HuggingFace',
                'version': '2.1',
                'status': 'متاح',
                'description': 'نموذج متخصص في تحليل النصوص العربية مع دعم للهجات المختلفة'
            },
            {
                'id': 3,
                'name': 'DocExtractor',
                'type': 'استخراج بيانات',
                'provider': 'محلي',
                'version': '1.5',
                'status': 'متاح',
                'description': 'نموذج لاستخراج البيانات من المستندات والعقود بدقة عالية'
            },
            {
                'id': 4,
                'name': 'TenderClassifier',
                'type': 'تصنيف مستندات',
                'provider': 'محلي',
                'version': '2.0',
                'status': 'متاح',
                'description': 'نموذج متخصص في تصنيف مستندات المناقصات والعقود'
            },
            {
                'id': 5,
                'name': 'AzureSummarizer',
                'type': 'تلخيص',
                'provider': 'Azure',
                'version': '3.2',
                'status': 'متاح',
                'description': 'نموذج لتلخيص المستندات الطويلة مع الحفاظ على المعلومات الأساسية'
            },
            {
                'id': 6,
                'name': 'TranslateAI',
                'type': 'ترجمة',
                'provider': 'OpenAI',
                'version': '2.5',
                'status': 'متاح',
                'description': 'نموذج للترجمة بين اللغات المختلفة مع دعم خاص للمصطلحات التقنية'
            },
            {
                'id': 7,
                'name': 'CostPredictor',
                'type': 'تنبؤ',
                'provider': 'محلي',
                'version': '1.8',
                'status': 'متاح',
                'description': 'نموذج للتنبؤ بتكاليف المشاريع بناءً على البيانات التاريخية'
            },
            {
                'id': 8,
                'name': 'RiskAnalyzer',
                'type': 'تنبؤ',
                'provider': 'Azure',
                'version': '2.1',
                'status': 'متاح',
                'description': 'نموذج لتحليل المخاطر المحتملة في المشاريع والمناقصات'
            },
            {
                'id': 9,
                'name': 'GPT-5',
                'type': 'تحليل نصوص',
                'provider': 'OpenAI',
                'version': '5.0-beta',
                'status': 'قيد التطوير',
                'description': 'النسخة التجريبية من الجيل الخامس لنماذج GPT مع قدرات متقدمة'
            },
            {
                'id': 10,
                'name': 'MultiModalAnalyzer',
                'type': 'تحليل نصوص',
                'provider': 'HuggingFace',
                'version': '1.0',
                'status': 'قيد التطوير',
                'description': 'نموذج متعدد الوسائط لتحليل النصوص والصور والمخططات'
            }
        ]
        
        return models
    
    def _generate_sample_usage(self):
        """
        إنشاء بيانات تجريبية لسجل استخدام النماذج
        """
        models = self._generate_sample_models()
        
        usage = []
        for i in range(50):
            # اختيار نموذج عشوائي من النماذج المتاحة
            available_models = [m for m in models if m['status'] == 'متاح']
            model = random.choice(available_models)
            
            # تحديد عدد الرموز بناءً على نوع النموذج
            if model['type'] in ['تحليل نصوص', 'تلخيص', 'ترجمة']:
                tokens = random.randint(100, 2000)
            else:
                tokens = random.randint(500, 5000)
            
            # تحديد تاريخ عشوائي خلال الشهر الماضي
            days_ago = random.randint(0, 30)
            usage_date = (datetime.now() - pd.Timedelta(days=days_ago)).strftime("%Y-%m-%d %H:%M")
            
            entry = {
                'id': i + 1,
                'model': model['name'],
                'type': model['type'],
                'tokens': tokens,
                'date': usage_date,
                'status': 'ناجح' if random.random() < 0.95 else 'فشل'
            }
            
            usage.append(entry)
        
        # ترتيب السجل حسب التاريخ (الأحدث أولاً)
        usage.sort(key=lambda x: x['date'], reverse=True)
        
        return usage