"""
IBKR Mapping Utilities
======================
Maps IBKR types and values to CPZ SDK models.
"""

from __future__ import annotations

from typing import Optional
from ..enums import OrderSide, OrderType, TimeInForce


def map_order_status(status: str) -> str:
    """
    Map IBKR order status to CPZ SDK status.
    
    IBKR statuses:
    - Submitted, PreSubmitted, PendingSubmit -> pending
    - Filled -> filled
    - Cancelled, Inactive -> canceled
    - ApiCancelled -> canceled
    - PendingCancel -> pending
    - PartiallyFilled -> partially_filled
    
    Args:
        status: IBKR order status string
        
    Returns:
        Normalized status string
    """
    status_lower = status.lower().replace(' ', '_')
    
    status_map = {
        'submitted': 'pending',
        'presubmitted': 'pending',
        'pendingsubmit': 'pending',
        'pending_submit': 'pending',
        'pendingcancel': 'pending',
        'pending_cancel': 'pending',
        'filled': 'filled',
        'cancelled': 'canceled',
        'canceled': 'canceled',
        'inactive': 'canceled',
        'apicancelled': 'canceled',
        'api_cancelled': 'canceled',
        'partiallyfilled': 'partially_filled',
        'partially_filled': 'partially_filled',
        'accepted': 'accepted',
        'pending': 'pending',
        'rejected': 'rejected',
        'error': 'rejected',
    }
    
    return status_map.get(status_lower, 'pending')


def map_order_side(side: str) -> OrderSide:
    """
    Map IBKR order side to CPZ SDK OrderSide.
    
    Args:
        side: IBKR side string ('BUY', 'SELL')
        
    Returns:
        OrderSide enum value
    """
    if side.upper() in ('BUY', 'BOT', 'B'):
        return OrderSide.BUY
    elif side.upper() in ('SELL', 'SLD', 'S'):
        return OrderSide.SELL
    else:
        return OrderSide.BUY


def map_order_type(order_type: str) -> OrderType:
    """
    Map IBKR order type to CPZ SDK OrderType.
    
    Args:
        order_type: IBKR order type string
        
    Returns:
        OrderType enum value
    """
    order_type_upper = order_type.upper()
    
    if order_type_upper in ('MKT', 'MARKET'):
        return OrderType.MARKET
    elif order_type_upper in ('LMT', 'LIMIT'):
        return OrderType.LIMIT
    elif order_type_upper in ('STP', 'STOP'):
        return OrderType.STOP
    elif order_type_upper in ('STPLMT', 'STOP_LIMIT', 'STOPLIMIT'):
        return OrderType.STOP_LIMIT
    else:
        return OrderType.MARKET


def map_time_in_force(tif: str) -> TimeInForce:
    """
    Map IBKR time in force to CPZ SDK TimeInForce.
    
    Args:
        tif: IBKR TIF string
        
    Returns:
        TimeInForce enum value
    """
    tif_upper = tif.upper()
    
    if tif_upper == 'DAY':
        return TimeInForce.DAY
    elif tif_upper in ('GTC', 'GTD'):
        return TimeInForce.GTC
    elif tif_upper == 'IOC':
        return TimeInForce.IOC
    elif tif_upper == 'FOK':
        return TimeInForce.FOK
    else:
        return TimeInForce.DAY


def to_ibkr_side(side: OrderSide) -> str:
    """Convert CPZ SDK OrderSide to IBKR side string."""
    return side.value.upper()


def to_ibkr_order_type(order_type: OrderType) -> str:
    """Convert CPZ SDK OrderType to IBKR order type string."""
    type_map = {
        OrderType.MARKET: 'MARKET',
        OrderType.LIMIT: 'LIMIT',
        OrderType.STOP: 'STOP',
        OrderType.STOP_LIMIT: 'STOP_LIMIT',
    }
    return type_map.get(order_type, 'MARKET')


def to_ibkr_tif(tif: TimeInForce) -> str:
    """Convert CPZ SDK TimeInForce to IBKR TIF string."""
    return tif.value.upper()
