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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
use super::fabric::execute_fabric_command;
use super::whisper;
use crate::db::Database;
use grammers_client::types::{Chat, Downloadable, Media, Message};
use grammers_client::{Client, InputMessage};
use log::{debug, error, info};

use regex::Regex;
use std::collections::HashMap;
use std::error::Error;
use std::path::Path;

pub async fn handle_message(
    tg: &mut Client,
    message: &Message,
    chat_map: HashMap<i64, String>,
    db: &mut Database,
) -> Result<(), Box<dyn std::error::Error>> {
    let (cmd, params, text) = parse_command(message.text().trim_start_matches(&['/', '!']));
    info!(
        "Chat:{} parse_command: {} {:?} {}",
        message.chat().id(),
        cmd,
        params,
        text
    );

    let output: String = match cmd.as_str() {
        "start" | "help" => help_text(),
        "patterns" | "l" => super::fabric::patterns().await?,

        "models" | "L" => super::fabric::models().await?,
        "changeDefaultModel" | "d" => super::fabric::change_default_model(&params[0]).await?,

        "chatIds" | "ids" => pretty_print_chat_map(&chat_map, 0),
        "chatAdd" | "a" => enable_chat(db, &params[0]),
        "chatRemove" | "r" => disable_chat(db, &params[0]),
        "fabric" | "f" => run_fabric(db, &params, &text).await,
        "whisperModel" | "wm" => {
            if params.len() > 0 {
                db.set_whisper_model(&params[0])
            } else {
                db.get_whisper_model().to_owned()
            }
        }
        "whisper" | "w" => {
            run_whisper(
                tg,
                &message,
                match &params.is_empty() {
                    true => db.get_whisper_model(),
                    false => &params[0],
                },
            )
            .await
        }

        _ => {
            if let (true, Some(id)) = is_chat_id(message.text(), &db.get_chat_ids()) {
                if db.chat_id_exists(&id) {
                    db.remove_chat_id(id);
                    "Chat id removed".to_owned()
                } else {
                    db.add_chat_id(id);
                    "Chat id added".to_owned()
                }
            } else {
                "".to_owned()
            }
        }
    };

    // let output = format!("cmd={} params={:?} text={}", cmd, params, text);

    if !output.is_empty() {
        send_response(tg, &message.chat(), &output, message.id()).await
    } else {
        Ok(())
    }
}

async fn run_whisper(tg: &Client, message: &&Message, whisper_model: &str) -> String {
    let parent_media = parse_parent_video(message).await;

    let media_path = match parent_media {
        Some((media, message_id)) => {
            Some(crate::handlers::download_media(tg, media, message_id).await)
        }
        None => None,
    };

    let output = match media_path {
        Some(path) => whisper::whisper_rs(&path, whisper_model).await,
        None => "Message has no audio".to_owned(),
    };

    output
}

// async fn parse_parent_audio(message: &&Message) {
//     match parse_parent_media(message).await {
//         Some(media) => matches!(media, Photo),
//         None => None,
//     }
// }

async fn parse_parent_photo(message: &&Message) -> Option<(grammers_client::types::Photo, i32)> {
    match message.get_reply().await {
        Ok(parent) => match parent {
            Some(parent) => match parent.media() {
                Some(media) => match media {
                    Media::Photo(photo) => Some((photo, parent.id())),
                    _ => None, // Filter out any other media types
                },
                None => None,
            },
            None => None,
        },
        Err(_) => None,
    }
}

// grammers_client::types::media::Document
async fn parse_parent_video(message: &&Message) -> Option<(grammers_client::types::Media, i32)> {
    match message.get_reply().await {
        Ok(parent) => match parent {
            Some(parent) => match parent.media() {
                Some(media) => match media {
                    Media::Document(_) => Some((media, parent.id())),
                    _ => None, // Filter out any other media types
                },
                None => None,
            },
            None => None,
        },
        Err(_) => None,
    }
}

// async fn parse_parent(message: &&Message) -> Option<(String, String)> {
//     match message.get_reply().await {
//         Ok(parent) => match parent {
//             Some(parent) => Some((parent.text().to_owned(), parent.chat().name().to_string())),
//             None => None,
//         },
//         Err(_) => None,
//     }
// }

fn enable_chat(db: &mut Database, params: &str) -> String {
    match params.parse::<i64>() {
        Ok(id) => {
            db.add_chat_id(id);
            format!("Enabled AI on {}", id)
        }
        Err(e) => format!("Chat Id Error: {} ", e),
    }
}

fn disable_chat(db: &mut Database, params: &str) -> String {
    match params.parse::<i64>() {
        Ok(id) => {
            db.remove_chat_id(id);
            format!("Disabled AI on {}", id)
        }
        Err(e) => format!("Chat Id Error: {} ", e),
    }
}

async fn run_fabric(_db: &mut Database, params: &Vec<String>, text: &str) -> String {
    let mut args = params.iter().map(|s| s.as_str()).collect::<Vec<&str>>();
    args.push(&text);

    match execute_fabric_command(&args).await {
        Ok(output) => output,
        Err(e) => format!("Fabric failed {}", e),
    }
}

fn is_chat_id(text: &str, chat_ids: &Vec<i64>) -> (bool, Option<i64>) {
    match text.parse::<i64>() {
        Ok(id) => (chat_ids.contains(&id), Some(id)),
        Err(_) => (false, None),
    }
}

fn help_text() -> String {
    return "Getting started:
        `/ids` - Show your chat names and their ID
        `/chatAdd <id>` - Enable AI features on that chat
        `/models` - List available models
        `/patterns - List available fabric patterns"
        .to_owned();
}

fn pretty_print_chat_map(chat_map: &HashMap<i64, String>, indent: usize) -> String {
    let mut output = String::new();
    for (k, v) in chat_map.iter() {
        output.push_str(&"  ".repeat(indent));
        output.push_str(&format!("{}: {}\n", k, v));
    }
    output
}

async fn send_response(
    tg: &Client,
    chat: &Chat,
    message: &str,
    message_id: i32,
) -> Result<(), Box<dyn Error>> {
    // println!("message: {}", message);
    let chunk_size = 4096;

    // Handle the message in chunks
    let mut start = 0;
    let mut end;

    while start < message.len() {
        end = start + chunk_size;

        // Make sure we don't exceed the message length
        if end > message.len() {
            end = message.len();
        } else {
            // Ensure that we split at valid UTF-8 character boundaries
            while !message.is_char_boundary(end) {
                end -= 1;
            }

            // Now try to find the last whitespace (or newline) before the limit to split cleanly
            if let Some(last_space) = message[start..end].rfind(|c: char| c == ' ' || c == '\n') {
                end = start + last_space;
            }
        }

        // Send the chunk (from start to end)
        // println!("send_message: {}", &message[start..end]);
        if start == 0 {
            tg.edit_message(chat, message_id, InputMessage::text(&message[start..end]))
                .await?;
        } else {
            tg.send_message(
                chat,
                InputMessage::text(&message[start..end]).reply_to(Some(message_id)),
            )
            .await?;
        }

        // Move start to end to process the next chunk
        start = end;

        // Skip any leading whitespace or newline in the next chunk
        while start < message.len() && message[start..].starts_with(|c: char| c == ' ' || c == '\n')
        {
            start += 1;
        }
    }

    Ok(())
}

pub fn parse_command(text: &str) -> (String, Vec<String>, String) {
    let re = Regex::new(r#"(?P<cmd>\w+)(?: (?P<params>(?:-\w+ "(?:[^"]+)"|-\w+ \w+|\w+)(?:\s+-\w+ "(?:[^"]+)"|\s+-\w+ \w+)*))?(?: (?P<text>.+))?"#)
        .unwrap();

    if let Some(captures) = re.captures(text.trim_start_matches('/')) {
        let cmd = captures.name("cmd").unwrap().as_str().to_string();

        // Manually parse parameters to handle quoted values
        let params_str = captures.name("params").map_or("", |p| p.as_str());
        let mut params: Vec<String> = Vec::new();
        let mut in_quotes = false;
        let mut current_param = String::new();

        for token in params_str.split_whitespace() {
            if token.starts_with('"') {
                in_quotes = true;
                current_param.push_str(&token[1..]); // remove opening quote
            } else if token.ends_with('"') {
                in_quotes = false;
                current_param.push(' ');
                current_param.push_str(&token[..token.len() - 1]); // remove closing quote
                params.push(current_param.clone());
                current_param.clear();
            } else if in_quotes {
                current_param.push(' ');
                current_param.push_str(token);
            } else {
                params.push(token.to_string());
            }
        }

        let mut text = captures.name("text").map_or("", |t| t.as_str()).to_string();
        // Remove surrounding quotes from the text if they exist
        if text.starts_with('"') && text.ends_with('"') {
            text = text[1..text.len() - 1].to_string();
        }

        (cmd, params, text)
    } else {
        ("".to_owned(), vec![], "".to_owned())
    }
}

#[test]
fn test_parse_command() {
    // Test cases

    // No command or text
    assert_eq!(parse_command(""), ("".to_owned(), vec![], "".to_owned()));

    // Single word command (no params, no text)
    assert_eq!(
        parse_command("ping"),
        ("ping".to_owned(), vec![], "".to_owned())
    );

    // Command with single-word parameter
    assert_eq!(
        parse_command("fabric -p summarize"),
        (
            "fabric".to_owned(),
            vec!["-p".to_string(), "summarize".to_string()],
            "".to_owned()
        )
    );

    // Command with multiple parameters (no text)
    assert_eq!(
        parse_command("chatAdd -d 1234567890 -u user_name"),
        (
            "chatAdd".to_owned(),
            vec![
                "-d".to_string(),
                "1234567890".to_string(),
                "-u".to_string(),
                "user_name".to_string()
            ],
            "".to_owned()
        )
    );

    // Command with parameters and text
    assert_eq!(
        parse_command("fabric -p summarize This is some text for the fabric command"),
        (
            "fabric".to_owned(),
            vec!["-p".to_string(), "summarize".to_string()],
            "This is some text for the fabric command".to_owned()
        )
    );

    // Command with quoted parameters and text
    assert_eq!(
        parse_command("chatRemove -d \"value with spaces\" And this is some extra text"),
        (
            "chatRemove".to_owned(),
            vec!["-d".to_string(), "value with spaces".to_string()],
            "And this is some extra text".to_owned()
        )
    );

    // Command with only quoted text
    assert_eq!(
        parse_command("ping \"Some quoted text\""),
        ("ping".to_owned(), vec![], "Some quoted text".to_owned())
    );

    // Complex command with multiple parameters and text
    assert_eq!(
        parse_command("fabric -p summarize -d 1234567890 -u user_name This is some additional text for the fabric command"),
        ("fabric".to_owned(),
            vec![
                "-p".to_string(), "summarize".to_string(),
                "-d".to_string(), "1234567890".to_string(),
                "-u".to_string(), "user_name".to_string()
            ],
        "This is some additional text for the fabric command".to_owned())
    );

    println!("All test cases passed");
}