from __future__ import annotations

from crypto_spot_bot.llm_advisor import LlmAdvisor, _extract_json
from crypto_spot_bot.storage import Storage


def test_extract_json_from_fenced_response() -> None:
    data = _extract_json(
        """
        ```json
        {"market_regime":"range","risk_level":"low","confidence_adjustment":0.02}
        ```
        """
    )

    assert data["market_regime"] == "range"
    assert data["confidence_adjustment"] == 0.02


def test_llm_advisor_parse_clamps_adjustment(make_settings, tmp_path) -> None:
    settings = make_settings(tmp_path, llm_advisor_max_adjustment=0.05)
    advisor = LlmAdvisor(settings, Storage(settings.database_path))

    advice = advisor._parse(
        "BTCUSDT",
        '{"market_regime":"breakout","risk_level":"high","confidence_adjustment":0.5,'
        '"block_entry":true,"grid_suitable":false,"reason_ru":"тест"}',
    )

    assert advice.model == "gemma4:e4b"
    assert advice.market_regime == "breakout"
    assert advice.risk_level == "high"
    assert advice.confidence_adjustment == 0.05
    assert advice.block_entry is True


def test_storage_records_llm_advice(make_settings, tmp_path) -> None:
    settings = make_settings(tmp_path)
    storage = Storage(settings.database_path)

    storage.insert_llm_advice(
        symbol="BTCUSDT",
        model="gemma4:e4b",
        prompt_json={"symbol": "BTCUSDT"},
        response_text='{"confidence_adjustment":0}',
        advice_json={"confidence_adjustment": 0.0, "reason_ru": "нейтрально"},
    )

    items = storage.recent_llm_advice(limit=1)
    assert items[0]["model"] == "gemma4:e4b"
    assert items[0]["prompt"]["symbol"] == "BTCUSDT"
    assert items[0]["advice"]["reason_ru"] == "нейтрально"
