from kotak_dashboard.backend import DataManager


def test_fetch_portfolio_calls_client(mock_client):
    """Ensure fetch_portfolio calls the correct client methods."""
    manager = DataManager(mock_client)
    manager.fetch_portfolio()

    mock_client.holdings.assert_called_once()
    mock_client.positions.assert_called_once()


def test_hydrate_live_prices_ohlc_fallback(mock_client, sample_holdings_json):
    """
    Critical Test: Verify that if 'change' is 0, we calculate it from OHLC 'close'.
    """
    manager = DataManager(mock_client)

    # Mock the Quotes API response
    # Scenario: LTP is 2200, but 'change' is 0. Previous Close (ohlc.close) is 2000.
    # Expected Change: +200
    mock_quotes_response = {
        "data": [
            {
                "instrument_token": "111",
                "ltp": "2200.0",
                "change": "0",  # API returning 0
                "per_change": "0",
                "display_symbol": "RELIANCE",
                "ohlc": {"close": "2000.0"},  # Previous close
            }
        ]
    }
    mock_client.quotes.return_value = mock_quotes_response

    # Run hydration
    updated_data, count = manager.hydrate_live_prices(sample_holdings_json)

    # Assertions
    assert count == 1
    item = updated_data["data"][0]
    assert item["currentPrice"] == 2200.0
    assert item["dayChange"] == 200.0  # (2200 - 2000)
    assert item["dayChangePct"] == 10.0  # (200 / 2000 * 100)


def test_hydrate_skips_mismatch(mock_client, sample_holdings_json):
    """Test safety check: Should skip if symbols are completely different."""
    manager = DataManager(mock_client)

    # Scenario: Token 111 returns data for 'ADANI' instead of 'RELIANCE'
    mock_quotes_response = {
        "data": [
            {
                "instrument_token": "111",
                "ltp": "100.0",
                "display_symbol": "ADANI-ENT",  # Mismatch
                "change": "5",
            }
        ]
    }
    mock_client.quotes.return_value = mock_quotes_response

    updated_data, count = manager.hydrate_live_prices(sample_holdings_json)

    # Should NOT update because RELIANCE != ADANI
    assert count == 0
    # FIX: Assert that the value remained 0 (not updated to 100)
    assert updated_data["data"][0]["currentPrice"] == 0
