use crate::config::Config;
use crate::config::types::TelegramConfig;
const MAX_LEN: usize = 128;
pub(crate) fn sanitize(title: &str) -> Option<String> {
let printable: String = title
.chars()
.map(|c| if c.is_control() { ' ' } else { c })
.collect();
let collapsed = printable.split_whitespace().collect::<Vec<_>>().join(" ");
if collapsed.is_empty() {
return None;
}
let bounded: String = collapsed.chars().take(MAX_LEN).collect();
let bounded = bounded.trim_end();
if bounded.is_empty() {
None
} else {
Some(bounded.to_string())
}
}
pub(crate) fn needs_update(stored: Option<&str>, observed: &str) -> bool {
stored != Some(observed)
}
pub fn record(tg: &TelegramConfig, chat_id: &str, title: Option<&str>) -> Result<bool, String> {
let Some(group) = tg.groups.get(chat_id) else {
return Ok(false);
};
let Some(observed) = title.and_then(sanitize) else {
return Ok(false);
};
if !needs_update(group.name.as_deref(), &observed) {
return Ok(false);
}
Config::write_key_string(
&format!("channels.telegram.groups.{chat_id}"),
"name",
&observed,
)
.map(|()| true)
.map_err(|e| format!("Failed to write group name for {chat_id}: {e}"))
}