"""Abstract base class for all brokers"""

from abc import ABC, abstractmethod
from typing import Dict, List, Any, Optional

class BaseBroker(ABC):
    """Abstract base class for all broker implementations"""
    
    def __init__(self, credentials: Dict, client_code: str):
        self.credentials = credentials
        self.client_code = client_code
        self.client_id = self._get_client_id(credentials)
        self.is_logged_in = False
        self.dynamic_profit_enabled = False
    
    def _get_client_id(self, credentials: Dict) -> str:
        """Extract client ID from credentials"""
        return credentials.get('user_id') or credentials.get('api_key', self.client_code)
    
    @abstractmethod
    def login(self) -> bool:
        """Login to broker platform"""
        pass
    
    @abstractmethod
    def place_order(self, symbol: str, action: str, quantity: int, exchange: str, 
                   expiry: str, remarks: str) -> Optional[str]:
        """Place a regular order"""
        pass
    
    @abstractmethod
    def place_profit_order(self, trading_symbol: str, quantity: int, exchange: str, 
                          transaction_type: str, remarks: str) -> Optional[str]:
        """Place profit booking order"""
        pass
    
    @abstractmethod
    def get_positions(self) -> List[Dict]:
        """Get current positions"""
        pass
    
    @abstractmethod
    def get_orders(self) -> List[Dict]:
        """Get order book"""
        pass
    
    @abstractmethod
    def get_quote(self, exchange: str, trading_symbol: str) -> Dict:
        """Get current market price"""
        pass
    
    @abstractmethod
    def close_all_positions(self, max_profit_target: int, max_loss_limit: int, 
                           dynamic_profit_enabled: bool) -> bool:
        """Close all open positions based on limits"""
        pass
    
    @abstractmethod
    def get_realized_pnl(self) -> float:
        """Get total realized profit/loss"""
        pass
    
    def split_order_quantity(self, quantity: int, max_qty: int) -> List[int]:
        """Split large order into smaller chunks"""
        chunks = []
        while quantity > max_qty:
            chunks.append(max_qty)
            quantity -= max_qty
        if quantity > 0:
            chunks.append(quantity)
        return chunks