"""Tests for the Nexus conversational awareness routes."""

from unittest.mock import patch


def test_nexus_page_returns_200(client):
    """GET /nexus should render without error."""
    response = client.get("/nexus")
    assert response.status_code == 200
    assert "NEXUS" in response.text


def test_nexus_page_contains_chat_form(client):
    """Nexus page must include the conversational chat form."""
    response = client.get("/nexus")
    assert response.status_code == 200
    assert "/nexus/chat" in response.text


def test_nexus_page_contains_teach_form(client):
    """Nexus page must include the teaching panel form."""
    response = client.get("/nexus")
    assert response.status_code == 200
    assert "/nexus/teach" in response.text


def test_nexus_chat_empty_message_returns_empty(client):
    """POST /nexus/chat with blank message returns empty response."""
    response = client.post("/nexus/chat", data={"message": "   "})
    assert response.status_code == 200
    assert response.text == ""


def test_nexus_chat_too_long_returns_error(client):
    """POST /nexus/chat with overlong message returns error partial."""
    long_msg = "x" * 10_001
    response = client.post("/nexus/chat", data={"message": long_msg})
    assert response.status_code == 200
    assert "too long" in response.text.lower()


def test_nexus_chat_posts_message(client):
    """POST /nexus/chat calls the session chat function and returns a partial."""
    with patch("dashboard.routes.nexus.chat", return_value="Hello from Timmy"):
        response = client.post("/nexus/chat", data={"message": "hello"})
    assert response.status_code == 200
    assert "hello" in response.text.lower() or "timmy" in response.text.lower()


def test_nexus_teach_stores_fact(client):
    """POST /nexus/teach should persist a fact and return confirmation."""
    with (
        patch("dashboard.routes.nexus.store_personal_fact") as mock_store,
        patch("dashboard.routes.nexus.recall_personal_facts_with_ids", return_value=[]),
    ):
        mock_store.return_value = None
        response = client.post("/nexus/teach", data={"fact": "Timmy loves Python"})
    assert response.status_code == 200
    assert "Timmy loves Python" in response.text


def test_nexus_teach_empty_fact_returns_empty(client):
    """POST /nexus/teach with blank fact returns empty response."""
    response = client.post("/nexus/teach", data={"fact": "   "})
    assert response.status_code == 200
    assert response.text == ""


def test_nexus_clear_history(client):
    """DELETE /nexus/history should clear the conversation log."""
    with patch("dashboard.routes.nexus.reset_session"):
        response = client.request("DELETE", "/nexus/history")
    assert response.status_code == 200
    assert "cleared" in response.text.lower()
