from __future__ import annotations
import platform
from typing import Optional
from core.config import logger
from core.db_adapters import BaseDBAdapter, MariaDBAdapter, MySQLAdapter
from core.homebrew_mysql import detect_homebrew_mysql
from core.runtime_platform import detect_macos_architecture, detect_runtime_platform
from core.tenant_manager import TenantManager

# Global Singleton Adapter Instances
_ADAPTER_SINGLETON: Optional[BaseDBAdapter] = None

def get_database_adapter() -> BaseDBAdapter:
    """
    [AI_DOC]
    Fabrika Deseni (Factory Pattern). 
    Isletim sistemini algilar, gerekli yapilandirmayi config/database.py uzerinden ceker
    ve uygun DB Adapter sinifini Singleton olarak dondurur.
    Golder, "Local-First" (Once Yerel DB) mantigiyla calistigi icin hep yerel adapter'i secer.
    [/AI_DOC]
    """
    global _ADAPTER_SINGLETON
    
    if _ADAPTER_SINGLETON is not None:
        return _ADAPTER_SINGLETON

    # Lisans kontrolu
    tenant_manager = TenantManager()
    if not tenant_manager.is_license_valid():
        raise RuntimeError("Lisans gecerli degil. Veritabani baslatilmadan once tenant girisi tamamlanmalidir.")

    plan_type = str(tenant_manager.get_plan_type() or "").strip()
    if plan_type not in tenant_manager.PLAN_FEATURES:
        raise RuntimeError(f"Lisans dosyasinda bilinmeyen plan tipi: {plan_type}")

    logger.info(f"[DB_FACTORY] Lisans Plan Bilgisi: {plan_type}. Local-First kurallari uygulaniyor.")

    runtime = detect_runtime_platform()
    
    # ---------------- WINDOWS ORTAMI ---------------- #
    if runtime == "windows":
        logger.info("[DB_FACTORY] Platform: Windows - Gomulu MariaDB Adapter seciliyor.")
        _ADAPTER_SINGLETON = MariaDBAdapter(db_name="Goldr")
        return _ADAPTER_SINGLETON
        
    # ---------------- MACOS ORTAMI ---------------- #
    elif runtime == "macos":
        machine = platform.machine()
        logger.info(f"[DB_FACTORY] Platform: macOS - Mimari: {machine}")
        
        info = detect_homebrew_mysql()
        if not info.available:
            raise RuntimeError(
                "Homebrew MySQL bu cihazda algilanamadi.\n"
                "Lutfen terminal uzerinden kurun ve baslatin:\n"
                "  brew install mysql\n"
                "  brew services start mysql\n"
                "Ardindan uygulamayi yeniden baslatin."
            )
            
        logger.info(f"[DB_FACTORY] Brew MySQL Soket Tespit Edildi: {info.detected_path_for_log()}")
        
        # Yeni birlestirilmis config sistemini kullaniyoruz
        from config.database import get_unified_db_config
        cfg = get_unified_db_config(socket_path=info.socket_path)
        
        _ADAPTER_SINGLETON = MySQLAdapter(db_config=cfg, db_name="Goldr")
        return _ADAPTER_SINGLETON

    else:
        raise RuntimeError(f"Desteklenmeyen platform: {runtime}")


def _reset_database_adapter_for_tests() -> None:
    """Testler ve cikis islemleri icin Singleton nesnesini sifirlar."""
    global _ADAPTER_SINGLETON
    _ADAPTER_SINGLETON = None




