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
/*
* _ _ _
* | | __ _ ______ __| | | | __ _ _ __ ___ __ _
* | | / _` ||_ /\ \/ /| | | |/ _` | '_ ` _ \ / _` |
* | |__| (_| | / / \ / | |___ | | (_| | | | | | | (_| |
* |_____\__,_|/___| /_/ |_____||_|\__,_|_| |_| |_|\__,_|
*
* Copyright (C) 2026 Raimo Geisel
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
//! Utility functions for file operations and system access.
//!
//! This module provides essential file system operations for the LazyLlama application,
//! including conversation history persistence and logging functionality. All file
//! operations use platform-appropriate directories following XDG specifications
//! on Unix systems and standard application data directories on Windows.
//!
//! # File Storage
//!
//! - **Location**: `~/.local/share/lazyllama/` (Unix) or equivalent on Windows
//! - **Format**: Plain text files with timestamp-based naming
//! - **Persistence**: Both combined and per-model history files
//! - **Error Handling**: Graceful degradation when storage is unavailable
use Result;
use Local;
use fs;
/// Saves conversation history to a timestamped file in the local data directory.
///
/// This function persists the provided conversation history to a new text file
/// in the application's data directory. The file is placed under
/// `~/.local/share/lazyllama/chat_YYYY-MM-DD_HH-MM-SS.txt` using the current
/// timestamp for unique identification.
///
/// # Arguments
///
/// * `history` - The complete conversation history string to be saved
///
/// # Returns
///
/// Returns `Ok(())` on successful file write or if the history is empty.
/// Returns an `anyhow::Error` if directory creation or file writing fails.
///
/// # Behavior
///
/// - **Empty Check**: Returns immediately if history string is empty
/// - **Directory Creation**: Creates the lazyllama directory if it doesn't exist
/// - **File Naming**: Uses timestamp format `YYYY-MM-DD_HH-MM-SS` for uniqueness
/// - **Atomic Write**: Uses `fs::write` for atomic file creation
///
/// # File Location
///
/// The storage location varies by platform:
/// - **Linux**: `~/.local/share/lazyllama/`
/// - **macOS**: `~/Library/Application Support/lazyllama/`
/// - **Windows**: `%LOCALAPPDATA%\lazyllama\`
///
/// # Error Handling
///
/// - Creates parent directories if they don't exist
/// - Propagates filesystem errors (permissions, disk space, etc.)
/// - Handles path encoding issues gracefully
///
/// # Example
///
/// ```no_run
/// use lazyllama::utils::save_history_to_file;
/// use anyhow::Result;
///
/// fn main() -> Result<()> {
/// let conversation = "YOU: Hello\nAI: Hi there!\n";
/// save_history_to_file(conversation)?;
/// // Creates: ~/.local/share/lazyllama/chat_2026-02-06_14-30-45.txt
/// Ok(())
/// }
/// ```
/// Saves separate conversation history files for each AI model.
///
/// This function creates individual history files for each AI model that has
/// conversation data, allowing users to maintain separate logs per model.
/// Each file is named with the model identifier and timestamp for easy
/// identification and organization.
///
/// # Arguments
///
/// * `model_histories` - HashMap mapping model names to their conversation histories
///
/// # Returns
///
/// Returns `Ok(())` on successful completion or an `anyhow::Error` if directory
/// creation or any file write operation fails.
///
/// # File Naming
///
/// Files are named using the pattern: `{safe_model_name}_{timestamp}.txt`
///
/// - **Model Name Sanitization**: Replaces `:`, `/`, `\` with `_` for filesystem compatibility
/// - **Timestamp Format**: `YYYY-MM-DD_HH-MM-SS` for consistent sorting
/// - **Extension**: Always `.txt` for universal compatibility
///
/// # Behavior
///
/// - **Empty History Skip**: Only creates files for models with non-empty histories
/// - **Atomic Writes**: Uses `fs::write` for atomic file creation per model
/// - **Single Timestamp**: All model files from one session share the same timestamp
/// - **Directory Reuse**: Creates the lazyllama directory once for all files
///
/// # Error Handling
///
/// - Fails fast if directory creation fails
/// - Continues processing remaining models if individual file writes fail
/// - Provides detailed error context for debugging
///
/// # Example
///
/// ```no_run
/// use std::collections::HashMap;
/// use lazyllama::utils::save_model_histories;
/// use anyhow::Result;
///
/// fn main() -> Result<()> {
/// let mut histories = HashMap::new();
/// histories.insert("llama2:7b".to_string(), "YOU: Test\nAI: Response".to_string());
/// histories.insert("codellama:13b".to_string(), "YOU: Code?\nAI: ```rust\n...".to_string());
///
/// save_model_histories(&histories)?;
/// // Creates:
/// // ~/.local/share/lazyllama/llama2_7b_2026-02-06_14-30-45.txt
/// // ~/.local/share/lazyllama/codellama_13b_2026-02-06_14-30-45.txt
/// Ok(())
/// }
/// ```
///
/// # Platform Compatibility
///
/// The function handles model names that may contain characters problematic
/// for certain filesystems, ensuring cross-platform compatibility.
/// Loads application settings from the config file.
///
/// This function reads the settings from `~/.config/lazyllama/settings.toml`
/// and deserializes them. If the file doesn't exist or cannot be read,
/// it returns the default settings.
///
/// # Returns
///
/// Returns the loaded `Settings` or default settings if loading fails.
///
/// # File Location
///
/// The config file location varies by platform:
/// - **Linux**: `~/.config/lazyllama/settings.toml`
/// - **macOS**: `~/Library/Application Support/lazyllama/settings.toml`
/// - **Windows**: `%APPDATA%\lazyllama\settings.toml`
///
/// # Example
///
/// ```no_run
/// use lazyllama::utils::load_settings;
///
/// let settings = load_settings();
/// println!("Theme: {:?}", settings.syntax_theme);
/// ```
/// Saves application settings to the config file.
///
/// This function serializes the provided settings and writes them to
/// `~/.config/lazyllama/settings.toml`. The config directory is created
/// if it doesn't exist.
///
/// # Arguments
///
/// * `settings` - The settings to save
///
/// # Returns
///
/// Returns `Ok(())` on success or an error if the operation fails.
///
/// # File Location
///
/// The config file location varies by platform:
/// - **Linux**: `~/.config/lazyllama/settings.toml`
/// - **macOS**: `~/Library/Application Support/lazyllama/settings.toml`
/// - **Windows**: `%APPDATA%\lazyllama\settings.toml`
///
/// # Example
///
/// ```no_run
/// use lazyllama::utils::save_settings;
/// use lazyllama::app::{Settings, SyntaxTheme};
/// use anyhow::Result;
///
/// fn main() -> Result<()> {
/// let mut settings = Settings::default();
/// settings.syntax_theme = SyntaxTheme::SolarizedDark;
/// save_settings(&settings)?;
/// Ok(())
/// }
/// ```