import sqlite3
import pymysql
import time
import os
import google.generativeai as genai
from flask import Flask, jsonify
from slugify import slugify
from datetime import datetime
from collections import defaultdict
from dotenv import load_dotenv
load_dotenv()

app = Flask(__name__)

# إعداد Gemini API
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY") or "AIzaSyDcPNUR3rJibnZofnfypoVoT8rgt0C5ldw"
genai.configure(api_key=GEMINI_API_KEY)
model = genai.GenerativeModel("gemini-2.0-flash")

# إعداد اتصال MySQL
mysql_conn = pymysql.connect(
    host="localhost",
    user="xonegold_ai",
    password="ahmedxonegold@2712",
    database="xonegold_phone",
    charset='utf8mb4'
)

def product_exists(cursor, slug):
    cursor.execute("SELECT id FROM products WHERE slug = %s", (slug,))
    return cursor.fetchone()

def generate_slug(name):
    return slugify(name)

def extract_brand(name):
    return name.split(" ")[0] if " " in name else "Unknown"

# تم تغيير اسم الوسيط model إلى device_model هنا فقط
def generate_ai_descriptions(name, brand, device_model, specs):
    prompt = f"""
    اكتب لي وصفًا احترافيًا مقنعًا للهاتف {name} يشمل:
    1. مقدمة تسويقية.
    2. المواصفات الأهم.
    3. مزايا الهاتف.
    4. عيوب الهاتف.

    المواصفات:
    {specs}
    """
    try:
        response = model.generate_content(prompt)
        return response.text if hasattr(response, "text") else None
    except Exception as e:
        print("⚠️ فشل توليد المحتوى:", e)
        return None

def process_devices():
    sqlite_conn = sqlite3.connect("devices.db")
    sqlite_cursor = sqlite_conn.cursor()

    sqlite_cursor.execute("SELECT id, name, url, image FROM devices")
    devices = sqlite_cursor.fetchall()

    sqlite_cursor.execute("SELECT device_id, spec_name, spec_value FROM basic_specs")
    basic_specs_all = sqlite_cursor.fetchall()

    sqlite_cursor.execute("SELECT device_id, group_name, spec_name, spec_value FROM advanced_specs")
    advanced_specs_all = sqlite_cursor.fetchall()

    # تنظيم المواصفات
    basic_specs_map = defaultdict(list)
    for device_id, sname, svalue in basic_specs_all:
        basic_specs_map[device_id].append((sname, svalue))

    adv_specs_map = defaultdict(lambda: defaultdict(list))
    for device_id, gname, sname, svalue in advanced_specs_all:
        adv_specs_map[device_id][gname].append((sname, svalue))

    with mysql_conn.cursor() as cursor:
        for device in devices:
            device_id, name, url, image = device
            slug = generate_slug(name)
            brand = extract_brand(name)
            model = "Unknown"
            price_global = 0
            price_local = 0

            if product_exists(cursor, slug):
                print(f"✅ {name} موجود مسبقًا، تم تخطيه.")
                continue

            print(f"⬇️ جاري إضافة: {name}")

            # المواصفات النصية
            basic_text = "\n".join([f"{k}: {v}" for k, v in basic_specs_map[device_id]])
            adv_text = "\n".join(
                [f"[{group}]\n" + "\n".join([f"- {k}: {v}" for k, v in specs])
                 for group, specs in adv_specs_map[device_id].items()]
            )
            specs_summary = f"{basic_text}\n{adv_text}"

            # توليد الوصف
            ai_text = generate_ai_descriptions(name, brand, model, specs_summary)
            short_description = ai_text.split("\n")[0] if ai_text else "وصف غير متوفر."

            try:
                cursor.execute("""
                    INSERT INTO products (name, slug, brand, model, image_url, product_url, short_description, full_description, price_global, price_local)
                    VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
                """, (name, slug, brand, model, image, url, short_description, ai_text, price_global, price_local))

                new_product_id = cursor.lastrowid

                for spec_name, spec_value in basic_specs_map[device_id]:
                    cursor.execute("""
                        INSERT INTO basic_specs (product_id, spec_name, spec_value)
                        VALUES (%s, %s, %s)
                    """, (new_product_id, spec_name, spec_value))

                for group_name, specs in adv_specs_map[device_id].items():
                    for spec_name, spec_value in specs:
                        cursor.execute("""
                            INSERT INTO advanced_specs (product_id, group_name, spec_name, spec_value)
                            VALUES (%s, %s, %s, %s)
                        """, (new_product_id, group_name, spec_name, spec_value))

                mysql_conn.commit()
                print(f"✅ تم إدخال {name} بنجاح!")
            except Exception as e:
                print(f"❌ خطأ في إدخال {name}: {e}")

            time.sleep(1.5)

    print("🚀 اكتملت المعالجة.")

@app.route("/ai")
def run_script():
    try:
        process_devices()
        return jsonify({"status": "success", "message": "تم التشغيل ✅"})
    except Exception as e:
        return jsonify({"status": "error", "message": str(e)})

if __name__ == '__main__':
    app.run(debug=True)
