use libremetaverse_types::UUID;
use metacrate_grid_agent::{
    ConversationChannel, ConversationKey, ConversationLimits, ConversationStore, MemoryRecord,
};

fn key(number: u64, channel: ConversationChannel) -> ConversationKey {
    ConversationKey::new(
        UUID::new_with_u_int64(number).expect("fixture UUID"),
        channel,
    )
    .expect("nonzero fixture")
}

#[test]
fn contexts_never_cross_avatar_or_channel_boundaries() {
    let store = ConversationStore::open(ConversationLimits::default(), None).expect("store");
    let sessions = [
        (key(1, ConversationChannel::PublicChat), "alice-public-only"),
        (key(1, ConversationChannel::DirectIm), "alice-direct-only"),
        (key(2, ConversationChannel::PublicChat), "bob-public-only"),
    ];
    for (session, text) in sessions {
        store
            .append(session, MemoryRecord::avatar_message(text))
            .expect("append isolated message");
    }
    for (session, own_text) in sessions {
        let messages = store
            .context(session)
            .expect("isolated context")
            .llm_messages()
            .expect("LLM messages");
        let serialized = messages
            .iter()
            .flat_map(|message| message.content.as_slice())
            .filter_map(|part| match part {
                metacrate_grid_agent::ContentPart::Text(text) => Some(text.as_str()),
                metacrate_grid_agent::ContentPart::Image { .. } => None,
            })
            .collect::<Vec<_>>()
            .join("\n");
        assert!(serialized.contains(own_text));
        for (_, other_text) in sessions {
            if other_text != own_text {
                assert!(!serialized.contains(other_text));
            }
        }
    }
}
