"""FastAPI dependencies for service injection."""

from functools import lru_cache
import sys
from pathlib import Path

# Add src to path - must be done before any imports
src_path = Path(__file__).parent.parent.parent / "src"
if str(src_path) not in sys.path:
    sys.path.insert(0, str(src_path))

# Import database and redis immediately
from core.database import get_database as _get_database
from src.core.redis import get_redis_client as _get_redis_client

# Lazy imports for other services (only import when needed to avoid import errors)
# These will be imported on-demand in their respective getter functions


@lru_cache()
def get_database():
    """Get database instance."""
    return _get_database()


async def get_db_session():
    """Get database session."""
    db = get_database()
    async with db.get_session() as session:
        yield session


@lru_cache()
def get_trading_engine():
    """Get trading engine instance."""
    from trading.engine import get_trading_engine as _get_trading_engine
    return _get_trading_engine()


@lru_cache()
def get_portfolio_tracker():
    """Get portfolio tracker instance."""
    from portfolio.tracker import get_portfolio_tracker as _get_portfolio_tracker
    return _get_portfolio_tracker()


@lru_cache()
def get_strategy_registry():
    """Get strategy registry instance."""
    from strategies.base import get_strategy_registry as _get_strategy_registry
    return _get_strategy_registry()


@lru_cache()
def get_backtesting_engine():
    """Get backtesting engine instance."""
    from backtesting.engine import get_backtest_engine as _get_backtesting_engine
    return _get_backtesting_engine()


def get_exchange_factory():
    """Get exchange factory."""
    from exchanges.factory import ExchangeFactory
    return ExchangeFactory


@lru_cache()
def get_redis_client():
    """Get Redis client instance."""
    return _get_redis_client()
