import time
import threading
import mysql.connector
from datetime import datetime
import logging
from authorization import G2GAutomation

# Logging ayarları
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('auth_updater.log'),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)

class AutoAuthUpdater:
    def __init__(self):
        self.g2g = None
        self.running = False
        self.update_interval = 45  # 45 saniye
        self.db_config = {
            'host': 'localhost',
            'user': 'root',
            'password': '',
            'database': 'squanch'
        }
        
    def connect_database(self):
        """Veritabanına bağlan"""
        try:
            conn = mysql.connector.connect(**self.db_config)
            logger.info("Veritabanı bağlantısı başarılı")
            return conn
        except mysql.connector.Error as e:
            logger.error(f"Veritabanı bağlantı hatası: {e}")
            return None
    
    def update_authorization_key(self, auth_key):
        """Authorization key'i veritabanında güncelle"""
        conn = self.connect_database()
        if not conn:
            return False
            
        try:
            cursor = conn.cursor()
            
            # Önce mevcut kaydı kontrol et
            check_sql = "SELECT id FROM ayar WHERE id = 1"
            cursor.execute(check_sql)
            result = cursor.fetchone()
            
            if not result:
                logger.error("Ayar tablosunda id=1 kaydı bulunamadı")
                return False
            
            # Güncelleme yap
            sql = "UPDATE ayar SET authorization_key = %s WHERE id = 1"
            cursor.execute(sql, (auth_key,))
            conn.commit()
            
            if cursor.rowcount > 0:
                logger.info(f"Authorization key başarıyla güncellendi: {auth_key[:50]}...")
                return True
            else:
                logger.warning("Hiçbir kayıt güncellenmedi - aynı değer olabilir")
                # Aynı değer olup olmadığını kontrol et
                check_current_sql = "SELECT authorization_key FROM ayar WHERE id = 1"
                cursor.execute(check_current_sql)
                current_key = cursor.fetchone()
                if current_key and current_key[0] == auth_key:
                    logger.info("Authorization key zaten güncel")
                    return True
                else:
                    logger.error("Güncelleme başarısız")
                    return False
                
        except mysql.connector.Error as e:
            logger.error(f"Veritabanı güncelleme hatası: {e}")
            return False
        finally:
            cursor.close()
            conn.close()
    
    def get_current_authorization_key(self):
        """Mevcut authorization key'i veritabanından al"""
        conn = self.connect_database()
        if not conn:
            return None
            
        try:
            cursor = conn.cursor()
            sql = "SELECT authorization_key FROM ayar WHERE id = 1"
            cursor.execute(sql)
            result = cursor.fetchone()
            
            if result:
                return result[0]
            else:
                logger.warning("Authorization key bulunamadı")
                return None
                
        except mysql.connector.Error as e:
            logger.error(f"Veritabanı okuma hatası: {e}")
            return None
        finally:
            cursor.close()
            conn.close()
    
    def start_g2g_session(self):
        """G2G oturumunu başlat"""
        try:
            # Eğer zaten çalışan bir oturum varsa, onu kullan
            if self.g2g and self.g2g.driver:
                logger.info("Mevcut G2G oturumu kullanılıyor")
                return True
            
            # Yeni oturum oluştur
            if not self.g2g:
                self.g2g = G2GAutomation()
            
            if self.g2g.start_session():
                logger.info("G2G oturum başarıyla başlatıldı")
                return True
            else:
                logger.error("G2G oturum başlatılamadı")
                return False
                
        except Exception as e:
            logger.error(f"G2G oturum başlatma hatası: {e}")
            return False
    
    def get_authorization_code(self):
        """Authorization kodunu al"""
        try:
            if not self.g2g:
                logger.error("G2G oturumu başlatılmamış")
                return None
            
            auth_code = self.g2g.get_authorization_code()
            if auth_code:
                logger.info(f"Authorization kodu alındı: {auth_code[:50]}...")
                return auth_code
            else:
                logger.error("Authorization kodu alınamadı")
                return None
                
        except Exception as e:
            logger.error(f"Authorization kodu alma hatası: {e}")
            return None
    
    def update_cycle(self):
        """Tek güncelleme döngüsü"""
        try:
            logger.info("Authorization kodu güncelleme döngüsü başlatılıyor...")
            
            # G2G oturumunu kontrol et - sadece gerekirse yeniden başlat
            if not self.g2g or not self.g2g.driver:
                logger.info("G2G oturumu başlatılıyor...")
                if not self.start_g2g_session():
                    logger.error("G2G oturumu başlatılamadı, döngü atlanıyor")
                    return False
            
            # Giriş durumunu kontrol et
            if not self.g2g.check_login_status():
                logger.warning("Giriş yapılmamış, sayfa yenileniyor...")
                # Oturumu yeniden başlatmak yerine sayfayı yenile
                try:
                    self.g2g.driver.get("https://www.g2g.com")
                    time.sleep(3)
                    if not self.g2g.check_login_status():
                        logger.error("Giriş yapılmamış, manuel giriş gerekli")
                        return False
                except Exception as e:
                    logger.error(f"Sayfa yenileme hatası: {e}")
                    return False
            
            # Authorization kodunu al
            auth_code = self.get_authorization_code()
            if not auth_code:
                logger.error("Authorization kodu alınamadı, döngü atlanıyor")
                return False
            
            # Veritabanında güncelle
            if self.update_authorization_key(auth_code):
                logger.info("✅ Authorization kodu başarıyla güncellendi")
                return True
            else:
                logger.error("❌ Authorization kodu güncellenemedi")
                return False
                
        except Exception as e:
            logger.error(f"Güncelleme döngüsü hatası: {e}")
            return False
    
    def run_continuous_updates(self):
        """Sürekli güncelleme döngüsü"""
        logger.info("🚀 Otomatik authorization güncelleme sistemi başlatılıyor...")
        logger.info(f"⏰ Güncelleme aralığı: {self.update_interval} saniye")
        
        self.running = True
        cycle_count = 0
        consecutive_failures = 0
        max_failures = 3
        
        while self.running:
            try:
                cycle_count += 1
                logger.info(f"🔄 Güncelleme döngüsü #{cycle_count} başlatılıyor...")
                
                success = self.update_cycle()
                
                if success:
                    logger.info(f"✅ Döngü #{cycle_count} başarıyla tamamlandı")
                    consecutive_failures = 0  # Başarılı döngü, hata sayacını sıfırla
                else:
                    consecutive_failures += 1
                    logger.warning(f"⚠️ Döngü #{cycle_count} başarısız (Ardışık hata: {consecutive_failures})")
                    
                    # Çok fazla ardışık hata varsa WebDriver'ı yeniden başlat
                    if consecutive_failures >= max_failures:
                        logger.warning(f"🔄 {max_failures} ardışık hata, WebDriver yeniden başlatılıyor...")
                        try:
                            if self.g2g:
                                self.g2g.close_session()
                                self.g2g = None
                            consecutive_failures = 0
                        except Exception as e:
                            logger.error(f"WebDriver kapatma hatası: {e}")
                
                # Bir sonraki döngüye kadar bekle
                logger.info(f"⏳ {self.update_interval} saniye bekleniyor...")
                for i in range(self.update_interval):
                    if not self.running:
                        break
                    time.sleep(1)
                    
            except KeyboardInterrupt:
                logger.info("🛑 Kullanıcı tarafından durduruldu")
                break
            except Exception as e:
                logger.error(f"❌ Beklenmeyen hata: {e}")
                consecutive_failures += 1
                logger.info("⏳ 10 saniye bekleniyor ve tekrar deneniyor...")
                time.sleep(10)
        
        logger.info("🛑 Otomatik güncelleme sistemi durduruldu")
        self.stop()
    
    def stop(self):
        """Sistemi durdur"""
        logger.info("🛑 Sistem durduruluyor...")
        self.running = False
        
        if self.g2g:
            try:
                self.g2g.close_session()
                logger.info("G2G oturumu kapatıldı")
            except Exception as e:
                logger.error(f"G2G oturumu kapatma hatası: {e}")
    
    def get_status(self):
        """Sistem durumunu al"""
        status = {
            'running': self.running,
            'g2g_connected': self.g2g is not None and self.g2g.driver is not None,
            'update_interval': self.update_interval,
            'current_auth_key': self.get_current_authorization_key()
        }
        return status

def main():
    """Ana fonksiyon"""
    updater = AutoAuthUpdater()
    
    try:
        print("🔐 G2G.com Otomatik Authorization Güncelleme Sistemi")
        print("=" * 60)
        print("📋 Özellikler:")
        print("   • 45 saniyede bir otomatik güncelleme")
        print("   • WebDriver sürekli açık kalır")
        print("   • Otomatik hata yönetimi")
        print("   • Veritabanı güncelleme logları")
        print("=" * 60)
        print("🚀 Sistem başlatılıyor...")
        print("❌ Durdurmak için Ctrl+C tuşlayın")
        print("=" * 60)
        
        # İlk G2G oturumunu başlat
        if not updater.start_g2g_session():
            print("❌ G2G oturumu başlatılamadı!")
            return
        
        print("✅ G2G oturumu başarıyla başlatıldı")
        print("🔄 Otomatik güncelleme döngüsü başlatılıyor...")
        
        # Sürekli güncelleme döngüsünü başlat
        updater.run_continuous_updates()
        
    except KeyboardInterrupt:
        print("\n🛑 Sistem kullanıcı tarafından durduruldu")
    except Exception as e:
        print(f"❌ Beklenmeyen hata: {e}")
    finally:
        updater.stop()
        print("👋 Sistem tamamen kapatıldı")

if __name__ == "__main__":
    main()
