Skip to main content

numby/
lib.rs

1//! # Numby Library
2//!
3//! This library provides the core functionality for the Numby natural language calculator.
4//!
5//! ## Modules
6//!
7//! - `config`: Configuration loading and management.
8//! - `evaluator`: Expression evaluation and conversions.
9//! - `models`: Data structures and state management.
10//! - `parser`: Parsing utilities and regex replacements.
11//! - `conversions`: Unit and currency conversion functions.
12//! - `prettify`: Number formatting for display.
13//! - `security`: Path validation and input sanitization.
14//! - `i18n`: Internationalization and localization support.
15
16mod completion;
17pub mod config;
18pub mod conversions;
19pub mod currency_fetcher;
20pub mod evaluator;
21pub mod highlight;
22pub mod i18n;
23pub mod line_groups;
24pub mod models;
25pub mod parser;
26pub mod prettify;
27pub mod security;
28
29#[cfg(feature = "android")]
30pub mod android_jni;
31
32#[cfg(test)]
33mod event_tests {
34    use crate::config::Config;
35    use crate::evaluator::{EventSubscriber, StateEvent};
36    use crate::models::AppState;
37    use std::sync::atomic::{AtomicUsize, Ordering};
38    use std::sync::Arc;
39
40    struct TestSubscriber {
41        event_count: Arc<AtomicUsize>,
42    }
43
44    impl EventSubscriber for TestSubscriber {
45        fn on_event(&self, _event: &StateEvent) {
46            self.event_count.fetch_add(1, Ordering::SeqCst);
47        }
48    }
49
50    #[test]
51    fn test_event_publishing() {
52        let config = Config::default();
53        let state = AppState::builder(&config).build();
54
55        let event_count = Arc::new(AtomicUsize::new(0));
56        let subscriber = Arc::new(TestSubscriber {
57            event_count: event_count.clone(),
58        });
59
60        let _ = state.subscribe(subscriber);
61
62        // Publish an event
63        state.publish_event(StateEvent::HistoryAdded(42.0));
64
65        assert_eq!(event_count.load(Ordering::SeqCst), 1);
66    }
67
68    #[test]
69    fn test_cache_invalidation_on_variable_change() {
70        let config = Config::default();
71        let state = AppState::builder(&config).build();
72
73        // Set a cache value
74        state
75            .cache
76            .set_display("test_key".to_string(), Some("cached_value".to_string()));
77
78        // Verify it's cached
79        assert_eq!(
80            state.cache.get_display("test_key"),
81            Some(Some("cached_value".to_string()))
82        );
83
84        // Trigger a variable change event
85        state.publish_event(StateEvent::VariableChanged("test".to_string()));
86
87        // Cache should be invalidated for prefix "test"
88        // Keys that don't start with "test" should still be there
89        state
90            .cache
91            .set_display("other_key".to_string(), Some("other_value".to_string()));
92
93        // Set a cache with "test" prefix
94        state
95            .cache
96            .set_display("test_key".to_string(), Some("new_value".to_string()));
97
98        // Trigger event
99        state.publish_event(StateEvent::VariableChanged("test".to_string()));
100
101        // The key with "test" prefix should be cleared
102        assert_eq!(state.cache.get_display("test_key"), None);
103
104        // But other keys should remain
105        assert_eq!(
106            state.cache.get_display("other_key"),
107            Some(Some("other_value".to_string()))
108        );
109    }
110
111    #[test]
112    fn test_set_variable_publishes_event() {
113        let config = Config::default();
114        let state = AppState::builder(&config).build();
115
116        let event_count = Arc::new(AtomicUsize::new(0));
117        let subscriber = Arc::new(TestSubscriber {
118            event_count: event_count.clone(),
119        });
120
121        let _ = state.subscribe(subscriber);
122
123        // Setting a variable should publish an event
124        let _ = state.set_variable("x".to_string(), 10.0, None);
125
126        assert_eq!(event_count.load(Ordering::SeqCst), 1);
127    }
128
129    #[test]
130    fn test_add_history_publishes_event() {
131        let config = Config::default();
132        let state = AppState::builder(&config).build();
133
134        let event_count = Arc::new(AtomicUsize::new(0));
135        let subscriber = Arc::new(TestSubscriber {
136            event_count: event_count.clone(),
137        });
138
139        let _ = state.subscribe(subscriber);
140
141        // Adding to history should publish an event
142        let _ = state.add_history(42.0, None);
143
144        assert_eq!(event_count.load(Ordering::SeqCst), 1);
145    }
146
147    #[test]
148    fn test_multiple_subscribers() {
149        let config = Config::default();
150        let state = AppState::builder(&config).build();
151
152        let count1 = Arc::new(AtomicUsize::new(0));
153        let count2 = Arc::new(AtomicUsize::new(0));
154
155        let sub1 = Arc::new(TestSubscriber {
156            event_count: count1.clone(),
157        });
158        let sub2 = Arc::new(TestSubscriber {
159            event_count: count2.clone(),
160        });
161
162        let _ = state.subscribe(sub1);
163        let _ = state.subscribe(sub2);
164
165        state.publish_event(StateEvent::HistoryAdded(42.0));
166
167        assert_eq!(count1.load(Ordering::SeqCst), 1);
168        assert_eq!(count2.load(Ordering::SeqCst), 1);
169    }
170}
171
172// C FFI API for Swift integration
173
174use once_cell::sync::Lazy;
175use std::ffi::{CStr, CString};
176use std::os::raw::c_char;
177use std::path::PathBuf;
178use std::sync::Mutex;
179
180static CONFIG_OVERRIDE_PATH: Lazy<Mutex<Option<PathBuf>>> = Lazy::new(|| Mutex::new(None));
181static CONFIG_CACHE: Lazy<Mutex<Option<crate::config::Config>>> = Lazy::new(|| Mutex::new(None));
182
183fn set_config_override_path(path: PathBuf) {
184    if let Ok(mut guard) = CONFIG_OVERRIDE_PATH.lock() {
185        *guard = Some(path);
186    }
187}
188
189fn get_config_override_path() -> Option<PathBuf> {
190    CONFIG_OVERRIDE_PATH
191        .lock()
192        .ok()
193        .and_then(|guard| guard.clone())
194}
195
196fn set_config_cache(config: crate::config::Config) {
197    if let Ok(mut guard) = CONFIG_CACHE.lock() {
198        *guard = Some(config);
199    }
200}
201
202fn clear_config_cache() {
203    if let Ok(mut guard) = CONFIG_CACHE.lock() {
204        *guard = None;
205    }
206}
207
208fn get_cached_config() -> crate::config::Config {
209    if let Ok(guard) = CONFIG_CACHE.lock() {
210        if let Some(cfg) = guard.as_ref() {
211            return cfg.clone();
212        }
213    }
214    let cfg = crate::config::load_config();
215    if let Ok(mut guard) = CONFIG_CACHE.lock() {
216        *guard = Some(cfg.clone());
217    }
218    cfg
219}
220
221type NumbyContext = crate::models::AppState; // Use AppState as context
222
223#[repr(C)]
224pub struct NumbyHighlightSpan {
225    pub start: u32,
226    pub len: u32,
227    pub kind: u8,
228    pub _pad: [u8; 3],
229}
230
231#[no_mangle]
232pub extern "C" fn libnumby_context_new() -> *mut NumbyContext {
233    let config = get_cached_config();
234    Box::into_raw(Box::new(crate::models::AppState::builder(&config).build()))
235}
236
237/// # Safety
238///
239/// This function dereferences raw pointers and must be called with valid pointers.
240#[no_mangle]
241pub unsafe extern "C" fn libnumby_evaluate(
242    ctx: *mut NumbyContext,
243    input: *const c_char,
244    out_formatted: *mut *mut c_char,
245    out_unit: *mut *mut c_char,
246    out_error: *mut *mut c_char,
247) -> f64 {
248    // Validate all pointers
249    if ctx.is_null()
250        || input.is_null()
251        || out_formatted.is_null()
252        || out_unit.is_null()
253        || out_error.is_null()
254    {
255        if !out_error.is_null() {
256            if let Ok(s) = CString::new("Invalid null pointer") {
257                *out_error = s.into_raw();
258            }
259        }
260        return 0.0;
261    }
262
263    // Convert C string to Rust string with validation
264    let input_str = match CStr::from_ptr(input).to_str() {
265        Ok(s) => s,
266        Err(_) => {
267            if let Ok(s) = CString::new("Invalid UTF-8 input") {
268                *out_error = s.into_raw();
269            }
270            return 0.0;
271        }
272    };
273
274    // Validate input size
275    if let Err(e) = crate::security::validate_input_size(input_str) {
276        if let Ok(s) = CString::new(e) {
277            *out_error = s.into_raw();
278        }
279        return 0.0;
280    }
281
282    let context = &mut *ctx;
283    let config = crate::config::Config::default();
284
285    let registry = match crate::evaluator::AgentRegistry::new(&config) {
286        Ok(r) => r,
287        Err(_) => {
288            if let Ok(s) = CString::new("Failed to initialize registry") {
289                *out_error = s.into_raw();
290            }
291            return 0.0;
292        }
293    };
294
295    match registry.evaluate(input_str, context) {
296        Some((result_str, _)) => {
297            // Parse result_str, e.g., "3.11 miles" -> value=3.11, formatted="3.11 miles", unit="miles"
298            let parts: Vec<&str> = result_str.split_whitespace().collect();
299            let value = parts
300                .first()
301                .and_then(|s| crate::conversions::parse_number_with_scale(s))
302                .unwrap_or(0.0);
303
304            // Safe string conversion
305            if let Ok(formatted_cstr) = CString::new(result_str.clone()) {
306                *out_formatted = formatted_cstr.into_raw();
307            }
308
309            if parts.len() > 1 {
310                let unit_str = parts[1..].join(" ");
311                if let Ok(unit_cstr) = CString::new(unit_str) {
312                    *out_unit = unit_cstr.into_raw();
313                }
314            }
315
316            value
317        }
318        None => {
319            if let Ok(s) = CString::new("Evaluation failed") {
320                *out_error = s.into_raw();
321            }
322            0.0
323        }
324    }
325}
326
327/// # Safety
328///
329/// This function dereferences raw pointers and must be called with valid pointers.
330#[no_mangle]
331pub unsafe extern "C" fn libnumby_set_variable(
332    ctx: *mut NumbyContext,
333    name: *const c_char,
334    value: f64,
335    unit: *const c_char,
336) -> i32 {
337    if ctx.is_null() || name.is_null() {
338        return -1;
339    }
340
341    let name_str = match CStr::from_ptr(name).to_str() {
342        Ok(s) => s,
343        Err(_) => return -1,
344    };
345
346    let unit_str = if unit.is_null() {
347        None
348    } else {
349        CStr::from_ptr(unit).to_str().ok().map(|s| s.to_string())
350    };
351
352    let context = &mut *ctx;
353    match context.set_variable(name_str.to_string(), value, unit_str) {
354        Ok(_) => 0,
355        Err(_) => -1,
356    }
357}
358
359/// # Safety
360///
361/// This function dereferences raw pointers and must be called with valid pointers.
362#[no_mangle]
363pub unsafe extern "C" fn libnumby_load_config(ctx: *mut NumbyContext, path: *const c_char) -> i32 {
364    if ctx.is_null() || path.is_null() {
365        return -1;
366    }
367
368    let path_str = match CStr::from_ptr(path).to_str() {
369        Ok(s) => s,
370        Err(_) => return -1,
371    };
372
373    // Validate path length
374    if path_str.len() > 4096 {
375        return -1;
376    }
377
378    // Validate path to prevent path traversal
379    let validated_path = match crate::security::validate_file_path(path_str) {
380        Ok(p) => p,
381        Err(_) => return -1,
382    };
383
384    // Load config from validated file
385    match std::fs::read_to_string(&validated_path) {
386        Ok(contents) => {
387            // Check file size limit (1MB max for config)
388            if contents.len() > 1_048_576 {
389                return -1;
390            }
391
392            match serde_json::from_str::<crate::config::Config>(&contents) {
393                Ok(config) => {
394                    let context = &mut *ctx;
395                    set_config_cache(config.clone());
396                    // Update context with new config values
397                    context.length_units = config.length_units;
398                    context.time_units = config.time_units;
399                    context.temperature_units = config.temperature_units;
400                    context.area_units = config.area_units;
401                    context.volume_units = config.volume_units;
402                    context.weight_units = config.weight_units;
403                    context.angular_units = config.angular_units;
404                    context.data_units = config.data_units;
405                    context.speed_units = config.speed_units;
406                    context.rates = config.currencies;
407                    context.number_format = config.number_format;
408                    context.number_max_decimals = config.number_max_decimals;
409                    set_config_override_path(validated_path.clone());
410                    crate::config::set_config_path_override(
411                        validated_path.to_string_lossy().as_ref(),
412                    );
413                    0
414                }
415                Err(_) => -1,
416            }
417        }
418        Err(_) => -1,
419    }
420}
421
422/// # Safety
423///
424/// This function dereferences raw pointers and must be called with valid pointers.
425#[no_mangle]
426pub unsafe extern "C" fn libnumby_set_locale(ctx: *mut NumbyContext, locale: *const c_char) -> i32 {
427    if ctx.is_null() || locale.is_null() {
428        return -1;
429    }
430
431    let locale_str = match CStr::from_ptr(locale).to_str() {
432        Ok(s) => s,
433        Err(_) => return -1,
434    };
435
436    // Set the locale using i18n module
437    match crate::i18n::set_locale(locale_str) {
438        Ok(_) => 0,
439        Err(_) => -1,
440    }
441}
442
443/// # Safety
444///
445/// This function dereferences raw pointers and must be called with valid pointers.
446#[no_mangle]
447pub unsafe extern "C" fn libnumby_set_number_format(
448    ctx: *mut NumbyContext,
449    format: *const c_char,
450    max_decimals: i32,
451) -> i32 {
452    if ctx.is_null() || format.is_null() {
453        return -1;
454    }
455
456    let format_str = match CStr::from_ptr(format).to_str() {
457        Ok(s) => s,
458        Err(_) => return -1,
459    };
460
461    let normalized = match crate::prettify::normalize_number_format(format_str) {
462        Some(val) => val,
463        None => return -1,
464    };
465
466    let max_decimals = if max_decimals < 0 {
467        return -1;
468    } else {
469        crate::prettify::clamp_max_decimals(max_decimals as usize)
470    };
471
472    let context = &mut *ctx;
473    context.number_format = normalized.to_string();
474    context.number_max_decimals = max_decimals;
475    0
476}
477
478/// Get the current locale
479///
480/// # Safety
481///
482/// Returns a C string that must be freed with libnumby_free_string
483#[no_mangle]
484pub unsafe extern "C" fn libnumby_get_locale() -> *mut c_char {
485    let locale = crate::i18n::get_locale();
486    CString::new(locale.to_string())
487        .map(|s| s.into_raw())
488        .unwrap_or(std::ptr::null_mut())
489}
490
491/// Get the number of available locales
492///
493/// # Safety
494///
495/// This function is safe to call
496#[no_mangle]
497pub unsafe extern "C" fn libnumby_get_locales_count() -> i32 {
498    crate::i18n::AVAILABLE_LOCALES.len() as i32
499}
500
501/// Get locale code at index
502///
503/// # Safety
504///
505/// Returns a C string that must be freed with libnumby_free_string
506#[no_mangle]
507pub unsafe extern "C" fn libnumby_get_locale_code(index: i32) -> *mut c_char {
508    let locales = crate::i18n::AVAILABLE_LOCALES;
509    if index < 0 || index >= locales.len() as i32 {
510        return std::ptr::null_mut();
511    }
512
513    let (locale, _) = locales[index as usize];
514    CString::new(locale)
515        .map(|s| s.into_raw())
516        .unwrap_or(std::ptr::null_mut())
517}
518
519/// Get locale display name at index
520///
521/// # Safety
522///
523/// Returns a C string that must be freed with libnumby_free_string
524#[no_mangle]
525pub unsafe extern "C" fn libnumby_get_locale_name(index: i32) -> *mut c_char {
526    let locales = crate::i18n::AVAILABLE_LOCALES;
527    if index < 0 || index >= locales.len() as i32 {
528        return std::ptr::null_mut();
529    }
530
531    let (_, display_name) = locales[index as usize];
532    CString::new(display_name)
533        .map(|s| s.into_raw())
534        .unwrap_or(std::ptr::null_mut())
535}
536
537/// # Safety
538///
539/// This function takes ownership of the raw pointer and frees it.
540#[no_mangle]
541pub unsafe extern "C" fn libnumby_free_string(s: *mut c_char) {
542    if !s.is_null() {
543        let _ = CString::from_raw(s);
544    }
545}
546
547/// Returns a heap-allocated array of highlight spans.
548/// Caller must free using libnumby_free_highlight_spans.
549///
550/// # Safety
551///
552/// This function dereferences raw pointers and must be called with valid pointers.
553#[no_mangle]
554pub unsafe extern "C" fn libnumby_highlight_spans(
555    ctx: *mut NumbyContext,
556    input: *const c_char,
557    out_len: *mut u32,
558) -> *mut NumbyHighlightSpan {
559    if out_len.is_null() {
560        return std::ptr::null_mut();
561    }
562    *out_len = 0;
563
564    if ctx.is_null() || input.is_null() {
565        return std::ptr::null_mut();
566    }
567
568    let input_str = match CStr::from_ptr(input).to_str() {
569        Ok(s) => s,
570        Err(_) => return std::ptr::null_mut(),
571    };
572
573    if crate::security::validate_highlight_input_size(input_str).is_err() {
574        return std::ptr::null_mut();
575    }
576
577    let context = &mut *ctx;
578    let config = get_cached_config();
579    let spans = crate::highlight::highlight_spans(input_str, context, &config);
580
581    let mut out: Vec<NumbyHighlightSpan> = Vec::with_capacity(spans.len());
582    for span in spans {
583        out.push(NumbyHighlightSpan {
584            start: span.start,
585            len: span.len,
586            kind: span.kind as u8,
587            _pad: [0; 3],
588        });
589    }
590
591    let mut boxed = out.into_boxed_slice();
592    let ptr = boxed.as_mut_ptr();
593    let len = boxed.len() as u32;
594    std::mem::forget(boxed);
595    *out_len = len;
596    ptr
597}
598
599/// Returns the start/end line indices for the multiline group containing the cursor.
600///
601/// Cursor is provided as a UTF-16 code unit offset (matching Cocoa text views).
602///
603/// # Safety
604///
605/// This function dereferences raw pointers and must be called with valid pointers.
606#[no_mangle]
607pub unsafe extern "C" fn libnumby_group_bounds_for_cursor(
608    input: *const c_char,
609    cursor_utf16: i32,
610    out_start: *mut i32,
611    out_end: *mut i32,
612) -> i32 {
613    if input.is_null() || out_start.is_null() || out_end.is_null() || cursor_utf16 < 0 {
614        return -1;
615    }
616
617    let input_str = match CStr::from_ptr(input).to_str() {
618        Ok(s) => s,
619        Err(_) => return -1,
620    };
621
622    if crate::security::validate_highlight_input_size(input_str).is_err() {
623        return -1;
624    }
625
626    let cursor = cursor_utf16 as usize;
627    let mut line_index: usize = 0;
628    for (idx, unit) in input_str.encode_utf16().enumerate() {
629        if idx >= cursor {
630            break;
631        }
632        if unit == b'\n' as u16 {
633            line_index += 1;
634        }
635    }
636
637    let lines: Vec<String> = input_str.split('\n').map(|line| line.to_string()).collect();
638    let (start, end) = crate::line_groups::group_bounds_for_line(&lines, line_index);
639    *out_start = start as i32;
640    *out_end = end as i32;
641    0
642}
643
644/// Returns the multiline group expression containing the cursor.
645///
646/// Cursor is provided as a UTF-16 code unit offset (matching Cocoa text views).
647/// Returns a C string that must be freed with libnumby_free_string. Outputs start/end line indices.
648///
649/// # Safety
650///
651/// This function dereferences raw pointers and must be called with valid pointers.
652#[no_mangle]
653pub unsafe extern "C" fn libnumby_group_expr_for_cursor(
654    input: *const c_char,
655    cursor_utf16: i32,
656    out_start: *mut i32,
657    out_end: *mut i32,
658) -> *mut c_char {
659    if input.is_null() || out_start.is_null() || out_end.is_null() || cursor_utf16 < 0 {
660        return std::ptr::null_mut();
661    }
662
663    let input_str = match CStr::from_ptr(input).to_str() {
664        Ok(s) => s,
665        Err(_) => return std::ptr::null_mut(),
666    };
667
668    if crate::security::validate_highlight_input_size(input_str).is_err() {
669        return std::ptr::null_mut();
670    }
671
672    let cursor = cursor_utf16 as usize;
673    let mut line_index: usize = 0;
674    for (idx, unit) in input_str.encode_utf16().enumerate() {
675        if idx >= cursor {
676            break;
677        }
678        if unit == b'\n' as u16 {
679            line_index += 1;
680        }
681    }
682
683    let lines: Vec<String> = input_str.split('\n').map(|line| line.to_string()).collect();
684    let groups = crate::line_groups::group_multiline_expressions(&lines);
685    for group in groups {
686        if line_index >= group.start && line_index <= group.end {
687            *out_start = group.start as i32;
688            *out_end = group.end as i32;
689            return CString::new(group.expr)
690                .map(|s| s.into_raw())
691                .unwrap_or(std::ptr::null_mut());
692        }
693    }
694
695    *out_start = line_index as i32;
696    *out_end = line_index as i32;
697    std::ptr::null_mut()
698}
699
700/// Frees highlight spans returned by libnumby_highlight_spans.
701///
702/// # Safety
703///
704/// This function takes ownership of the raw pointer and frees it.
705#[no_mangle]
706pub unsafe extern "C" fn libnumby_free_highlight_spans(ptr: *mut NumbyHighlightSpan, len: u32) {
707    if ptr.is_null() || len == 0 {
708        return;
709    }
710    let _ = Box::from_raw(std::ptr::slice_from_raw_parts_mut(ptr, len as usize));
711}
712
713/// # Safety
714///
715/// This function dereferences raw pointers and must be called with valid pointers.
716#[no_mangle]
717pub unsafe extern "C" fn libnumby_clear_history(ctx: *mut NumbyContext) -> i32 {
718    if ctx.is_null() {
719        return -1;
720    }
721
722    let context = &mut *ctx;
723    match context.history.write() {
724        Ok(mut history) => {
725            history.clear();
726            0
727        }
728        Err(_) => -1,
729    }
730}
731
732/// Clear all variables from the context
733///
734/// # Safety
735///
736/// This function dereferences raw pointers and must be called with valid pointers.
737#[no_mangle]
738pub unsafe extern "C" fn libnumby_clear_variables(ctx: *mut NumbyContext) -> i32 {
739    if ctx.is_null() {
740        return -1;
741    }
742
743    let context = &mut *ctx;
744    match context.variables.write() {
745        Ok(mut variables) => {
746            variables.clear();
747            0
748        }
749        Err(_) => -1,
750    }
751}
752
753/// # Safety
754///
755/// This function dereferences raw pointers and must be called with valid pointers.
756#[no_mangle]
757pub unsafe extern "C" fn libnumby_get_history_count(ctx: *mut NumbyContext) -> i32 {
758    if ctx.is_null() {
759        return -1;
760    }
761
762    let context = &*ctx;
763    match context.history.read() {
764        Ok(history) => history.len() as i32,
765        Err(_) => -1,
766    }
767}
768
769/// # Safety
770///
771/// This function takes ownership of the raw pointer and frees it.
772#[no_mangle]
773pub unsafe extern "C" fn libnumby_context_free(ctx: *mut NumbyContext) {
774    if !ctx.is_null() {
775        drop(Box::from_raw(ctx));
776    }
777}
778
779/// Fetches latest currency rates from the API and updates the config file
780///
781/// Returns 0 on success, -1 on failure
782/// On success, updates both the config file and the context's rates
783///
784/// # Safety
785///
786/// This function dereferences raw pointers and must be called with valid pointers.
787#[no_mangle]
788pub unsafe extern "C" fn libnumby_update_currency_rates(ctx: *mut NumbyContext) -> i32 {
789    if ctx.is_null() {
790        return -1;
791    }
792
793    // Fetch rates from API
794    let (rates, date) = match crate::currency_fetcher::fetch_latest_rates() {
795        Ok(result) => result,
796        Err(_) => return -1,
797    };
798
799    // Determine candidate paths (override first, fallback to default)
800    let mut candidate_paths = Vec::new();
801    if let Some(path) = get_config_override_path() {
802        candidate_paths.push(path);
803    }
804    let default_path = crate::config::get_config_path();
805    if candidate_paths
806        .first()
807        .map(|p| p != &default_path)
808        .unwrap_or(true)
809    {
810        candidate_paths.push(default_path);
811    }
812
813    let mut persisted_path: Option<PathBuf> = None;
814    for path in candidate_paths {
815        match crate::config::update_currency_rates_at_path(&path, rates.clone(), date.clone()) {
816            Ok(_) => {
817                persisted_path = Some(path);
818                break;
819            }
820            Err(_) => continue,
821        }
822    }
823
824    let Some(saved_path) = persisted_path else {
825        return -1;
826    };
827
828    set_config_override_path(saved_path.clone());
829    crate::config::set_config_path_override(saved_path.to_string_lossy().as_ref());
830    clear_config_cache();
831
832    // Update context with new rates
833    let context = &mut *ctx;
834    context.rates = rates;
835
836    0
837}
838
839/// Returns the default config path used by the Rust core.
840#[no_mangle]
841pub extern "C" fn libnumby_get_default_config_path() -> *mut c_char {
842    let path = crate::config::get_config_path();
843    match CString::new(path.to_string_lossy().to_string()) {
844        Ok(cstr) => cstr.into_raw(),
845        Err(_) => std::ptr::null_mut(),
846    }
847}
848
849/// Sets currency rates from JSON data provided by the caller (e.g., from Swift URLSession)
850///
851/// Expected JSON format: {"date": "2025-01-01", "usd": {"eur": 0.92, "gbp": 0.79, ...}}
852///
853/// Returns 0 on success, -1 on failure
854///
855/// # Safety
856///
857/// This function dereferences raw pointers and must be called with valid pointers.
858#[no_mangle]
859pub unsafe extern "C" fn libnumby_set_currency_rates_json(
860    ctx: *mut NumbyContext,
861    json_data: *const c_char,
862) -> i32 {
863    if ctx.is_null() || json_data.is_null() {
864        return -1;
865    }
866
867    let json_str = match CStr::from_ptr(json_data).to_str() {
868        Ok(s) => s,
869        Err(_) => return -1,
870    };
871
872    // Parse JSON in the same format as the currency API
873    #[derive(serde::Deserialize)]
874    struct CurrencyApiResponse {
875        date: String,
876        usd: std::collections::HashMap<String, f64>,
877    }
878
879    let api_response: CurrencyApiResponse = match serde_json::from_str(json_str) {
880        Ok(r) => r,
881        Err(_) => return -1,
882    };
883
884    // Convert to uppercase keys
885    let mut rates: std::collections::HashMap<String, f64> = std::collections::HashMap::new();
886    rates.insert("USD".to_string(), 1.0);
887    for (currency_code, rate) in api_response.usd {
888        rates.insert(currency_code.to_uppercase(), rate);
889    }
890
891    let api_date = api_response.date;
892
893    // Update config file with both API date and current fetch timestamp
894    let config_path = get_config_override_path().unwrap_or_else(crate::config::get_config_path);
895    if crate::config::update_currency_rates_at_path(&config_path, rates.clone(), api_date).is_err()
896    {
897        return -1;
898    }
899    crate::config::set_config_path_override(config_path.to_string_lossy().as_ref());
900    clear_config_cache();
901
902    // Update context
903    let context = &mut *ctx;
904    context.rates = rates;
905
906    0
907}
908
909/// Checks if currency rates are stale (older than 24 hours)
910///
911/// Returns 1 if stale, 0 if fresh, -1 on error
912///
913/// # Safety
914///
915/// This function is safe to call from C code.
916#[no_mangle]
917pub extern "C" fn libnumby_are_rates_stale() -> i32 {
918    let config = crate::config::load_config();
919    match config.rates_updated_at {
920        Some(date) => {
921            if crate::currency_fetcher::are_rates_stale(&date) {
922                1 // Stale
923            } else {
924                0 // Fresh
925            }
926        }
927        None => 1, // No date = stale
928    }
929}
930
931/// Gets the last update date for currency rates (when we last fetched)
932///
933/// Returns a C string with the date in YYYY-MM-DD format, or null if unavailable
934/// Caller must free the returned string with libnumby_free_string
935///
936/// # Safety
937///
938/// This function is safe to call from C code.
939#[no_mangle]
940pub extern "C" fn libnumby_get_rates_update_date() -> *mut c_char {
941    let config = crate::config::load_config();
942    match config.rates_updated_at {
943        Some(date) => {
944            if let Ok(cstr) = CString::new(date) {
945                cstr.into_raw()
946            } else {
947                std::ptr::null_mut()
948            }
949        }
950        None => std::ptr::null_mut(),
951    }
952}
953
954/// Gets the API rates date (when the rates were published by the API)
955///
956/// Returns a C string with the date in YYYY-MM-DD format, or null if unavailable
957/// Caller must free the returned string with libnumby_free_string
958///
959/// # Safety
960///
961/// This function is safe to call from C code.
962#[no_mangle]
963pub extern "C" fn libnumby_get_api_rates_date() -> *mut c_char {
964    let config = crate::config::load_config();
965    match config.api_rates_date {
966        Some(date) => {
967            if let Ok(cstr) = CString::new(date) {
968                cstr.into_raw()
969            } else {
970                std::ptr::null_mut()
971            }
972        }
973        None => std::ptr::null_mut(),
974    }
975}
976
977#[cfg(test)]
978mod i18n_tests {
979    // NOTE: These tests modify global locale state and should be run with:
980    // cargo test --lib i18n -- --test-threads=1
981    use crate::i18n;
982
983    #[test]
984    fn test_locale_detection() {
985        // Init with default
986        i18n::init_locale(None);
987        let locale = i18n::get_locale();
988        // Should be either system locale or en-US fallback
989        assert!(!locale.to_string().is_empty());
990    }
991
992    #[test]
993    fn test_init_locale_english() {
994        i18n::init_locale(Some("en-US"));
995        let locale = i18n::get_locale();
996        assert_eq!(locale.to_string(), "en-US");
997    }
998
999    #[test]
1000    fn test_init_locale_spanish() {
1001        i18n::init_locale(Some("es"));
1002        let locale = i18n::get_locale();
1003        assert_eq!(locale.to_string(), "es");
1004    }
1005
1006    #[test]
1007    fn test_init_locale_chinese() {
1008        i18n::init_locale(Some("zh-CN"));
1009        let locale = i18n::get_locale();
1010        assert_eq!(locale.to_string(), "zh-CN");
1011    }
1012
1013    #[test]
1014    fn test_fl_macro_simple() {
1015        i18n::init_locale(Some("en-US"));
1016        let msg = crate::fl!("app-description");
1017        assert!(msg.contains("Numby"));
1018        assert!(msg.contains("calculator"));
1019    }
1020
1021    #[test]
1022    fn test_fl_macro_with_args() {
1023        i18n::init_locale(Some("en-US"));
1024        let msg = crate::fl!("version-output", "version" => "0.1.0");
1025        assert!(msg.contains("0.1.0"));
1026    }
1027
1028    #[test]
1029    fn test_english_error_message() {
1030        i18n::init_locale(Some("en-US"));
1031        let msg = crate::fl!("error-evaluating-expression");
1032        assert_eq!(msg, "Error evaluating expression");
1033    }
1034
1035    #[test]
1036    fn test_spanish_error_message() {
1037        i18n::init_locale(Some("es"));
1038        let msg = crate::fl!("error-evaluating-expression");
1039        assert_eq!(msg, "Error al evaluar la expresión");
1040    }
1041
1042    #[test]
1043    fn test_chinese_error_message() {
1044        i18n::init_locale(Some("zh-CN"));
1045        let msg = crate::fl!("error-evaluating-expression");
1046        assert_eq!(msg, "求值表达式时出错");
1047    }
1048
1049    #[test]
1050    fn test_english_security_messages() {
1051        i18n::init_locale(Some("en-US"));
1052        // Re-check locale was actually set
1053        assert_eq!(i18n::get_locale().to_string(), "en-US");
1054        let msg1 = crate::fl!("path-traversal-detected");
1055        let msg2 = crate::fl!("invalid-path");
1056        assert_eq!(
1057            msg1, "Path traversal detected",
1058            "Expected English, got: {}",
1059            msg1
1060        );
1061        assert_eq!(msg2, "Invalid path", "Expected English, got: {}", msg2);
1062    }
1063
1064    #[test]
1065    fn test_spanish_security_messages() {
1066        i18n::init_locale(Some("es"));
1067        assert_eq!(i18n::get_locale().to_string(), "es");
1068        let msg1 = crate::fl!("path-traversal-detected");
1069        let msg2 = crate::fl!("invalid-path");
1070        assert_eq!(
1071            msg1, "Se detectó un recorrido de ruta",
1072            "Expected Spanish, got: {}",
1073            msg1
1074        );
1075        assert_eq!(msg2, "Ruta inválida", "Expected Spanish, got: {}", msg2);
1076    }
1077
1078    #[test]
1079    fn test_chinese_security_messages() {
1080        i18n::init_locale(Some("zh-CN"));
1081        assert_eq!(i18n::get_locale().to_string(), "zh-CN");
1082        let msg1 = crate::fl!("path-traversal-detected");
1083        let msg2 = crate::fl!("invalid-path");
1084        assert_eq!(msg1, "检测到路径遍历", "Expected Chinese, got: {}", msg1);
1085        assert_eq!(msg2, "无效路径", "Expected Chinese, got: {}", msg2);
1086    }
1087
1088    #[test]
1089    fn test_english_tui_messages() {
1090        i18n::init_locale(Some("en-US"));
1091        assert_eq!(i18n::get_locale().to_string(), "en-US");
1092        let msg = crate::fl!("commands-help");
1093        assert!(
1094            msg.contains("quit"),
1095            "Expected 'quit' in English message, got: {}",
1096            msg
1097        );
1098        assert!(
1099            msg.contains("save"),
1100            "Expected 'save' in English message, got: {}",
1101            msg
1102        );
1103    }
1104
1105    #[test]
1106    fn test_spanish_tui_messages() {
1107        i18n::init_locale(Some("es"));
1108        assert_eq!(i18n::get_locale().to_string(), "es");
1109        let msg = crate::fl!("commands-help");
1110        assert!(
1111            msg.contains("salir"),
1112            "Expected 'salir' in Spanish message, got: {}",
1113            msg
1114        );
1115        assert!(
1116            msg.contains("guardar"),
1117            "Expected 'guardar' in Spanish message, got: {}",
1118            msg
1119        );
1120    }
1121
1122    #[test]
1123    fn test_chinese_tui_messages() {
1124        i18n::init_locale(Some("zh-CN"));
1125        assert_eq!(i18n::get_locale().to_string(), "zh-CN");
1126        let msg = crate::fl!("commands-help");
1127        assert!(
1128            msg.contains("退出"),
1129            "Expected '退出' in Chinese message, got: {}",
1130            msg
1131        );
1132        assert!(
1133            msg.contains("保存"),
1134            "Expected '保存' in Chinese message, got: {}",
1135            msg
1136        );
1137    }
1138
1139    #[test]
1140    fn test_message_with_variable() {
1141        i18n::init_locale(Some("en-US"));
1142        assert_eq!(i18n::get_locale().to_string(), "en-US");
1143        let msg = crate::fl!("input-too-long", "actual" => "150000", "max" => "100000");
1144        assert!(msg.contains("150000"));
1145        assert!(msg.contains("100000"));
1146        assert!(
1147            msg.contains("chars"),
1148            "Expected 'chars' in English message, got: {}",
1149            msg
1150        );
1151    }
1152
1153    #[test]
1154    fn test_spanish_message_with_variable() {
1155        i18n::init_locale(Some("es"));
1156        assert_eq!(i18n::get_locale().to_string(), "es");
1157        let msg = crate::fl!("input-too-long", "actual" => "150000", "max" => "100000");
1158        assert!(msg.contains("150000"));
1159        assert!(msg.contains("100000"));
1160        assert!(
1161            msg.contains("caracteres"),
1162            "Expected 'caracteres' in Spanish message, got: {}",
1163            msg
1164        );
1165    }
1166
1167    #[test]
1168    fn test_chinese_message_with_variable() {
1169        i18n::init_locale(Some("zh-CN"));
1170        assert_eq!(i18n::get_locale().to_string(), "zh-CN");
1171        let msg = crate::fl!("input-too-long", "actual" => "150000", "max" => "100000");
1172        assert!(msg.contains("150000"));
1173        assert!(msg.contains("100000"));
1174        assert!(
1175            msg.contains("字符"),
1176            "Expected '字符' in Chinese message, got: {}",
1177            msg
1178        );
1179    }
1180
1181    #[test]
1182    fn test_fallback_for_missing_key() {
1183        i18n::init_locale(Some("en-US"));
1184        let msg = crate::fl!("non-existent-key");
1185        // Should return the key itself as fallback
1186        assert_eq!(msg, "non-existent-key");
1187    }
1188}
1189
1190/// Return the common completion suffix for the variable at a UTF-16 cursor offset.
1191/// The caller frees the returned string with libnumby_free_string.
1192///
1193/// # Safety
1194/// ctx must be a valid context. input must be a valid NUL-terminated UTF-8 string.
1195#[no_mangle]
1196pub unsafe extern "C" fn libnumby_complete_variable(
1197    ctx: *mut NumbyContext,
1198    input: *const c_char,
1199    cursor_utf16: u32,
1200) -> *mut c_char {
1201    if ctx.is_null() || input.is_null() {
1202        return std::ptr::null_mut();
1203    }
1204    let Ok(input) = CStr::from_ptr(input).to_str() else {
1205        return std::ptr::null_mut();
1206    };
1207    if crate::security::validate_input_size(input).is_err() {
1208        return std::ptr::null_mut();
1209    }
1210    let mut utf16 = 0usize;
1211    let cursor = input
1212        .char_indices()
1213        .map(|(i, c)| (i, Some(c)))
1214        .chain(std::iter::once((input.len(), None)))
1215        .find_map(|(i, c)| {
1216            if utf16 == cursor_utf16 as usize {
1217                return Some(i);
1218            }
1219            utf16 += c.map_or(0, char::len_utf16);
1220            None
1221        });
1222    let Some(cursor) = cursor else {
1223        return std::ptr::null_mut();
1224    };
1225    let config = get_cached_config();
1226    crate::completion::variable_suffix(input, cursor, &*ctx, &config)
1227        .and_then(|suffix| CString::new(suffix).ok())
1228        .map_or(std::ptr::null_mut(), CString::into_raw)
1229}