import pytest
from agents.models import AgentSession
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.utils import timezone
from scrobbles.models import Scrobble

User = get_user_model()


@pytest.fixture
def user():
    return User.objects.create_user(username="agenttest", password="testpass123")


@pytest.fixture
def agent_scrobble(user):
    agent_session = AgentSession.find_or_create(
        provider="openrouter", model="test-model"
    )[0]
    return Scrobble.objects.create(
        user=user,
        agent_session=agent_session,
        media_type="AgentSession",
        timestamp=timezone.now(),
        log={
            "title": "First prompt",
            "turns": [
                {
                    "prompt": "First prompt",
                    "response": "First response about hovercrafts",
                },
                {"prompt": "What about eels?", "response": "Eels are electric."},
            ],
        },
    )


@pytest.mark.django_db
def test_agent_session_search_matches_prompt(user, agent_scrobble, client):
    client.force_login(user)
    resp = client.get(reverse("agents:agent_session_search"), {"q": "eels"})
    assert resp.status_code == 200
    content = resp.content.decode()
    assert "eels" in content
    assert "<mark>eels</mark>" in content


@pytest.mark.django_db
def test_agent_session_search_matches_response(user, agent_scrobble, client):
    client.force_login(user)
    resp = client.get(reverse("agents:agent_session_search"), {"q": "hovercraft"})
    assert resp.status_code == 200
    content = resp.content.decode()
    assert "<mark>hovercraft</mark>" in content


@pytest.mark.django_db
def test_agent_session_search_no_match(user, agent_scrobble, client):
    client.force_login(user)
    resp = client.get(reverse("agents:agent_session_search"), {"q": "zzzznothing"})
    assert resp.status_code == 200
    assert "No agent sessions found" in resp.content.decode()


@pytest.mark.django_db
def test_agent_session_search_requires_login(client, agent_scrobble):
    resp = client.get(reverse("agents:agent_session_search"), {"q": "eels"})
    assert resp.status_code == 302


@pytest.mark.django_db
def test_global_scrobble_search_matches_agent_turns(user, agent_scrobble, client):
    client.force_login(user)
    resp = client.get(reverse("scrobbles:search"), {"q": "hovercraft"})
    assert resp.status_code == 200
    content = resp.content.decode()
    assert "hovercraft" in content
    assert "<mark>hovercraft</mark>" in content


@pytest.mark.django_db
def test_global_scrobble_search_agent_media_type_filter(user, agent_scrobble, client):
    client.force_login(user)
    resp = client.get(
        reverse("scrobbles:search"), {"q": "eels", "media_type": "AgentSession"}
    )
    assert resp.status_code == 200
    content = resp.content.decode()
    assert "<mark>eels</mark>" in content
