#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import time
import requests
import mysql.connector
from bs4 import BeautifulSoup
import re
import random

# ==========================================
# ⚙️ إعدادات الاتصال
# ==========================================
DB_CONFIG = {
    'user': 'galal',
    'password': '2842004',
    'host': '127.0.0.1',
    'database': 'mysys',
    'raise_on_warnings': True
}

BOT_TOKEN = "8355736702:AAH2gVRDUoNU_MhMvc9SPab3duVkoCKW7t0"

HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
}

# ==========================================
# 🛠️ دوال مساعدة (Normalization)
# ==========================================
def normalize_text(text):
    """تنسيق النص العربي لتحسين البحث"""
    if not text:
        return ""
    # إزالة التشكيل
    text = re.sub(r'[\u0617-\u061A\u064B-\u0652]', '', text)
    # توحيد الألف
    text = re.sub(r'[أإآ]', 'ا', text)
    # توحيد الياء والتاء المربوطة
    text = text.replace('ة', 'ه').replace('ي', 'ى')
    return text

# ==========================================
# 🔌 دوال قاعدة البيانات
# ==========================================
def get_db_connection():
    return mysql.connector.connect(**DB_CONFIG)

def get_platform_id(slug):
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute("SELECT id FROM platforms WHERE slug = %s", (slug,))
    result = cursor.fetchone()
    conn.close()
    return result[0] if result else None

def project_exists(platform_id, remote_id):
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute("SELECT id FROM projects WHERE platform_id = %s AND remote_id = %s", (platform_id, remote_id))
    result = cursor.fetchone()
    conn.close()
    return result is not None

def save_project(platform_id, remote_id, title, url, description):
    conn = get_db_connection()
    cursor = conn.cursor()
    sql = "INSERT INTO projects (platform_id, remote_id, title, url, description) VALUES (%s, %s, %s, %s, %s)"
    cursor.execute(sql, (platform_id, remote_id, title, url, description))
    conn.commit()
    project_id = cursor.lastrowid
    conn.close()
    return project_id

def log_notification(user_id, project_id):
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute("INSERT INTO sent_logs (user_id, project_id) VALUES (%s, %s)", (user_id, project_id))
    conn.commit()
    conn.close()

def get_interested_users(platform_slug, title, description):
    """
    جلب المستخدمين المهتمين مع تجميع الكلمات المفتاحية المطابقة لكل مستخدم
    """
    conn = get_db_connection()
    cursor = conn.cursor(dictionary=True)
    
    full_text = normalize_text(title + " " + description)
    
    # جلب كل الكلمات المفتاحية للمشتركين في هذه المنصة
    sql = """
    SELECT DISTINCT u.id, u.username, u.telegram_chat_id, k.keyword
    FROM users u
    JOIN user_platforms up ON u.id = up.user_id
    JOIN platforms p ON up.platform_id = p.id
    JOIN keywords k ON u.id = k.user_id
    WHERE u.is_active = 1 
      AND u.telegram_chat_id IS NOT NULL
      AND u.is_paused = 0 
      AND p.slug = %s
    """
    cursor.execute(sql, (platform_slug,))
    rows = cursor.fetchall()
    conn.close()
    
    # تجميع النتائج: مفتاح القاموس هو رقم المستخدم
    users_map = {} 

    for row in rows:
        kw_clean = normalize_text(row['keyword'])
        
        # فحص وجود الكلمة في النص
        if kw_clean in full_text:
            uid = row['id']
            
            # إذا كان المستخدم جديداً في القائمة، ننسخ بياناته وننشئ قائمة للكلمات
            if uid not in users_map:
                users_map[uid] = row.copy()
                users_map[uid]['matched_keywords'] = []
            
            # إضافة الكلمة للقائمة (بدون تكرار)
            if row['keyword'] not in users_map[uid]['matched_keywords']:
                users_map[uid]['matched_keywords'].append(row['keyword'])
                
    # إرجاع قائمة المستخدمين (Values of the dictionary)
    return list(users_map.values())

# ==========================================
# 📡 دوال الإرسال والبحث
# ==========================================
def send_telegram(chat_id, msg):
    url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
    payload = {
        "chat_id": chat_id,
        "text": msg,
        "parse_mode": "HTML",
        "disable_web_page_preview": True
    }
    try:
        requests.post(url, json=payload, timeout=10)
    except Exception as e:
        print(f"Telegram Error: {e}")

def process_new_project(platform_slug, remote_id, title, url, description):
    platform_id = get_platform_id(platform_slug)
    if not platform_id:
        return False

    # 1. طباعة للمراقبة
    print(f"🔥 New {platform_slug}: {title}")
    
    # 2. حفظ المشروع في قاعدة البيانات
    project_id = save_project(platform_id, remote_id, title, url, description)

    # 3. جلب المهتمين وإرسال الإشعارات
    interested_users = get_interested_users(platform_slug, title, description)
    
    for user in interested_users:
        # تحويل قائمة الكلمات إلى نص هاشتاج (مثال: #تصميم #فوتوشوب)
        keywords_str = " ".join([f"#{k}" for k in user['matched_keywords']])
        
        # تقصير الوصف للرسالة
        short_desc = (description[:200] + '...') if len(description) > 200 else description
        
        msg = (
            f"🎯 <b>مشروع جديد ({platform_slug})</b>\n"
            f"🏷 <b>{title}</b>\n\n"
            f"🔑 <b>المطابقة:</b> {keywords_str}\n"
            f"📝 {short_desc}\n\n"
            f"🔗 <a href='{url}'>رابط المشروع</a>"
        )
        
        send_telegram(user['telegram_chat_id'], msg)
        log_notification(user['id'], project_id)
        print(f"   -> Sent to {user['username']} (Keywords: {keywords_str})")

    return True

# ==========================================
# 🕷️ دوال الـ Scraping (Updated Logic)
# ==========================================

def scrape_mostaql():
    """جلب مشاريع مستقل (يعتمد على الروابط)"""
    try:
        # صفحة المشاريع - قسم البرمجة - الأحدث
        url = "https://mostaql.com/projects?category=development&sort=latest"
        print("🔎 Scanning Mostaql...")
        resp = requests.get(url, headers=HEADERS, timeout=20)
        soup = BeautifulSoup(resp.text, "html.parser")
        
        # البحث عن أي رابط يحتوي على /project/ داخل h2
        project_links = soup.select("h2 a[href*='/project/']")
        
        for tag in project_links:
            title = tag.text.strip()
            link = tag['href']
            full_url = link if link.startswith("http") else f"https://mostaql.com{link}"
            
            # استخراج الـ ID
            try:
                remote_id = link.split('/project/')[1].split('-')[0]
            except:
                continue
                
            if not remote_id.isdigit(): continue

            # تحقق سريع في الداتابيز قبل فتح الصفحة
            pid = get_platform_id('mostaql')
            if project_exists(pid, remote_id):
                continue

            # Deep Scraping: الدخول للصفحة لجلب الوصف
            try:
                p_resp = requests.get(full_url, headers=HEADERS, timeout=10)
                p_soup = BeautifulSoup(p_resp.text, "html.parser")
                # محاولة جلب الوصف من الكلاسات المحتملة
                desc_el = p_soup.select_one(".card-content") or p_soup.select_one("#project-brief-panel")
                description = desc_el.text.strip() if desc_el else "التفاصيل داخل الرابط"
            except:
                description = "التفاصيل داخل الرابط"

            process_new_project('mostaql', remote_id, title, full_url, description)

    except Exception as e:
        print(f"❌ Mostaql Error: {e}")

def scrape_khamsat():
    """جلب طلبات خمسات (يعتمد على الروابط)"""
    try:
        url = "https://khamsat.com/community/requests"
        print("🔎 Scanning Khamsat...")
        resp = requests.get(url, headers=HEADERS, timeout=20)
        soup = BeautifulSoup(resp.text, "html.parser")
        
        # البحث عن كل الروابط
        all_links = soup.find_all("a", href=True)
        
        for tag in all_links:
            link = tag['href']
            
            # الشروط: رابط طلبات + ليس تعليق + ليس القسم الرئيسي
            if "/community/requests/" in link and "#" not in link:
                title = tag.text.strip()
                if not title: continue 
                
                full_url = link if link.startswith("http") else f"https://khamsat.com{link}"
                
                # استخراج ID
                try:
                    remote_id = link.split('/requests/')[1].split('-')[0]
                except:
                    continue

                if not remote_id.isdigit(): continue

                # تحقق سريع
                pid = get_platform_id('khamsat')
                if project_exists(pid, remote_id):
                    continue

                # Deep Scraping: الدخول للصفحة لجلب الوصف
                try:
                    k_resp = requests.get(full_url, headers=HEADERS, timeout=10)
                    k_soup = BeautifulSoup(k_resp.text, "html.parser")
                    # محاولة جلب الوصف
                    desc_el = k_soup.find("article", class_="article-body") or k_soup.select_one(".post_content")
                    description = desc_el.text.strip() if desc_el else "التفاصيل داخل الرابط"
                except:
                    description = "التفاصيل داخل الرابط"

                process_new_project('khamsat', remote_id, title, full_url, description)

    except Exception as e:
        print(f"❌ Khamsat Error: {e}")

# ==========================================
# 🚀 التشغيل الرئيسي
# ==========================================
if __name__ == "__main__":
    print("🚀 Bot Started (Full Version)...")
    
    while True:
        scrape_mostaql()
        scrape_khamsat()
        
        # انتظار عشوائي بين 30 و 60 ثانية لتجنب الحظر
        wait_time = random.randint(15, 30)
        print(f"💤 Waiting {wait_time}s...")
        time.sleep(wait_time)