import logging
from typing import Dict, Any, List, Optional
from core.config import get_default_cash_account_name
from core.db import DataManager, SettingsManager
from core.auth import AuthRepository
from modules.crm import PersonManager, DebtManager, CustomerHistoryManager
from modules.stock import (
    ProductDefinitionManager, StockManager, DepotManager,
    StockMovementManager, BarcodeHistoryManager, CategoryManager
)
from modules.cash import (
    CashAccountManager, CardAccountManager, CurrencyManager,
    FinancialTransactionManager, ScheduledTransactionManager
)
from modules.repair import RepairManager
from modules.sales import SaleManager, TransactionService
from modules.services import ServiceManager
from modules.tax import (
    TaxApplicationManager,
    TaxDefinitionManager,
    TaxEngine,
    TaxProfileManager,      # <-- AKTİF EDİLDİ
    TaxProfileItemManager   # <-- Gerekirse diye aktif edildi
)
from modules.utils import CalendarManager

logger = logging.getLogger(__name__)

class ServiceContainer:
    """
    Tüm servis ve yöneticileri (Managers) barındıran merkezi konteyner.
    Dependency Injection (DI) için kullanılır.
    """
    def __init__(
        self,
        profile_file_path: str,
        data_manager: Optional[DataManager] = None,
        settings_manager: Optional[SettingsManager] = None,
        currency_manager: Optional[CurrencyManager] = None,
    ):
        self.profile_path = profile_file_path
        self.data_manager = data_manager or DataManager(profile_file_path=profile_file_path)
        self.db = self.data_manager.db
        self.settings_manager = settings_manager or SettingsManager(data_manager=self.data_manager)
        self.currency_manager = currency_manager or CurrencyManager()
        self.profile_id = self.data_manager.profile_id
        
        self.auth_repo = AuthRepository(self.db, self.profile_id)
        
        self.depot_manager = DepotManager(self.data_manager)
        self.category_manager = CategoryManager(self.data_manager)
        self.person_manager = PersonManager(self.data_manager)
        self.calendar_manager = CalendarManager(self.data_manager)
        self.service_manager = ServiceManager(self.data_manager)
        
        self.product_manager = ProductDefinitionManager(self.data_manager, "Product")
        self.stock_manager = StockManager(self.data_manager, "Product")
        
        self.ziynet_manager = ProductDefinitionManager(self.data_manager, "Ziynet")
        self.ziynet_stock_manager = StockManager(self.data_manager, "Ziynet")
        
        self.scrap_manager = ProductDefinitionManager(self.data_manager, "Scrap")
        self.scrap_stock_manager = StockManager(self.data_manager, "Scrap")
        
        self.stock_movement_manager = StockMovementManager(self.data_manager)
        self.barcode_history_manager = BarcodeHistoryManager(self.data_manager)
        
        self.cash_account_manager = CashAccountManager(self.data_manager)
        self.card_account_manager = CardAccountManager(self.data_manager)
        self.scheduled_transaction_manager = ScheduledTransactionManager(self.data_manager)
        
        self.cash_managers = {}
        self.card_managers = {}
        self._init_financial_managers()
        
        self.debt_manager = DebtManager(self.data_manager)
        self.sale_manager = SaleManager(self.data_manager)
        self.repair_manager = RepairManager(self.data_manager)
        self.customer_history_manager = CustomerHistoryManager(self.data_manager)
        
        # --- VERGİ SİSTEMİ ---
        self.tax_definition_manager = TaxDefinitionManager(self.data_manager)
        self.tax_profile_manager = TaxProfileManager(self.data_manager)          # <-- EKLENDİ
        self.tax_profile_item_manager = TaxProfileItemManager(self.data_manager) # <-- EKLENDİ
        self.tax_application_manager = TaxApplicationManager(self.data_manager)
        self.tax_engine = TaxEngine(self.data_manager)
        
        self.transaction_service = self._create_transaction_service()
        
        logger.info("ServiceContainer başarıyla başlatıldı.")

    def _init_financial_managers(self):
        """Finansal hesaplar için transaction manager'ları oluşturur."""
        if not self.cash_account_manager.get_all():
            from core.db import CashAccount
            self.cash_account_manager.add_item(
                CashAccount(name=get_default_cash_account_name())
            )
            
        for acc in self.cash_account_manager.get_all():
            key = f"cash_transactions_{acc.id}"
            self.cash_managers[acc.id] = FinancialTransactionManager(self.data_manager, key)
            
        for acc in self.card_account_manager.get_all():
            key = f"card_transactions_{acc.id}"
            self.card_managers[acc.id] = FinancialTransactionManager(self.data_manager, key)

    def _create_transaction_service(self):
        """TransactionService'i gerekli bağımlılıklarla oluşturur."""
        managers_dict = {
            'stock_manager': self.stock_manager,
            'product_manager': self.product_manager,
            'ziynet_stock_manager': self.ziynet_stock_manager,
            'ziynet_manager': self.ziynet_manager,
            'scrap_stock_manager': self.scrap_stock_manager,
            'scrap_manager': self.scrap_manager,
            'customer_history_manager': self.customer_history_manager,
            'cash_managers': self.cash_managers,
            'card_managers': self.card_managers,
            'barcode_history_manager': self.barcode_history_manager,
            'stock_movement_manager': self.stock_movement_manager,
            'sale_manager': self.sale_manager,
            'tax_application_manager': self.tax_application_manager,
        }
        return TransactionService(self.data_manager, managers_dict, self.currency_manager, current_user=None)

    def refresh_financial_managers(self):
        """Yeni hesap eklendiğinde manager listesini tazeler."""
        self.cash_managers.clear()
        self.card_managers.clear()
        self._init_financial_managers()
        self.transaction_service.managers['cash_managers'] = self.cash_managers
        self.transaction_service.managers['card_managers'] = self.card_managers

    def get_gold_stock(self):
        return self.stock_manager.get_all()

    def get_scrap_stock(self):
        return self.scrap_stock_manager.get_all()

    def get_jewelry_stock(self):
        return self.ziynet_stock_manager.get_all()




