"""
Veritabanı Kurulum Scripti
schema.sql dosyasını okuyup veritabanına uygular
"""

import mysql.connector
from mysql.connector import Error
import os
import logging

from config import DB_CONFIG

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)


def read_sql_file(file_path):
    """SQL dosyasını okuyup komutlara ayırır"""
    with open(file_path, 'r', encoding='utf-8') as file:
        content = file.read()
    
    # SQL komutlarını ayır
    # Yorumları ve boş satırları temizle
    statements = []
    current_statement = ""
    
    lines = content.split('\n')
    for line in lines:
        # Tek satır yorumları atla
        stripped = line.strip()
        if not stripped or stripped.startswith('--'):
            continue
        
        # Çok satırlı yorumları atla
        if stripped.startswith('/*') and stripped.endswith('*/'):
            continue
        
        current_statement += line + '\n'
        
        # ; ile bitiyorsa statement'ı ekle
        if stripped.endswith(';'):
            statement = current_statement.strip()
            if statement:
                # Son ; karakterini kaldır (bazı durumlarda gerekli olmayabilir)
                statements.append(statement)
            current_statement = ""
    
    # Son statement'ı ekle (eğer ; ile bitmiyorsa)
    if current_statement.strip():
        statements.append(current_statement.strip())
    
    return statements


def execute_sql_statements(connection, statements):
    """SQL komutlarını çalıştırır"""
    cursor = connection.cursor()
    success_count = 0
    error_count = 0
    
    for i, statement in enumerate(statements, 1):
        if not statement.strip() or statement.strip().startswith('--'):
            continue
        
        try:
            # Çoklu statement desteği (CREATE TABLE, INSERT gibi komutlar için)
            if ';' in statement:
                # Birden fazla statement varsa
                for result in cursor.execute(statement, multi=True):
                    if result.with_rows:
                        result.fetchall()
            else:
                # Tek statement
                cursor.execute(statement)
                if cursor.with_rows:
                    cursor.fetchall()
            
            connection.commit()
            success_count += 1
            if i % 10 == 0 or i == len(statements):
                logger.info(f"✓ İlerleme: {i}/{len(statements)} komut işlendi")
        except Error as e:
            error_count += 1
            error_msg = str(e)
            
            # Bazı hatalar normal olabilir (örn: tablo zaten var, duplicate key)
            if any(keyword in error_msg.lower() for keyword in ['already exists', 'duplicate', 'table', 'key']):
                logger.debug(f"⚠ Komut {i} atlandı (normal): {error_msg[:100]}")
                success_count += 1  # Normal hata olarak say
                error_count -= 1
            else:
                logger.error(f"✗ Komut {i} hatası: {error_msg}")
                logger.debug(f"Hatalı komut başlangıcı: {statement[:200]}...")
    
    cursor.close()
    return success_count, error_count


def setup_database():
    """Veritabanını kurar"""
    schema_file = os.path.join(os.path.dirname(__file__), 'database', 'schema.sql')
    
    if not os.path.exists(schema_file):
        logger.error(f"Schema dosyası bulunamadı: {schema_file}")
        return False
    
    logger.info("Veritabanı bağlantısı kuruluyor...")
    try:
        connection = mysql.connector.connect(
            host=DB_CONFIG['host'],
            database=DB_CONFIG['database'],
            user=DB_CONFIG['username'],
            password=DB_CONFIG['password'],
            port=DB_CONFIG['port'],
            charset=DB_CONFIG.get('charset', 'utf8mb4')
        )
        
        if connection.is_connected():
            logger.info("✓ Veritabanı bağlantısı başarılı!")
            
            # SQL dosyasını oku
            logger.info("SQL dosyası okunuyor...")
            statements = read_sql_file(schema_file)
            logger.info(f"✓ {len(statements)} SQL komutu bulundu")
            
            # Komutları çalıştır
            logger.info("SQL komutları çalıştırılıyor...")
            success, errors = execute_sql_statements(connection, statements)
            
            logger.info(f"\n{'='*50}")
            logger.info(f"Kurulum tamamlandı!")
            logger.info(f"Başarılı: {success}")
            logger.info(f"Hatalı: {errors}")
            logger.info(f"{'='*50}")
            
            return True
            
    except Error as e:
        logger.error(f"Veritabanı bağlantı hatası: {str(e)}")
        return False
    finally:
        if connection and connection.is_connected():
            connection.close()
            logger.info("Veritabanı bağlantısı kapatıldı")


def check_database_status():
    """Veritabanı durumunu kontrol eder"""
    try:
        connection = mysql.connector.connect(
            host=DB_CONFIG['host'],
            database=DB_CONFIG['database'],
            user=DB_CONFIG['username'],
            password=DB_CONFIG['password'],
            port=DB_CONFIG['port']
        )
        
        cursor = connection.cursor()
        
        # Tabloları kontrol et
        cursor.execute("SHOW TABLES")
        tables = cursor.fetchall()
        
        logger.info(f"\n{'='*50}")
        logger.info(f"Veritabanı: {DB_CONFIG['database']}")
        logger.info(f"Toplam Tablo: {len(tables)}")
        logger.info(f"{'='*50}")
        
        if tables:
            logger.info("\nTablolar:")
            for table in tables:
                # Satır sayısını al
                cursor.execute(f"SELECT COUNT(*) FROM {table[0]}")
                count = cursor.fetchone()[0]
                logger.info(f"  - {table[0]}: {count} kayıt")
        
        cursor.close()
        connection.close()
        
        return True
        
    except Error as e:
        logger.error(f"Durum kontrolü hatası: {str(e)}")
        return False


if __name__ == "__main__":
    import sys
    
    if len(sys.argv) > 1 and sys.argv[1] == 'status':
        # Sadece durum kontrolü
        check_database_status()
    else:
        # Kurulum
        print("="*50)
        print("IHARS Dernek Yönetim Sistemi - Veritabanı Kurulumu")
        print("="*50)
        print()
        
        response = input("Veritabanını kurmak istediğinize emin misiniz? (mevcut tablolar silinebilir) [y/N]: ")
        if response.lower() != 'y':
            print("Kurulum iptal edildi.")
            exit(0)
        
        if setup_database():
            print("\n✓ Veritabanı kurulumu tamamlandı!")
            print("\nDurum kontrolü yapılıyor...")
            check_database_status()
        else:
            print("\n✗ Veritabanı kurulumu başarısız!")
            exit(1)

