1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
use std::sync::Arc;

pub use crate::traits::MessageBuilder;

#[derive(Clone)]
pub struct PromptMessageGroup {
    title: String,
    messages: Vec<(String, Arc<dyn Fn() -> String + Send + Sync>)>,
}

impl std::fmt::Debug for PromptMessageGroup {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PromptMessageGroup")
            .field("title", &self.title)
            // Optionally, you can show the number of messages or their titles
            // but not the closures themselves as they do not implement Debug
            .field(
                "messages",
                &self
                    .messages
                    .iter()
                    .map(|(title, _)| title)
                    .collect::<Vec<_>>(),
            )
            .finish()
    }
}

impl PromptMessageGroup {
    // Constructor for a new PromptMessageGroup with a title.
    pub fn new(title: &str) -> Self {
        PromptMessageGroup {
            title: title.to_string(),
            messages: Vec::new(),
        }
    }

    // Inserts a static message into the group.
    pub fn insert(&mut self, key: &str, value: &str) {
        let v = value.to_string();
        self.messages
            .push((key.to_string(), Arc::new(move || v.clone())));
    }

    // Inserts a dynamic message into the group.
    pub fn insert_dyn<F>(&mut self, key: &str, value: F)
    where
        F: Fn() -> String + 'static + Send + Sync,
    {
        self.messages.push((key.to_string(), Arc::new(value)));
    }

    // Removes a message by key.
    pub fn remove_key(&mut self, key: &str) {
        self.messages.retain(|(k, _)| k != key);
    }
}

impl MessageBuilder for PromptMessageGroup {
    fn build(&mut self) -> String {
        let messages = self
            .messages
            .iter()
            .map(|(key, value_fn)| {
                if key.is_empty() {
                    format!("{}", value_fn())
                } else {
                    format!("{}: {}", key, value_fn())
                }
            })
            .collect::<Vec<String>>()
            .join("\n");

        if self.title.is_empty() {
            messages
        } else {
            format!("[{}]\n{}", self.title, messages)
        }
    }
}

// one time
pub struct PromptMessageBuilder<T>
where
    T: IntoIterator,
    T::Item: MessageBuilder,
{
    groups: Option<T>,
}

impl<T> PromptMessageBuilder<T>
where
    T: IntoIterator,
    T::Item: MessageBuilder,
{
    // Constructor for a new PromptMessageBuilder with an iterable of items that implement MessageBuilder.
    pub fn new(groups: T) -> Self {
        PromptMessageBuilder {
            groups: Some(groups),
        }
    }
}

impl<T> MessageBuilder for PromptMessageBuilder<T>
where
    T: IntoIterator,
    T::Item: MessageBuilder,
{
    fn build(&mut self) -> String {
        let groups = self
            .groups
            .take()
            .expect("Groups should not be taken more than once");

        groups
            .into_iter()
            .map(|mut group| group.build())
            .collect::<Vec<String>>()
            .join("\n\n")
    }
}

// pub struct PromptMessageBuilder {
//     groups: Vec<PromptMessageGroup>,
// }
//
// impl PromptMessageBuilder {
//     // Constructor for a new PromptMessageBuilder with groups.
//     pub fn new(groups: Vec<PromptMessageGroup>) -> Self {
//         PromptMessageBuilder { groups }
//     }
// }
//
// impl MessageBuilder for PromptMessageBuilder {
//     fn build(&self) -> String {
//         self.groups
//             .iter()
//             .map(|group| group.build())
//             .collect::<Vec<String>>()
//             .join("\n\n")
//     }
// }

// pub struct PromptMessageBuilder<'a> {
//     groups: Vec<&'a PromptMessageGroup>,
// }
//
// impl<'a> PromptMessageBuilder<'a> {
//     // Constructor for a new PromptMessageBuilder with groups.
//     pub fn new(groups: Vec<&'a PromptMessageGroup>) -> Self {
//         PromptMessageBuilder { groups }
//     }
// }
//
// impl<'a> MessageBuilder for PromptMessageBuilder<'a> {
//     fn build(&self) -> String {
//         self.groups
//             .iter()
//             .map(|group| group.build())
//             .collect::<Vec<String>>()
//             .join("\n\n")
//     }
// }

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_insert_static_message() {
        let mut group = PromptMessageGroup::new("Test Group");
        group.insert("Key1", "Value1");
        group.insert("Key2", "Value2");

        // Assuming a method to retrieve a message for testing purposes
        // This part is purely illustrative; actual implementation may vary
        assert_eq!(group.messages[0].0, "Key1");
        assert_eq!((group.messages[0].1)(), "Value1");
        assert_eq!(group.messages[1].0, "Key2");
        assert_eq!((group.messages[1].1)(), "Value2");
    }

    #[test]
    fn test_insert_dynamic_message() {
        let dynamic_value = || "Dynamic Value".to_string();
        let mut group = PromptMessageGroup::new("Group");
        group.insert_dyn("Key", dynamic_value);

        assert_eq!(group.messages[0].0, "Key");
        assert_eq!((group.messages[0].1)(), "Dynamic Value");
    }

    #[test]
    fn test_remove_key() {
        let mut group = PromptMessageGroup::new("Group");
        group.insert("Key", "Value");
        assert_eq!(group.messages.len(), 1);
        group.remove_key("Key");
        assert!(group.messages.is_empty());
    }

    #[test]
    fn test_build_output() {
        let mut group1 = PromptMessageGroup::new("Group1");
        group1.insert("Key1", "Value1");
        let mut group2 = PromptMessageGroup::new("Group2");
        group2.insert("Key2", "Value2");

        let output = PromptMessageBuilder::new(vec![group1, group2]).build();

        let expected_output = "[Group1]\nKey1: Value1\n\n[Group2]\nKey2: Value2";
        assert_eq!(output, expected_output);
    }
}