"""Execution Mode Router & Dispatcher."""
from __future__ import annotations

from typing import Optional

from backend.app.config.settings import TradingMode, settings
from backend.app.execution.bybit_demo import bybit_demo_adapter
from backend.app.execution.paper import paper_engine
from backend.app.execution.state_machine import OrderStateMachine
from backend.app.schemas.order import OrderIntent, OrderResult, OrderStatus


class ExecutionRouter:
    """Dispatches orders to the appropriate execution adapter according to system trading mode."""

    def __init__(self, mode: Optional[TradingMode] = None) -> None:
        self.mode = mode or settings.TRADING_MODE
        self.paper_engine = paper_engine
        self.demo_adapter = bybit_demo_adapter

    def submit_order(self, intent: OrderIntent) -> OrderResult:
        current_mode = settings.TRADING_MODE

        if current_mode == TradingMode.BACKTEST:
            return OrderResult(
                client_order_id=intent.client_order_id,
                exchange_order_id=None,
                status=OrderStatus.REJECTED,
                message="Cannot submit live router orders in BACKTEST mode. Use BacktestEngine.",
            )
        elif current_mode == TradingMode.PAPER:
            return self.paper_engine.execute_order(intent)
        elif current_mode == TradingMode.BYBIT_DEMO:
            return self.demo_adapter.execute_order(intent)
        elif current_mode == TradingMode.LIVE:
            from backend.app.execution.bybit_live import bybit_live_adapter
            if not bybit_live_adapter:
                return OrderResult(
                    client_order_id=intent.client_order_id,
                    exchange_order_id=None,
                    status=OrderStatus.REJECTED,
                    message="Live execution adapter not initialized or authorization missing.",
                )
            return bybit_live_adapter.execute_order(intent)
        else:
            return OrderResult(
                client_order_id=intent.client_order_id,
                exchange_order_id=None,
                status=OrderStatus.REJECTED,
                message=f"Unsupported trading mode: {current_mode}",
            )


execution_router = ExecutionRouter()
