import pandas as pd
from kotak_dashboard.backend import AnalyticsEngine


def test_process_holdings_calculations(sample_holdings_json):
    """Test if P&L, Current Value, and Invested Amount are calculated correctly."""
    # Process
    df = AnalyticsEngine.process_holdings(sample_holdings_json)

    # Assertions for RELIANCE (Index 0)
    # Invested: 10 * 2000 = 20000
    # Current Value (defaults to 0 if not hydrated, but let's check basic structure)

    assert "investedAmount" in df.columns
    assert "dayPnL" in df.columns
    assert df.loc[0, "investedAmount"] == 20000.0
    assert df.loc[1, "investedAmount"] == 15000.0


def test_process_holdings_with_live_data():
    """Test calculations when live data (dayChange) is present."""
    input_data = {
        "data": [
            {
                "tradingSymbol": "TEST",
                "quantity": 10,
                "averagePrice": 100,
                "currentPrice": 110,
                "dayChange": 5.0,
            }
        ]
    }

    df = AnalyticsEngine.process_holdings(input_data)

    # Day P&L = Quantity * DayChange = 10 * 5 = 50
    assert df.loc[0, "dayPnL"] == 50.0
    # Total P&L = (110*10) - (100*10) = 1100 - 1000 = 100
    assert df.loc[0, "profitAndLoss"] == 100.0


def test_get_sector_data(sample_holdings_json):
    """Test sector aggregation."""
    # Mock pre-calculated current value for the test
    df = pd.DataFrame(sample_holdings_json["data"])
    df["currentValue"] = [25000, 16000]  # Reliance, TCS

    sector_df = AnalyticsEngine.get_sector_data(df)

    assert len(sector_df) == 2
    assert "sector" in sector_df.columns
    assert (
        sector_df.loc[sector_df["sector"] == "Oil & Gas", "currentValue"].values[0]
        == 25000
    )
