from BTKSorgu import BTKSorgu
import time
import pymysql.cursors
import requests
from requests.adapters import HTTPAdapter, Retry
import random
import shutil
import logging

# Logging ayarları
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

def requests_retry_session(retries=5, backoff_factor=1, status_forcelist=(500, 502, 504), timeout=20):
    session = requests.Session()
    retry = Retry(
        total=retries,
        read=retries,
        connect=retries,
        backoff_factor=backoff_factor,
        status_forcelist=status_forcelist
    )
    adapter = HTTPAdapter(max_retries=retry)
    session.mount('http://', adapter)
    session.mount('https://', adapter)
    session.timeout = timeout
    return session

def random_user_agent():
    user_agents = [
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.3 Safari/605.1.15',
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36',
        'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0',
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36',
    ]
    return random.choice(user_agents)

def connect_db():
    try:
        connection = pymysql.connect(
            host='109.123.241.227',
            user='democu_domain',
            password='34trabzon61',
            db='democu_domain',
            charset='utf8mb4',
            cursorclass=pymysql.cursors.DictCursor,
            autocommit=True,
            connect_timeout=10  # Veritabanı bağlantısı için zaman aşımı
        )
        return connection
    except pymysql.MySQLError as e:
        logging.error(f"Veritabanı bağlantı hatası: {e}")
        raise

def is_tesseract_installed():
    return shutil.which("tesseract") is not None

def handle_domain(domain, db):
    try:
        id = domain['id']
        isim = domain.get('firma', '')
        dom = domain.get('domain', '')
        bot_token = domain['bot_token']
        chat_id = domain['chat_id']
        chat_id2 = domain['chat_id2']
        uzanti = ".com"
        uyari = "‼⛔‼⚠️ "
        position = domain.get('position', 'isim_once')
        retry_count = 0
        max_retries = 5
        success = False

        while not success and retry_count < max_retries:
            try:
                if not db.open:
                    logging.warning("Veritabanı bağlantısı kapalı, yeniden bağlanıyor...")
                    db.ping(reconnect=True)

                if not isim or not dom:
                    logging.warning(f"Geçersiz isim veya domain: isim={isim}, dom={dom}")
                    break

                if position == 'isim_once':
                    url = isim + str(dom) + uzanti
                else:  # dom_once
                    url = str(dom) + isim + uzanti

                logging.info(f"Sorgulanan URL: {url}")
                x = BTKSorgu(url)
                geri_donus = str(x)

                if not geri_donus:
                    logging.info(f"Boş sonuç alındı, tekrar deneniyor: {url}")
                    retry_count += 1
                    time.sleep(random.uniform(5, 15))  # Rastgele bekleme süresi ekleyin
                    continue

                liste = geri_donus.split()
                say = len(liste)

                if say > 1:
                    if liste[-1] == "engellenmiştir.":
                        mesaj = str(uyari) + geri_donus
                        if bot_token and chat_id:
                            requests_retry_session(timeout=10).post(
                                url=f'https://api.telegram.org/bot{bot_token}/sendMessage',
                                headers={'User-Agent': random_user_agent()},
                                data={"chat_id": chat_id, "text": mesaj}
                            ).json()

                        for _ in range(2):
                            if bot_token and chat_id2:
                                requests_retry_session(timeout=10).post(
                                    url=f'https://api.telegram.org/bot{bot_token}/sendMessage',
                                    headers={'User-Agent': random_user_agent()},
                                    data={"chat_id": chat_id2, "text": mesaj}
                                ).json()
                            time.sleep(5)

                        logging.info(f"URL Engellendi: {url}")
                        dom += 1
                        with db.cursor() as cursor:
                            cursor.execute('UPDATE url SET domain = %s WHERE id = %s', (dom, id))
                            db.commit()
                    elif liste[-1] == "bulunamadı.":
                        mesaj = "\u2705" + " www." + url + " URL adresi için herhangi bir yasaklama kararı yoktur."
                        logging.info(mesaj)
                        if bot_token and chat_id:
                            requests_retry_session(timeout=10).post(
                                url=f'https://api.telegram.org/bot{bot_token}/sendMessage',
                                headers={'User-Agent': random_user_agent()},
                                data={"chat_id": chat_id, "text": mesaj}
                            ).json()
                    elif liste[-1] == "Değil!":
                        logging.info(f"Uyarı Mesajı: {geri_donus}")
                    else:
                        logging.info(f"Beklenmeyen Sonuç: {geri_donus}")
                else:
                    logging.warning("Hata: Yetersiz veri döndü.")
                    continue

                success = True
            except requests.exceptions.RequestException as e:
                logging.error(f"BTKSorgu hatası: {e}")
                retry_count += 1
                time.sleep(random.uniform(5, 15))  # Rastgele bekleme süresi ekleyin
            except pymysql.MySQLError as e:
                logging.error(f"Veritabanı hatası: {e}")
                db.ping(reconnect=True)
                retry_count += 1
                time.sleep(random.uniform(5, 15))  # Rastgele bekleme süresi ekleyin
            except Exception as e:
                logging.error(f"BTKSorgu hatası: {e}")
                if str(e) == "Muhtemelen Sisteminizde 'tesseract-ocr' Yüklü Değil!":
                    logging.warning("Tesseract-ocr yüklenmemiş. Yeniden kontrol ediliyor...")
                    retry_count += 1
                    time.sleep(random.uniform(5, 15))  # Rastgele bekleme süresi ekleyin
                else:
                    raise e

        if not success:
            logging.error(f"Max deneme sayısına ulaşıldı: {url}")

    except Exception as e:
        logging.error(f"Domain işleme hatası: {e}")

def check_and_update():
    if not is_tesseract_installed():
        logging.error("Tesseract-ocr sisteminizde yüklü değil! Lütfen yükleyin.")
        return

    try:
        db = connect_db()

        with db.cursor() as cursor:
            cursor.execute('SELECT * FROM url')
            domains = cursor.fetchall()

            # Her domain sorgusunu sırayla çalıştır
            for domain in domains:
                handle_domain(domain, db)

    except Exception as e:
        logging.error(f"Veritabanı hatası: {e}")
    finally:
        if db:
            db.close()

while True:
    try:
        check_and_update()
    except Exception as e:
        logging.error(f"Döngüde bir hata oluştu: {e}")
    time.sleep(600)  # 10 dakika bekleme (600 saniye)
