"""Tests for the LLM recommendation field on sentiment."""

from __future__ import annotations

import pytest

from app.models.ticker import Ticker
from app.providers.openai_sentiment import parse_recommendation
from app.services import sentiment_service as svc
from tests.conftest import _test_session_factory  # type: ignore


@pytest.fixture
async def session():
    async with _test_session_factory() as s:
        yield s


def test_parse_recommendation_valid_and_invalid():
    assert parse_recommendation("buy") == "buy"
    assert parse_recommendation("HOLD") == "hold"
    assert parse_recommendation(" Avoid ") == "avoid"
    assert parse_recommendation("strong buy") is None
    assert parse_recommendation(None) is None
    assert parse_recommendation("") is None


async def test_store_persists_recommendation(session):
    session.add(Ticker(symbol="AAA"))
    await session.commit()

    rec = await svc.store_sentiment(
        session,
        symbol="AAA",
        classification="bullish",
        confidence=70,
        source="gemini",
        reasoning="Analysts upgraded; strong retail buzz.",
        citations=[{"url": "http://x", "title": "X"}],
        recommendation="buy",
    )
    assert rec.recommendation == "buy"

    rows = await svc.get_sentiment_scores(session, "AAA", lookback_hours=168)
    assert rows[0].recommendation == "buy"
    assert rows[0].reasoning.startswith("Analysts")
