switchy_env 0.3.0

Switchy Environment Variables package
Documentation
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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
//! Simulator environment for testing.
//!
//! This module provides a configurable environment with deterministic defaults
//! for testing. It maintains its own set of environment variables separate from
//! the system environment, allowing for controlled and reproducible tests.
//!
//! The simulator automatically initializes with real environment variables and
//! adds simulator-specific defaults for common configuration values.
//!
//! # Examples
//!
//! ```rust
//! # #[cfg(feature = "simulator")]
//! # {
//! use switchy_env::simulator::{set_var, var, reset};
//!
//! // Set a test variable
//! set_var("DATABASE_URL", "sqlite::memory:");
//!
//! // Access it like normal
//! let db_url = var("DATABASE_URL").unwrap();
//! assert_eq!(db_url, "sqlite::memory:");
//!
//! // Reset to defaults
//! reset();
//! # }
//! ```

use crate::{EnvError, EnvProvider, Result};
use std::collections::BTreeMap;
use std::sync::{Arc, RwLock};

/// Simulator environment provider with configurable variables
pub struct SimulatorEnv {
    vars: Arc<RwLock<BTreeMap<String, String>>>,
}

impl SimulatorEnv {
    /// Creates a new simulator environment provider with default values
    ///
    /// Initializes the environment with real environment variables and adds
    /// simulator-specific defaults for testing and deterministic behavior.
    #[must_use]
    pub fn new() -> Self {
        let mut vars = BTreeMap::new();

        // Load real environment variables as defaults
        for (key, value) in std::env::vars() {
            vars.insert(key, value);
        }

        // Override with simulator-specific defaults
        Self::set_simulator_defaults(&mut vars);

        Self {
            vars: Arc::new(RwLock::new(vars)),
        }
    }

    /// Set a variable for testing
    ///
    /// # Panics
    ///
    /// * If the internal `RwLock` is poisoned
    pub fn set_var(&self, name: &str, value: &str) {
        let mut vars = self.vars.write().unwrap();
        vars.insert(name.to_string(), value.to_string());
    }

    /// Remove a variable
    ///
    /// # Panics
    ///
    /// * If the internal `RwLock` is poisoned
    pub fn remove_var(&self, name: &str) {
        let mut vars = self.vars.write().unwrap();
        vars.remove(name);
    }

    /// Clear all variables
    ///
    /// # Panics
    ///
    /// * If the internal `RwLock` is poisoned
    pub fn clear(&self) {
        let mut vars = self.vars.write().unwrap();
        vars.clear();
    }

    /// Reset to defaults
    ///
    /// # Panics
    ///
    /// * If the internal `RwLock` is poisoned
    pub fn reset(&self) {
        let mut vars = self.vars.write().unwrap();
        vars.clear();

        // Reload real environment variables
        for (key, value) in std::env::vars() {
            vars.insert(key, value);
        }
        drop(vars);

        // Reacquire lock for setting defaults
        let mut vars = self.vars.write().unwrap();
        Self::set_simulator_defaults(&mut vars);
    }

    fn set_simulator_defaults(vars: &mut BTreeMap<String, String>) {
        // Set deterministic defaults for common variables
        vars.entry("SIMULATOR_SEED".to_string())
            .or_insert_with(|| "12345".to_string());
        vars.entry("SIMULATOR_UUID_SEED".to_string())
            .or_insert_with(|| "54321".to_string());
        vars.entry("SIMULATOR_EPOCH_OFFSET".to_string())
            .or_insert_with(|| "0".to_string());
        vars.entry("SIMULATOR_STEP_MULTIPLIER".to_string())
            .or_insert_with(|| "1".to_string());
        vars.entry("SIMULATOR_RUNS".to_string())
            .or_insert_with(|| "1".to_string());
        vars.entry("SIMULATOR_MAX_PARALLEL".to_string())
            .or_insert_with(|| "1".to_string());
        vars.entry("SIMULATOR_DURATION".to_string())
            .or_insert_with(|| "60".to_string());

        // Database defaults for testing
        vars.entry("DATABASE_URL".to_string())
            .or_insert_with(|| "sqlite::memory:".to_string());
        vars.entry("DB_HOST".to_string())
            .or_insert_with(|| "localhost".to_string());
        vars.entry("DB_NAME".to_string())
            .or_insert_with(|| "test_db".to_string());
        vars.entry("DB_USER".to_string())
            .or_insert_with(|| "test_user".to_string());
        vars.entry("DB_PASSWORD".to_string())
            .or_insert_with(|| "test_password".to_string());

        // Service defaults
        vars.entry("PORT".to_string())
            .or_insert_with(|| "8080".to_string());
        vars.entry("SSL_PORT".to_string())
            .or_insert_with(|| "8443".to_string());

        // Debug defaults
        vars.entry("DEBUG_RENDERER".to_string())
            .or_insert_with(|| "0".to_string());
        vars.entry("TOKIO_CONSOLE".to_string())
            .or_insert_with(|| "0".to_string());

        log::debug!(
            "Set simulator environment defaults: {} variables",
            vars.len()
        );
    }
}

impl Default for SimulatorEnv {
    fn default() -> Self {
        Self::new()
    }
}

impl EnvProvider for SimulatorEnv {
    /// Get an environment variable as a string
    ///
    /// # Errors
    ///
    /// * If the environment variable is not found
    ///
    /// # Panics
    ///
    /// * If the internal `RwLock` is poisoned
    fn var(&self, name: &str) -> Result<String> {
        let vars = self.vars.read().unwrap();
        vars.get(name)
            .cloned()
            .ok_or_else(|| EnvError::NotFound(name.to_string()))
    }

    /// Get all environment variables
    ///
    /// # Panics
    ///
    /// * If the internal `RwLock` is poisoned
    fn vars(&self) -> BTreeMap<String, String> {
        let vars = self.vars.read().unwrap();
        vars.clone()
    }
}

static PROVIDER: std::sync::LazyLock<SimulatorEnv> = std::sync::LazyLock::new(SimulatorEnv::new);

/// Get an environment variable as a string
///
/// # Errors
///
/// * If the environment variable is not found
///
/// # Panics
///
/// * If the internal `RwLock` is poisoned
pub fn var(name: &str) -> Result<String> {
    PROVIDER.var(name)
}

/// Get an environment variable with a default value
#[must_use]
pub fn var_or(name: &str, default: &str) -> String {
    PROVIDER.var_or(name, default)
}

/// Get an environment variable parsed as a specific type
///
/// # Errors
///
/// * If the environment variable is not found
/// * If the environment variable value cannot be parsed to the target type
pub fn var_parse<T>(name: &str) -> Result<T>
where
    T: std::str::FromStr,
    T::Err: std::fmt::Display,
{
    PROVIDER.var_parse(name)
}

/// Get an environment variable parsed with a default value
#[must_use]
pub fn var_parse_or<T>(name: &str, default: T) -> T
where
    T: std::str::FromStr,
    T::Err: std::fmt::Display,
{
    PROVIDER.var_parse_or(name, default)
}

/// Get an optional environment variable parsed as a specific type
///
/// # Returns
///
/// * `Ok(Some(value))` if the variable exists and parses successfully
/// * `Ok(None)` if the variable doesn't exist
/// * `Err(EnvError::ParseError)` if the variable exists but can't be parsed
///
/// # Errors
///
/// * If the environment variable exists but cannot be parsed to the target type
pub fn var_parse_opt<T>(name: &str) -> Result<Option<T>>
where
    T: std::str::FromStr,
    T::Err: std::fmt::Display,
{
    PROVIDER.var_parse_opt(name)
}

/// Check if an environment variable exists
#[must_use]
pub fn var_exists(name: &str) -> bool {
    PROVIDER.var_exists(name)
}

/// Get all environment variables
///
/// # Panics
///
/// * If the internal `RwLock` is poisoned
#[must_use]
pub fn vars() -> BTreeMap<String, String> {
    PROVIDER.vars()
}

/// Set a variable for testing (simulator only)
///
/// # Panics
///
/// * If the internal `RwLock` is poisoned
pub fn set_var(name: &str, value: &str) {
    PROVIDER.set_var(name, value);
}

/// Remove a variable (simulator only)
///
/// # Panics
///
/// * If the internal `RwLock` is poisoned
pub fn remove_var(name: &str) {
    PROVIDER.remove_var(name);
}

/// Clear all variables (simulator only)
///
/// # Panics
///
/// * If the internal `RwLock` is poisoned
pub fn clear() {
    PROVIDER.clear();
}

/// Reset to defaults (simulator only)
///
/// # Panics
///
/// * If the internal `RwLock` is poisoned
pub fn reset() {
    PROVIDER.reset();
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::EnvProvider;
    use serial_test::serial;

    // Note: All tests in this module use #[serial] because they interact with the global
    // PROVIDER singleton (LazyLock<SimulatorEnv>). This global state contains a BTreeMap
    // of environment variables that is shared across all tests.
    //
    // Running these tests in parallel causes race conditions where:
    // 1. test_global_vars() and test_global_clear() call clear() which removes ALL variables
    // 2. test_global_reset() calls reset() which restores defaults and removes custom vars
    // 3. These operations can occur while other tests are setting/reading variables
    //
    // The serial_test crate ensures these tests run one at a time, preventing interference.

    #[test_log::test]
    #[serial]
    fn test_simulator_env_new_has_defaults() {
        let env = SimulatorEnv::new();
        assert_eq!(env.var("SIMULATOR_SEED").unwrap(), "12345");
        assert_eq!(env.var("SIMULATOR_UUID_SEED").unwrap(), "54321");
        assert_eq!(env.var("PORT").unwrap(), "8080");
        assert_eq!(env.var("DATABASE_URL").unwrap(), "sqlite::memory:");
    }

    #[test_log::test]
    #[serial]
    fn test_simulator_env_set_and_get_var() {
        let env = SimulatorEnv::new();
        env.set_var("TEST_VAR", "test_value");
        assert_eq!(env.var("TEST_VAR").unwrap(), "test_value");
    }

    #[test_log::test]
    #[serial]
    fn test_simulator_env_set_var_overwrites() {
        let env = SimulatorEnv::new();
        env.set_var("TEST_VAR", "first");
        env.set_var("TEST_VAR", "second");
        assert_eq!(env.var("TEST_VAR").unwrap(), "second");
    }

    #[test_log::test]
    #[serial]
    fn test_simulator_env_remove_var() {
        let env = SimulatorEnv::new();
        env.set_var("TEST_VAR", "test_value");
        assert_eq!(env.var("TEST_VAR").unwrap(), "test_value");

        env.remove_var("TEST_VAR");
        assert!(matches!(
            env.var("TEST_VAR"),
            Err(EnvError::NotFound(ref name)) if name == "TEST_VAR"
        ));
    }

    #[test_log::test]
    #[serial]
    fn test_simulator_env_clear() {
        let env = SimulatorEnv::new();
        env.set_var("TEST_VAR", "test_value");

        env.clear();

        // After clear, even defaults should be gone
        assert!(matches!(
            env.var("SIMULATOR_SEED"),
            Err(EnvError::NotFound(_))
        ));
        assert!(matches!(env.var("TEST_VAR"), Err(EnvError::NotFound(_))));
    }

    #[test_log::test]
    #[serial]
    fn test_simulator_env_reset() {
        let env = SimulatorEnv::new();
        env.set_var("CUSTOM_VAR", "custom_value");
        env.set_var("PORT", "9999");

        env.reset();

        // Custom variable should be gone
        assert!(matches!(env.var("CUSTOM_VAR"), Err(EnvError::NotFound(_))));

        // Default should be restored
        assert_eq!(env.var("PORT").unwrap(), "8080");
    }

    #[test_log::test]
    #[serial]
    fn test_simulator_env_var_or_with_existing() {
        let env = SimulatorEnv::new();
        env.set_var("TEST_VAR", "actual_value");
        assert_eq!(env.var_or("TEST_VAR", "default"), "actual_value");
    }

    #[test_log::test]
    #[serial]
    fn test_simulator_env_var_or_with_missing() {
        let env = SimulatorEnv::new();
        assert_eq!(env.var_or("MISSING_VAR", "default_value"), "default_value");
    }

    #[test_log::test]
    #[serial]
    fn test_simulator_env_var_parse_success() {
        let env = SimulatorEnv::new();
        env.set_var("NUMBER", "42");
        let result: i32 = env.var_parse("NUMBER").unwrap();
        assert_eq!(result, 42);
    }

    #[test_log::test]
    #[serial]
    fn test_simulator_env_var_parse_error() {
        let env = SimulatorEnv::new();
        env.set_var("NOT_A_NUMBER", "abc");
        let result: Result<i32> = env.var_parse("NOT_A_NUMBER");
        assert!(matches!(result, Err(EnvError::ParseError(_, _))));
    }

    #[test_log::test]
    #[serial]
    fn test_simulator_env_var_parse_not_found() {
        let env = SimulatorEnv::new();
        let result: Result<i32> = env.var_parse("MISSING");
        assert!(matches!(result, Err(EnvError::NotFound(_))));
    }

    #[test_log::test]
    #[serial]
    fn test_simulator_env_var_parse_or_with_valid() {
        let env = SimulatorEnv::new();
        env.set_var("NUMBER", "100");
        let result: i32 = env.var_parse_or("NUMBER", 42);
        assert_eq!(result, 100);
    }

    #[test_log::test]
    #[serial]
    fn test_simulator_env_var_parse_or_with_invalid() {
        let env = SimulatorEnv::new();
        env.set_var("NOT_A_NUMBER", "xyz");
        let result: i32 = env.var_parse_or("NOT_A_NUMBER", 42);
        assert_eq!(result, 42);
    }

    #[test_log::test]
    #[serial]
    fn test_simulator_env_var_parse_or_with_missing() {
        let env = SimulatorEnv::new();
        let result: i32 = env.var_parse_or("MISSING", 42);
        assert_eq!(result, 42);
    }

    #[test_log::test]
    #[serial]
    fn test_simulator_env_var_parse_opt_some() {
        let env = SimulatorEnv::new();
        env.set_var("NUMBER", "123");
        let result: Option<i32> = env.var_parse_opt("NUMBER").unwrap();
        assert_eq!(result, Some(123));
    }

    #[test_log::test]
    #[serial]
    fn test_simulator_env_var_parse_opt_none() {
        let env = SimulatorEnv::new();
        let result: Option<i32> = env.var_parse_opt("MISSING").unwrap();
        assert_eq!(result, None);
    }

    #[test_log::test]
    #[serial]
    fn test_simulator_env_var_parse_opt_parse_error() {
        let env = SimulatorEnv::new();
        env.set_var("NOT_A_NUMBER", "not_an_int");
        let result: Result<Option<i32>> = env.var_parse_opt("NOT_A_NUMBER");
        assert!(matches!(result, Err(EnvError::ParseError(_, _))));
    }

    #[test_log::test]
    #[serial]
    fn test_simulator_env_var_exists_true() {
        let env = SimulatorEnv::new();
        env.set_var("EXISTS", "yes");
        assert!(env.var_exists("EXISTS"));
    }

    #[test_log::test]
    #[serial]
    fn test_simulator_env_var_exists_false() {
        let env = SimulatorEnv::new();
        assert!(!env.var_exists("DOES_NOT_EXIST"));
    }

    #[test_log::test]
    #[serial]
    fn test_simulator_env_vars() {
        let env = SimulatorEnv::new();
        env.clear();
        env.set_var("VAR1", "value1");
        env.set_var("VAR2", "value2");

        let vars = env.vars();
        assert_eq!(vars.get("VAR1").map(String::as_str), Some("value1"));
        assert_eq!(vars.get("VAR2").map(String::as_str), Some("value2"));
        assert_eq!(vars.len(), 2);
    }

    #[test_log::test]
    #[serial]
    fn test_simulator_env_default_trait() {
        let env1 = SimulatorEnv::default();
        let env2 = SimulatorEnv::new();

        // Both should have the same defaults
        assert_eq!(env1.var("PORT").unwrap(), env2.var("PORT").unwrap());
    }

    #[test_log::test]
    #[serial]
    fn test_global_var() {
        // This tests the global PROVIDER functions
        // Ensure the variable doesn't exist from a previous test
        remove_var("GLOBAL_TEST");
        set_var("GLOBAL_TEST", "global_value");
        assert_eq!(var("GLOBAL_TEST").unwrap(), "global_value");
        remove_var("GLOBAL_TEST");
    }

    #[test_log::test]
    #[serial]
    fn test_global_var_or() {
        remove_var("MISSING_GLOBAL");
        assert_eq!(var_or("MISSING_GLOBAL", "fallback"), "fallback");
    }

    #[test_log::test]
    #[serial]
    fn test_global_var_parse() {
        set_var("GLOBAL_NUMBER", "777");
        let result: i32 = var_parse("GLOBAL_NUMBER").unwrap();
        assert_eq!(result, 777);
        remove_var("GLOBAL_NUMBER");
    }

    #[test_log::test]
    #[serial]
    fn test_global_var_parse_or() {
        remove_var("MISSING_NUMBER");
        let result: i32 = var_parse_or("MISSING_NUMBER", 999);
        assert_eq!(result, 999);
    }

    #[test_log::test]
    #[serial]
    fn test_global_var_parse_opt() {
        set_var("OPTIONAL_NUMBER", "555");
        let result: Option<i32> = var_parse_opt("OPTIONAL_NUMBER").unwrap();
        assert_eq!(result, Some(555));
        remove_var("OPTIONAL_NUMBER");
    }

    #[test_log::test]
    #[serial]
    fn test_global_var_exists() {
        // Ensure clean state
        remove_var("EXISTS_GLOBAL");
        assert!(!var_exists("EXISTS_GLOBAL"));

        set_var("EXISTS_GLOBAL", "yes");
        assert!(var_exists("EXISTS_GLOBAL"));
        remove_var("EXISTS_GLOBAL");
        assert!(!var_exists("EXISTS_GLOBAL"));
    }

    #[test_log::test]
    #[serial]
    fn test_global_vars() {
        clear();
        set_var("VARS_TEST1", "val1");
        set_var("VARS_TEST2", "val2");

        let all_vars = vars();
        assert!(all_vars.contains_key("VARS_TEST1"));
        assert!(all_vars.contains_key("VARS_TEST2"));

        reset();
    }

    #[test_log::test]
    #[serial]
    fn test_global_clear() {
        set_var("TO_BE_CLEARED", "value");
        clear();
        assert!(!var_exists("TO_BE_CLEARED"));
        reset(); // Restore defaults for other tests
    }

    #[test_log::test]
    #[serial]
    fn test_global_reset() {
        set_var("TO_BE_RESET", "custom");
        reset();
        assert!(!var_exists("TO_BE_RESET"));
        // Defaults should be restored
        assert!(var_exists("PORT"));
    }

    #[test_log::test]
    #[serial]
    fn test_simulator_defaults_completeness() {
        let env = SimulatorEnv::new();

        // Test all documented defaults exist
        assert!(env.var_exists("SIMULATOR_SEED"));
        assert!(env.var_exists("SIMULATOR_UUID_SEED"));
        assert!(env.var_exists("SIMULATOR_EPOCH_OFFSET"));
        assert!(env.var_exists("SIMULATOR_STEP_MULTIPLIER"));
        assert!(env.var_exists("SIMULATOR_RUNS"));
        assert!(env.var_exists("SIMULATOR_MAX_PARALLEL"));
        assert!(env.var_exists("SIMULATOR_DURATION"));
        assert!(env.var_exists("DATABASE_URL"));
        assert!(env.var_exists("DB_HOST"));
        assert!(env.var_exists("DB_NAME"));
        assert!(env.var_exists("DB_USER"));
        assert!(env.var_exists("DB_PASSWORD"));
        assert!(env.var_exists("PORT"));
        assert!(env.var_exists("SSL_PORT"));
        assert!(env.var_exists("DEBUG_RENDERER"));
        assert!(env.var_exists("TOKIO_CONSOLE"));
    }

    #[test_log::test]
    #[serial]
    fn test_parse_various_types() {
        let env = SimulatorEnv::new();

        // Test bool
        env.set_var("BOOL_TRUE", "true");
        env.set_var("BOOL_FALSE", "false");
        assert!(env.var_parse::<bool>("BOOL_TRUE").unwrap());
        assert!(!env.var_parse::<bool>("BOOL_FALSE").unwrap());

        // Test float
        env.set_var("FLOAT", "2.5");
        assert!((env.var_parse::<f64>("FLOAT").unwrap() - 2.5).abs() < 0.001);

        // Test unsigned
        env.set_var("UNSIGNED", "42");
        assert_eq!(env.var_parse::<u32>("UNSIGNED").unwrap(), 42);
    }

    #[test_log::test]
    #[serial]
    fn test_simulator_env_arc_sharing() {
        // SimulatorEnv uses Arc<RwLock<...>> internally, so cloned instances share state
        let env1 = SimulatorEnv::new();
        let vars_clone = env1.vars.clone();
        let env2 = SimulatorEnv { vars: vars_clone };

        // Set a variable through env1
        env1.set_var("SHARED_VAR", "from_env1");

        // It should be visible through env2 since they share the same Arc
        assert_eq!(env2.var("SHARED_VAR").unwrap(), "from_env1");

        // Modify through env2
        env2.set_var("SHARED_VAR", "from_env2");

        // Change should be visible through env1
        assert_eq!(env1.var("SHARED_VAR").unwrap(), "from_env2");
    }

    #[test_log::test]
    #[serial]
    fn test_remove_nonexistent_var() {
        let env = SimulatorEnv::new();

        // Removing a non-existent variable should not panic
        env.remove_var("DEFINITELY_DOES_NOT_EXIST_123456789");

        // Environment should still work normally after
        assert_eq!(env.var("PORT").unwrap(), "8080");
    }

    #[test_log::test]
    #[serial]
    fn test_empty_string_value() {
        let env = SimulatorEnv::new();
        env.set_var("EMPTY_VAR", "");

        // Reading an empty string should succeed
        assert_eq!(env.var("EMPTY_VAR").unwrap(), "");

        // Empty string exists
        assert!(env.var_exists("EMPTY_VAR"));

        // Parsing empty string as String should work
        let s: String = env.var_parse("EMPTY_VAR").unwrap();
        assert_eq!(s, "");

        // Parsing empty string as number should fail with parse error
        let result: Result<i32> = env.var_parse("EMPTY_VAR");
        assert!(matches!(result, Err(EnvError::ParseError(_, _))));
    }

    #[test_log::test]
    #[serial]
    fn test_concurrent_read_write() {
        use std::sync::Arc;
        use std::thread;

        let env = SimulatorEnv::new();
        let vars = Arc::clone(&env.vars);

        // Spawn multiple reader threads
        let mut handles = vec![];
        for i in 0..4 {
            let vars_clone = vars.clone();
            let handle = thread::spawn(move || {
                let env = SimulatorEnv { vars: vars_clone };
                for _ in 0..100 {
                    // Read operations
                    let _ = env.var("PORT");
                    let _ = env.vars();
                    let _ = env.var_exists("SIMULATOR_SEED");
                }
                i
            });
            handles.push(handle);
        }

        // Spawn a writer thread
        let vars_clone = vars.clone();
        let writer = thread::spawn(move || {
            let env = SimulatorEnv { vars: vars_clone };
            for j in 0..100 {
                env.set_var("CONCURRENT_VAR", &format!("value_{j}"));
            }
        });

        // All threads should complete without panicking (no deadlock, no data race)
        for handle in handles {
            handle.join().expect("Reader thread panicked");
        }
        writer.join().expect("Writer thread panicked");

        // Final state should be consistent
        let env = SimulatorEnv { vars };
        assert!(env.var("CONCURRENT_VAR").is_ok());
    }

    #[test_log::test]
    #[serial]
    fn test_real_env_vars_preserved_on_new() {
        // Set a real env var before creating SimulatorEnv
        unsafe {
            std::env::set_var("REAL_TEST_VAR_FOR_SIMULATOR", "real_value");
        }

        let env = SimulatorEnv::new();

        // The real env var should be present
        assert_eq!(
            env.var("REAL_TEST_VAR_FOR_SIMULATOR").unwrap(),
            "real_value"
        );

        // Cleanup
        unsafe {
            std::env::remove_var("REAL_TEST_VAR_FOR_SIMULATOR");
        }
    }

    #[test_log::test]
    #[serial]
    fn test_reset_reloads_real_env_vars() {
        // Set up: ensure a real env var exists
        unsafe {
            std::env::set_var("REAL_VAR_FOR_RESET_TEST", "original");
        }

        let env = SimulatorEnv::new();
        assert_eq!(env.var("REAL_VAR_FOR_RESET_TEST").unwrap(), "original");

        // Clear the simulator env
        env.clear();
        assert!(env.var("REAL_VAR_FOR_RESET_TEST").is_err());

        // Change the real env var
        unsafe {
            std::env::set_var("REAL_VAR_FOR_RESET_TEST", "changed");
        }

        // Reset should reload from the real environment
        env.reset();
        assert_eq!(env.var("REAL_VAR_FOR_RESET_TEST").unwrap(), "changed");

        // Cleanup
        unsafe {
            std::env::remove_var("REAL_VAR_FOR_RESET_TEST");
        }
    }
}