"""Integration tests for UI trading workflow."""

import pytest
from decimal import Decimal
from PyQt6.QtWidgets import QApplication
from unittest.mock import Mock, patch
from src.ui.widgets.trading_view import TradingView
from src.core.database import Order, OrderStatus, OrderSide, OrderType


@pytest.fixture
def app():
    """Create QApplication for tests."""
    if not QApplication.instance():
        return QApplication([])
    return QApplication.instance()


@pytest.fixture
def trading_view(app):
    """Create TradingView with mocked backend."""
    view = TradingView()
    
    # Mock trading engine
    mock_engine = Mock()
    mock_order = Mock(spec=Order)
    mock_order.id = 1
    mock_engine.execute_order.return_value = mock_order
    view.trading_engine = mock_engine
    
    return view


def test_order_placement_workflow(trading_view):
    """Test complete order placement workflow."""
    # Set up form
    trading_view.current_exchange_id = 1
    trading_view.current_symbol = "BTC/USD"
    trading_view.order_type_combo.setCurrentText("Market")
    trading_view.side_combo.setCurrentText("Buy")
    trading_view.quantity_input.setValue(0.1)
    
    # Place order
    trading_view._place_order()
    
    # Verify engine was called
    trading_view.trading_engine.execute_order.assert_called_once()
    call_args = trading_view.trading_engine.execute_order.call_args
    assert call_args[1]['symbol'] == "BTC/USD"
    assert call_args[1]['side'] == OrderSide.BUY


def test_position_table_update(trading_view):
    """Test positions table updates with portfolio data."""
    # Mock portfolio data
    mock_portfolio = {
        'positions': [
            {
                'symbol': 'BTC/USD',
                'quantity': 0.1,
                'entry_price': 50000,
                'current_price': 51000,
                'unrealized_pnl': 100
            }
        ],
        'performance': {
            'current_value': 5100,
            'unrealized_pnl': 100,
            'realized_pnl': 0
        }
    }
    
    trading_view.portfolio_tracker.get_current_portfolio = Mock(return_value=mock_portfolio)
    trading_view._update_positions()
    
    assert trading_view.positions_table.rowCount() == 1
    assert trading_view.positions_table.item(0, 0).text() == "BTC/USD"
