import os
import pytest
from gomemory import GoMemoryClient, Role, Message
from gomemory.exceptions import APIError
from pydantic import ValidationError

# Default to localhost if not set in the environment
BASE_URL = os.getenv("GOMEMORY_BASE_URL", "http://localhost:9000")

@pytest.fixture(scope="module")
def client():
    return GoMemoryClient(base_url=BASE_URL)

def test_health_check(client):
    response = client.health_check()
    assert response == "Server is healthy!"

def test_create_user(client):
    response = client.create_user()
    assert response.user_id is not None
    assert isinstance(response.user_id, str)

def test_add_memory(client):
    # Setup: need a user first
    user = client.create_user()
    
    messages = [
        Message(role=Role.USER, content="Hey man what's up! My name is mario .. my brother's name is Wario!"),
        Message(role=Role.ASSISTANT, content="I will remember that.")
    ]
    
    response = client.add_memory(user_id=user.user_id, messages=messages)
    assert response.req_id is not None
    assert response.msg is not None

def test_get_memory_validation(client):
    # Test the Pydantic XOR validation (should fail before hitting the server)
    with pytest.raises(ValidationError) as exc_info:
        client.get_memory(
            user_id="4bdc091b-eaa5-4d42-bbba-3cd798b9d294", 
        )
    assert "Exactly one of 'messages' or 'query' must be provided. Cannot provide both or neither." in str(exc_info.value)

def test_get_memory_success(client):
    user = client.create_user()
    
    # Optional: Wait for your Go server's worker pool to process embeddings 
    # if add_memory is asynchronous before calling get_memory.
    
    # Using query
    memories = client.get_memory(
        user_id="4bdc091b-eaa5-4d42-bbba-3cd798b9d294",
        query="I like dogs",
        threshold=0.7
    )
    assert isinstance(memories, list)

def test_get_status(client):
    user = client.create_user()
    messages = [Message(role=Role.USER, content="Test memory status")]
    insert_res = client.add_memory(user_id=user.user_id, messages=messages)
    
    status_res = client.get_status(req_id=insert_res.req_id)
    assert status_res.status is not None
    assert status_res.created_at is not None