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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
//! Convenient macros for application messaging and logging.
//!
//! Provides a comprehensive set of macros that simplify message display and logging throughout the application with automatic debug mode detection.
//!
//! ## Features
//!
//! - **Dual Output Mode**: Automatic switching between tracing and console output
//! - **Debug Detection**: Runtime detection of debug mode configuration
//! - **Message Categorization**: Different macros for different message types
//! - **Performance Optimization**: Cached debug mode detection for efficiency
//! - **Error Handling**: Specialized macros for error creation and handling
//!
//! ## Usage
//!
//! ```rust
//! use kasl::{msg_info, msg_error, msg_success, msg_warning};
//! use kasl::libs::messages::types::Message;
//!
//! // Basic message display
//! msg_info!(Message::TaskCreated);
//! msg_success!(Message::DailyReportSent("2025-01-15".to_string()));
//! msg_error!(Message::ConfigSaveError);
//!
//! // Custom formatted messages
//! let count = 5;
//! msg_info!(format!("Processing {} items", count));
//! ```
/// Convenience macros for common message operations with conditional tracing support
use OnceLock;
/// Global cache for debug mode detection to avoid repeated environment variable checks.
///
/// This static variable uses `OnceLock` to cache the result of debug mode detection
/// on first access. This provides significant performance benefits by avoiding
/// repeated environment variable lookups, which can be expensive operations.
///
/// ## Performance Benefits
/// - **Single Check**: Environment variables are checked only once per application run
/// - **Fast Access**: Subsequent checks are simple memory reads
/// - **Thread Safety**: OnceLock provides thread-safe initialization
/// - **Memory Efficiency**: Minimal memory overhead for caching
static DEBUG_MODE: = new;
/// Checks if debug mode is enabled, with caching for performance.
///
/// This function determines whether the application is running in debug mode
/// by checking for the presence of debug-related environment variables. The
/// result is cached using `OnceLock` to avoid repeated expensive environment
/// variable lookups.
///
/// ## Detection Logic
///
/// Debug mode is considered enabled if either of these environment variables is set:
/// - **`KASL_DEBUG`**: Application-specific debug flag
/// - **`RUST_LOG`**: Standard Rust logging configuration
///
/// The presence of either variable indicates that the user wants enhanced
/// logging output and expects debug information to be available.
///
/// ## Caching Strategy
///
/// The function uses a lazy initialization pattern:
/// 1. **First Call**: Checks environment variables and caches result
/// 2. **Subsequent Calls**: Returns cached value without environment checks
/// 3. **Thread Safety**: Multiple threads can safely call this function
/// 4. **Performance**: Subsequent calls are essentially free
///
/// ## Integration Points
///
/// This function is used by all message macros to determine output routing:
/// - **Debug Mode**: Messages go to tracing system with structured logging
/// - **Normal Mode**: Messages go to simple console output (println!/eprintln!)
///
/// # Returns
///
/// Returns `true` if debug mode is enabled, `false` otherwise. The result
/// is cached for the lifetime of the application.
///
/// # Examples
///
/// ```rust
/// use kasl::libs::messages::macros::is_debug_mode;
///
/// if is_debug_mode() {
/// println!("Running in debug mode with enhanced logging");
/// } else {
/// println!("Running in normal mode with simple output");
/// }
/// ```
/// Prints a general message with automatic debug mode routing.
///
/// This macro provides the basic message display functionality with automatic
/// detection of debug mode to route output appropriately. It supports both
/// simple single-line messages and formatted messages with optional line breaks.
///
/// ## Output Routing
///
/// - **Debug Mode**: Uses `tracing::info!` for structured logging
/// - **Normal Mode**: Uses `println!` for simple console output
///
/// ## Usage Patterns
///
/// ### Simple Message
/// ```rust
/// use kasl::msg_print;
/// use kasl::libs::messages::types::Message;
///
/// msg_print!(Message::ConfigSaved);
/// // Output: "Configuration saved successfully"
/// ```
///
/// ### Message with Line Breaks
/// ```rust
/// use kasl::msg_print;
/// use kasl::libs::messages::types::Message;
///
/// msg_print!(Message::ReportHeader("2025-01-15".to_string()), true);
/// // Output: "\nš Daily Work Report\n"
/// ```
///
/// ## Performance Notes
///
/// - Debug mode detection is cached for efficiency
/// - Tracing integration provides structured logging in debug mode
/// - Simple println! provides fast output in production mode
/// Prints a success message with ā
prefix and automatic routing.
///
/// This macro is specifically designed for displaying success notifications
/// and positive confirmations. The green checkmark emoji provides visual
/// confirmation that operations completed successfully.
///
/// ## Visual Design
///
/// - **Prefix**: ā
(green checkmark emoji)
/// - **Purpose**: Success confirmations and positive outcomes
/// - **Examples**: Task creation, configuration saves, successful exports
///
/// ## Output Examples
///
/// ```text
/// ā
Task created successfully
/// ā
Configuration saved successfully
/// ā
Data exported to file.csv
/// ```
///
/// ## Usage Patterns
///
/// ### Simple Success Message
/// ```rust
/// use kasl::msg_success;
/// use kasl::libs::messages::types::Message;
///
/// msg_success!(Message::TaskCreated);
/// // Output: "ā
Task created successfully"
/// ```
///
/// ### Success Message with Line Breaks
/// ```rust
/// use kasl::msg_success;
/// use kasl::libs::messages::types::Message;
///
/// msg_success!(Message::ExportCompleted("data.csv".to_string()), true);
/// // Output: "\nā
Data exported successfully to: data.csv\n"
/// ```
/// Prints an error message with ā prefix and automatic routing.
///
/// This macro handles error message display with appropriate severity level
/// routing. In debug mode, errors are logged through the tracing system,
/// while in normal mode they're displayed on stderr for proper error handling.
///
/// ## Visual Design
///
/// - **Prefix**: ā (red X emoji)
/// - **Purpose**: Error notifications and failure messages
/// - **Stream**: Uses stderr in normal mode for proper error stream handling
///
/// ## Output Routing
///
/// - **Debug Mode**: Uses `tracing::error!` for structured error logging
/// - **Normal Mode**: Uses `eprintln!` to write to stderr
///
/// ## Error Stream Benefits
///
/// Using stderr for error output provides several advantages:
/// - **Stream Separation**: Errors don't interfere with normal output
/// - **Script Compatibility**: Scripts can separate errors from data
/// - **Shell Redirection**: Users can redirect errors independently
/// - **Log Aggregation**: Error logs can be collected separately
///
/// ## Usage Patterns
///
/// ### Simple Error Message
/// ```rust
/// use kasl::msg_error;
/// use kasl::libs::messages::types::Message;
///
/// msg_error!(Message::TaskNotFound);
/// // Output to stderr: "ā Task not found"
/// ```
///
/// ### Error Message with Line Breaks
/// ```rust
/// use kasl::msg_error;
/// use kasl::libs::messages::types::Message;
///
/// msg_error!(Message::ConfigParseError, true);
/// // Output to stderr: "\nā Failed to parse configuration file\n"
/// ```
/// Prints a warning message with ā ļø prefix and automatic routing.
///
/// This macro displays warning messages that indicate potential issues or
/// situations requiring user attention, but which don't prevent operation
/// from continuing. Warnings help users understand system state and make
/// informed decisions.
///
/// ## Visual Design
///
/// - **Prefix**: ā ļø (warning triangle emoji)
/// - **Purpose**: Cautionary messages and non-critical issues
/// - **Severity**: Less critical than errors, more important than info
///
/// ## Warning Categories
///
/// Warnings are appropriate for:
/// - **Deprecated Features**: Features that will be removed in future versions
/// - **Configuration Issues**: Non-critical configuration problems
/// - **Performance Concerns**: Operations that may be slow or inefficient
/// - **Fallback Behavior**: When the system falls back to default behavior
/// - **Resource Limitations**: When approaching resource limits
///
/// ## Usage Patterns
///
/// ### Simple Warning Message
/// ```rust
/// use kasl::msg_warning;
/// use kasl::libs::messages::types::Message;
///
/// msg_warning!(Message::AutostartCheckingAlternative);
/// // Output: "ā ļø Checking alternative autostart methods..."
/// ```
///
/// ### Warning Message with Line Breaks
/// ```rust
/// use kasl::msg_warning;
/// use kasl::libs::messages::types::Message;
///
/// msg_warning!(Message::WatcherSignalHandlingNotSupported, true);
/// // Output: "\nā ļø Signal handling not supported on this platform\n"
/// ```
/// Prints an informational message with ā¹ļø prefix and automatic routing.
///
/// This macro displays informational messages that provide useful context
/// or status updates to users. Info messages help users understand what
/// the system is doing and provide transparency into system operations.
///
/// ## Visual Design
///
/// - **Prefix**: ā¹ļø (information emoji)
/// - **Purpose**: Status updates and informational content
/// - **Tone**: Neutral, informative, helpful
///
/// ## Information Categories
///
/// Info messages are appropriate for:
/// - **Status Updates**: Progress information for long-running operations
/// - **System State**: Current system status and configuration
/// - **Process Information**: What the system is currently doing
/// - **User Guidance**: Helpful tips and usage information
/// - **Confirmation**: Non-critical confirmations and acknowledgments
///
/// ## Usage Patterns
///
/// ### Simple Info Message
/// ```rust
/// use kasl::msg_info;
/// use kasl::libs::messages::types::Message;
///
/// msg_info!(Message::WatcherStarted(1234));
/// // Output: "ā¹ļø Watcher started with PID: 1234"
/// ```
///
/// ### Info Message with Line Breaks
/// ```rust
/// use kasl::msg_info;
/// use kasl::libs::messages::types::Message;
///
/// msg_info!(Message::WorkingHoursForMonth("2025-01".to_string()), true);
/// // Output: "\nā¹ļø š
Monthly Summary\n"
/// ```
/// Debug-only message display with š prefix.
///
/// This macro provides debug-specific logging that only appears when debug
/// mode is explicitly enabled. Debug messages are useful for troubleshooting
/// and development but are hidden from normal users to avoid clutter.
///
/// ## Debug-Only Behavior
///
/// - **Debug Mode**: Messages are displayed using `tracing::debug!`
/// - **Normal Mode**: Messages are completely suppressed (no output)
/// - **Performance**: No overhead in production builds when debug is disabled
///
/// ## Visual Design
///
/// - **Prefix**: š (magnifying glass emoji)
/// - **Purpose**: Development and troubleshooting information
/// - **Audience**: Developers and power users debugging issues
///
/// ## Debug Message Categories
///
/// Debug messages are appropriate for:
/// - **Technical Details**: Low-level system information
/// - **State Changes**: Internal state transitions and updates
/// - **Performance Metrics**: Timing and performance measurements
/// - **Data Flow**: How data moves through the system
/// - **Error Context**: Additional context for debugging errors
///
/// ## Usage Patterns
///
/// ### Technical Debug Information
/// ```rust
/// use kasl::msg_debug;
///
/// let task_id = 42;
/// msg_debug!(format!("Processing task with ID: {}", task_id));
/// // Debug mode output: "š Processing task with ID: 42"
/// // Normal mode output: (nothing)
/// ```
///
/// ### State Change Debugging
/// ```rust
/// use kasl::msg_debug;
///
/// let old_state = "Active";
/// let new_state = "InPause";
/// msg_debug!(format!("State transition: {:?} -> {:?}", old_state, new_state));
/// // Debug mode output: "š State transition: Active -> InPause"
/// // Normal mode output: (nothing)
/// ```
/// Creates an `anyhow::Error` from a message with ā prefix.
///
/// This macro provides a convenient way to create `anyhow::Error` instances
/// from application messages. It's useful for error propagation in functions
/// that return `Result<T, anyhow::Error>` and need to convert application
/// messages into proper error types.
///
/// ## Error Creation Strategy
///
/// - **Prefix Addition**: Automatically adds ā prefix for visual consistency
/// - **Error Propagation**: Creates errors suitable for `?` operator use
/// - **Message Integration**: Works with the application's message system
/// - **Type Compatibility**: Returns `anyhow::Error` for easy integration
///
/// ## Use Cases
///
/// ### Function Error Returns
/// ```rust
/// use anyhow::Result;
/// use kasl::{msg_error_anyhow, libs::messages::Message};
///
/// # fn config_is_invalid() -> bool { false }
/// fn validate_config() -> Result<()> {
/// if config_is_invalid() {
/// return Err(msg_error_anyhow!(Message::ConfigParseError));
/// }
/// Ok(())
/// }
/// ```
///
/// ### Error Context Addition
/// ```rust
/// use anyhow::{Result, Context};
/// use kasl::{msg_error_anyhow, libs::messages::Message};
///
/// # fn some_operation() -> Result<()> { Ok(()) }
/// fn complex_operation() -> Result<()> {
/// some_operation()
/// .context(msg_error_anyhow!(Message::TaskUpdateFailed))
/// }
/// ```
///
/// ## Error Handling Benefits
///
/// - **Consistent Formatting**: All errors have consistent visual presentation
/// - **Message Reuse**: Leverages existing message definitions
/// - **Type Safety**: Provides proper error types for Rust's error handling
/// - **Integration**: Works seamlessly with `anyhow` and `?` operator
/// Early return with an error created from a message.
///
/// This macro combines error creation with immediate return, providing a
/// convenient way to exit functions early when error conditions are detected.
/// It's equivalent to `return Err(msg_error_anyhow!(message))` but more concise.
///
/// ## Early Return Pattern
///
/// - **Error Creation**: Creates an `anyhow::Error` with ā prefix
/// - **Immediate Return**: Returns the error immediately from the function
/// - **Function Exit**: Stops execution at the point of the macro call
/// - **Clean Code**: Reduces boilerplate for error handling
///
/// ## Use Cases
///
/// ### Input Validation
/// ```rust
/// use anyhow::Result;
/// use kasl::{msg_bail_anyhow, libs::messages::Message};
///
/// fn process_task(task_id: Option<i32>) -> Result<()> {
/// let id = match task_id {
/// Some(id) => id,
/// None => msg_bail_anyhow!(Message::InvalidInput),
/// };
///
/// // Continue processing with valid ID
/// let _ = id;
/// Ok(())
/// }
/// ```
///
/// ### Permission Checking
/// ```rust
/// use anyhow::Result;
/// use kasl::{msg_bail_anyhow, libs::messages::Message};
///
/// # fn user_has_permission() -> bool { true }
/// fn secure_operation() -> Result<()> {
/// if !user_has_permission() {
/// msg_bail_anyhow!(Message::PermissionDenied);
/// }
///
/// // Continue with authorized operation
/// Ok(())
/// }
/// ```
///
/// ### Resource Validation
/// ```rust
/// use anyhow::Result;
/// use kasl::{msg_bail_anyhow, libs::messages::Message};
///
/// # fn resource_exists(_path: &str) -> bool { true }
/// fn access_resource(path: &str) -> Result<()> {
/// if !resource_exists(path) {
/// msg_bail_anyhow!(Message::FileNotFound);
/// }
///
/// // Continue with valid resource
/// Ok(())
/// }
/// ```
///
/// ## Code Style Benefits
///
/// - **Reduced Boilerplate**: Eliminates repetitive error handling code
/// - **Clear Intent**: Makes error conditions immediately obvious
/// - **Consistent Errors**: All bail errors have consistent formatting
/// - **Maintainability**: Easier to update error handling patterns