verdure-context 0.0.5

An ecosystem framework for Rust.
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
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
//! Application context implementation
//!
//! This module provides the main `ApplicationContext` implementation that serves as the
//! central hub for application-wide state, configuration, environment management, and
//! integration with the IoC container.

use crate::config::{ConfigFactory, ConfigManager, ConfigSource, ConfigValue};
use crate::error::{ContextError, ContextResult};
use crate::event::{
    ConfigurationChangedEvent, ContextAwareEventListener, ContextInitializedEvent,
    ContextInitializingEvent, Event, EventListener, EventPublisher,
};
use dashmap::DashMap;
use std::path::Path;
use std::sync::Arc;
use verdure_ioc::{ComponentContainer, ComponentFactory, ComponentInstance};

/// Application context builder
///
/// `ApplicationContextBuilder` provides a fluent API for constructing
/// an `ApplicationContext` with various configuration sources, profiles,
/// and settings.
///
/// # Examples
///
/// ```rust
/// use verdure_context::ApplicationContextBuilder;
///
/// let context = ApplicationContextBuilder::new()
///     .with_property("app.name", "MyApp")
///     .build()
///     .unwrap();
/// ```
#[derive(Debug)]
pub struct ApplicationContextBuilder {
    config_sources: Vec<ConfigSource>,
    properties: std::collections::HashMap<String, String>,
}

impl ApplicationContextBuilder {
    /// Creates a new application context builder
    ///
    /// # Examples
    ///
    /// ```rust
    /// use verdure_context::ApplicationContextBuilder;
    ///
    /// let builder = ApplicationContextBuilder::new();
    /// ```
    pub fn new() -> Self {
        Self {
            config_sources: Vec::new(),
            properties: std::collections::HashMap::new(),
        }
    }

    /// Adds a configuration source
    ///
    /// # Arguments
    ///
    /// * `source` - The configuration source to add
    ///
    /// # Examples
    ///
    /// ```rust
    /// use verdure_context::{ApplicationContextBuilder, ConfigSource};
    /// use std::collections::HashMap;
    ///
    /// let builder = ApplicationContextBuilder::new()
    ///     .with_config_source(ConfigSource::Environment);
    /// ```
    pub fn with_config_source(mut self, source: ConfigSource) -> Self {
        self.config_sources.push(source);
        self
    }

    /// Loads configuration from a TOML file
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the TOML configuration file
    ///
    /// # Examples
    ///
    /// ```rust
    /// use verdure_context::ApplicationContextBuilder;
    ///
    /// let builder = ApplicationContextBuilder::new()
    ///     .with_toml_config_file("config/app.toml");
    /// ```
    pub fn with_toml_config_file<P: AsRef<Path>>(mut self, path: P) -> Self {
        let path_str = path.as_ref().to_string_lossy().to_string();
        self.config_sources.push(ConfigSource::TomlFile(path_str));
        self
    }

    /// Loads configuration from a YAML file
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the YAML configuration file
    ///
    /// # Examples
    ///
    /// ```rust
    /// use verdure_context::ApplicationContextBuilder;
    ///
    /// let builder = ApplicationContextBuilder::new()
    ///     .with_yaml_config_file("config/app.yaml");
    /// ```
    pub fn with_yaml_config_file<P: AsRef<Path>>(mut self, path: P) -> Self {
        let path_str = path.as_ref().to_string_lossy().to_string();
        self.config_sources.push(ConfigSource::YamlFile(path_str));
        self
    }

    /// Loads configuration from a Properties file
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the Properties configuration file
    ///
    /// # Examples
    ///
    /// ```rust
    /// use verdure_context::ApplicationContextBuilder;
    ///
    /// let builder = ApplicationContextBuilder::new()
    ///     .with_properties_config_file("config/app.properties");
    /// ```
    pub fn with_properties_config_file<P: AsRef<Path>>(mut self, path: P) -> Self {
        let path_str = path.as_ref().to_string_lossy().to_string();
        self.config_sources
            .push(ConfigSource::PropertiesFile(path_str));
        self
    }

    /// Loads configuration from a file with automatic format detection
    ///
    /// The format is detected based on the file extension:
    /// - `.toml` -> TOML format
    /// - `.yaml` or `.yml` -> YAML format  
    /// - `.properties` -> Properties format
    /// - Others -> Attempts to parse as TOML first, then YAML, then Properties
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the configuration file
    ///
    /// # Examples
    ///
    /// ```rust
    /// use verdure_context::ApplicationContextBuilder;
    ///
    /// let builder = ApplicationContextBuilder::new()
    ///     .with_config_file("config/app.yaml")
    ///     .with_config_file("config/database.properties")
    ///     .with_config_file("config/server.toml");
    /// ```
    pub fn with_config_file<P: AsRef<Path>>(mut self, path: P) -> Self {
        let path_str = path.as_ref().to_string_lossy().to_string();
        self.config_sources.push(ConfigSource::ConfigFile(path_str));
        self
    }

    /// Sets a property value
    ///
    /// # Arguments
    ///
    /// * `key` - The property key
    /// * `value` - The property value
    ///
    /// # Examples
    ///
    /// ```rust
    /// use verdure_context::ApplicationContextBuilder;
    ///
    /// let builder = ApplicationContextBuilder::new()
    ///     .with_property("app.name", "MyApplication");
    /// ```
    pub fn with_property(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.properties.insert(key.into(), value.into());
        self
    }

    /// Builds the application context
    ///
    /// # Returns
    ///
    /// A new `ApplicationContext` instance configured with the specified settings
    ///
    /// # Errors
    ///
    /// Returns an error if context initialization fails
    ///
    /// # Examples
    ///
    /// ```rust
    /// use verdure_context::ApplicationContextBuilder;
    ///
    /// let context = ApplicationContextBuilder::new()
    ///     .with_property("app.name", "MyApp")
    ///     .build()
    ///     .unwrap();
    /// ```
    pub fn build(self) -> ContextResult<ApplicationContext> {
        let context = ApplicationContext::new();

        // Add configuration sources
        for source in self.config_sources {
            context.config_manager.add_source(source)?;
        }

        // Add properties as a configuration source
        if !self.properties.is_empty() {
            context
                .config_manager
                .add_source(ConfigSource::Properties(self.properties))?;
        }

        Ok(context)
    }
}

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

/// Main application context
///
/// `ApplicationContext` serves as the central hub for application-wide services,
/// configuration, environment management, and integration with the IoC container.
/// It provides a unified interface for accessing all framework services.
///
/// # Examples
///
/// ```rust
/// use verdure_context::ApplicationContext;
///
/// let context = ApplicationContext::builder()
///     .with_property("app.name", "MyApp")
///     .build()
///     .unwrap();
///
/// // Access configuration
/// let app_name = context.get_config("app.name");
///
/// // Access IoC container
/// let container = context.container();
/// ```
pub struct ApplicationContext {
    /// Configuration manager
    config_manager: Arc<ConfigManager>,
    /// Event publisher for application-wide events
    event_publisher: EventPublisher,
    /// IoC container integration
    container: Arc<ComponentContainer>,
    /// Application properties cache
    properties_cache: DashMap<String, ConfigValue>,
}

impl ApplicationContext {
    /// Creates a new application context
    ///
    /// # Examples
    ///
    /// ```rust
    /// use verdure_context::ApplicationContext;
    ///
    /// let context = ApplicationContext::new();
    /// ```
    pub fn new() -> Self {
        Self {
            config_manager: Arc::new(ConfigManager::new()),
            event_publisher: EventPublisher::new(),
            container: Arc::new(ComponentContainer::new()),
            properties_cache: DashMap::new(),
        }
    }

    /// Creates a builder for constructing an application context
    ///
    /// # Examples
    ///
    /// ```rust
    /// use verdure_context::ApplicationContext;
    ///
    /// let context = ApplicationContext::builder()
    ///     .with_property("app.version", "1.0.0")
    ///     .build()
    ///     .unwrap();
    /// ```
    pub fn builder() -> ApplicationContextBuilder {
        ApplicationContextBuilder::new()
    }
    fn initialize_early(&self) -> ContextResult<()> {
        self.container.register_component(self.config_manager.clone());

        for factory in inventory::iter::<ConfigFactory> {
            let config_component = (factory.create_fn)(self.config_manager.clone())?;
            self.container.register_component(config_component);
        }
        Ok(())
    }
    /// Initializes the application context
    ///
    /// This method initializes the IoC container and performs any other
    /// necessary initialization steps.
    ///
    /// # Returns
    ///
    /// `Ok(())` if initialization succeeds, an error otherwise
    ///
    /// # Examples
    ///
    /// ```rust
    /// use verdure_context::ApplicationContext;
    ///
    /// let context = ApplicationContext::new();
    /// context.initialize().unwrap();
    /// ```
    pub fn initialize(&self) -> ContextResult<()> {
        self.initialize_early()?;
        // Publish context-initializing event at the start
        let initializing_event = ContextInitializingEvent {
            config_sources_count: self.config_manager.sources_count(),
            timestamp: std::time::SystemTime::now(),
        };
        self.event_publisher
            .publish_with_context(&initializing_event, self);

        // Initialize the IoC container
        self.container.initialize().map_err(|e| {
            ContextError::initialization_failed(format!(
                "IoC container initialization failed: {}",
                e
            ))
        })?;

        // Publish context initialized event at the end
        let initialized_event = ContextInitializedEvent {
            config_sources_count: self.config_manager.sources_count(),
            timestamp: std::time::SystemTime::now(),
        };
        self.event_publisher
            .publish_with_context(&initialized_event, self);

        Ok(())
    }

    /// Gets a configuration value by key
    ///
    /// # Arguments
    ///
    /// * `key` - The configuration key
    ///
    /// # Returns
    ///
    /// The configuration value as a string, or an empty string if not found
    ///
    /// # Examples
    ///
    /// ```rust
    /// use verdure_context::{ApplicationContext, ConfigSource};
    /// use std::collections::HashMap;
    ///
    /// let mut context = ApplicationContext::new();
    ///
    /// let mut props = HashMap::new();
    /// props.insert("app.name".to_string(), "MyApp".to_string());
    /// context.add_config_source(ConfigSource::Properties(props)).unwrap();
    ///
    /// assert_eq!(context.get_config("app.name"), "MyApp");
    /// ```
    pub fn get_config(&self, key: &str) -> String {
        self.config_manager.get_string_or_default(key, "")
    }

    /// Gets a configuration value as a specific type
    ///
    /// # Arguments
    ///
    /// * `key` - The configuration key
    ///
    /// # Returns
    ///
    /// The configuration value parsed as the requested type
    ///
    /// # Errors
    ///
    /// Returns an error if the key is not found or cannot be parsed as the requested type
    ///
    /// # Examples
    ///
    /// ```rust
    /// use verdure_context::{ApplicationContext, ConfigSource};
    /// use std::collections::HashMap;
    ///
    /// let mut context = ApplicationContext::new();
    ///
    /// let mut props = HashMap::new();
    /// props.insert("app.port".to_string(), "8080".to_string());
    /// context.add_config_source(ConfigSource::Properties(props)).unwrap();
    ///
    /// let port: i64 = context.get_config_as("app.port").unwrap();
    /// assert_eq!(port, 8080);
    /// ```
    pub fn get_config_as<T>(&self, key: &str) -> ContextResult<T>
    where
        T: std::str::FromStr,
        T::Err: std::fmt::Display,
    {
        let value = self.config_manager.get_string(key)?;
        value
            .parse::<T>()
            .map_err(|e| ContextError::invalid_configuration(key, e.to_string()))
    }

    /// Gets a configuration value with a default
    ///
    /// # Arguments
    ///
    /// * `key` - The configuration key
    /// * `default` - The default value to return if key is not found
    ///
    /// # Examples
    ///
    /// ```rust
    /// use verdure_context::ApplicationContext;
    ///
    /// let context = ApplicationContext::new();
    /// let port = context.get_config_or_default("app.port", "8080");
    /// assert_eq!(port, "8080");
    /// ```
    pub fn get_config_or_default(&self, key: &str, default: &str) -> String {
        self.config_manager.get_string_or_default(key, default)
    }

    /// Sets a configuration property
    ///
    /// # Arguments
    ///
    /// * `key` - The configuration key
    /// * `value` - The configuration value
    ///
    /// # Examples
    ///
    /// ```rust
    /// use verdure_context::ApplicationContext;
    ///
    /// let mut context = ApplicationContext::new();
    /// context.set_config("runtime.property", "runtime.value");
    ///
    /// assert_eq!(context.get_config("runtime.property"), "runtime.value");
    /// ```
    /// Sets a configuration property
    pub fn set_config(&self, key: &str, value: &str) {
        let old_value = self.get_config(key);
        let old_value_opt = if old_value.is_empty() {
            None
        } else {
            Some(old_value)
        };

        self.config_manager
            .set(key, ConfigValue::String(value.to_string()));

        let event = ConfigurationChangedEvent {
            key: key.to_string(),
            old_value: old_value_opt,
            new_value: value.to_string(),
            timestamp: std::time::SystemTime::now(),
        };
        self.event_publisher.publish(&event);
    }

    /// Adds a configuration source
    pub fn add_config_source(&self, source: ConfigSource) -> ContextResult<()> {
        self.config_manager.add_source(source)
    }

    /// Gets the IoC container
    ///
    /// # Returns
    ///
    /// A reference to the IoC container
    ///
    /// # Examples
    ///
    /// ```rust
    /// use verdure_context::ApplicationContext;
    ///
    /// let context = ApplicationContext::new();
    /// let container = context.container();
    /// ```
    pub fn container(&self) -> Arc<ComponentContainer> {
        self.container.clone()
    }
    
    /// Gets a shared reference to the ConfigManager for IoC registration
    pub fn config_manager(&self) -> Arc<ConfigManager> {
        self.config_manager.clone()
    }

    /// Gets a component from the IoC container
    ///
    /// # Returns
    ///
    /// The requested component if found
    ///
    /// # Examples
    ///
    /// ```rust
    /// use verdure_context::ApplicationContext;
    /// use std::sync::Arc;
    ///
    /// #[derive(Debug)]
    /// struct MyService {
    ///     name: String,
    /// }
    ///
    /// let context = ApplicationContext::new();
    ///
    /// // First register the component
    /// let service = Arc::new(MyService {
    ///     name: "TestService".to_string(),
    /// });
    /// context.container().register_component(service);
    ///
    /// // Then retrieve it
    /// let retrieved: Option<Arc<MyService>> = context.get_component();
    /// assert!(retrieved.is_some());
    /// ```
    pub fn get_component<T: 'static + Send + Sync>(&self) -> Option<Arc<T>> {
        self.container.get_component()
    }
    /// Registers a pre-created component instance with the context container
    pub fn register_component(&self, instance: ComponentInstance) {
        self.container.register_component(instance)
    }

    /// Publishes an event
    ///
    /// # Arguments
    ///
    /// * `event` - The event to publish
    ///
    /// # Examples
    ///
    /// ```rust
    /// use verdure_context::{ApplicationContext, Event};
    /// use std::any::Any;
    ///
    /// #[derive(Debug, Clone)]
    /// struct MyEvent {
    ///     message: String,
    /// }
    ///
    /// impl Event for MyEvent {
    ///     fn name(&self) -> &'static str { "MyEvent" }
    ///     fn as_any(&self) -> &dyn Any { self }
    ///     fn into_any(self: Box<Self>) -> Box<dyn Any> { self }
    /// }
    ///
    /// let context = ApplicationContext::new();
    /// let event = MyEvent {
    ///     message: "Hello, World!".to_string(),
    /// };
    ///
    /// context.publish_event(&event);
    /// ```
    pub fn publish_event<T: Event + 'static>(&self, event: &T) {
        self.event_publisher.publish(event);
    }

    /// Subscribes to events with context access
    ///
    /// Context-aware listeners receive both the event and a reference to the ApplicationContext,
    /// allowing them to interact with the context during event handling.
    ///
    /// # Arguments
    ///
    /// * `listener` - The context-aware event listener to register
    ///
    /// # Examples
    ///
    /// ```rust
    /// use verdure_context::{ApplicationContext, ContextInitializedEvent, ContextAwareEventListener};
    ///
    /// struct StartupListener;
    ///
    /// impl ContextAwareEventListener<ContextInitializedEvent> for StartupListener {
    ///     fn on_context_event(&self, event: &ContextInitializedEvent, context: &ApplicationContext) {
    ///         println!("Context initialized! App name: {}", context.get_config("app.name"));
    ///         println!("Environment: {}", context.environment());
    ///     }
    /// }
    ///
    /// let mut context = ApplicationContext::new();
    /// context.subscribe_to_context_events(StartupListener);
    /// ```
    /// Subscribes to events with context access
    pub fn subscribe_to_context_events<
        T: Event + 'static,
        L: ContextAwareEventListener<T> + 'static,
    >(
        &self,
        listener: L,
    ) {
        self.event_publisher.subscribe_context_aware(listener);
    }
    ///
    /// # Arguments
    ///
    /// * `listener` - The event listener to register
    ///
    /// # Examples
    ///
    /// ```rust
    /// use verdure_context::{ApplicationContext, Event, EventListener};
    /// use std::any::Any;
    ///
    /// #[derive(Debug, Clone)]
    /// struct TestEvent;
    ///
    /// impl Event for TestEvent {
    ///     fn name(&self) -> &'static str { "TestEvent" }
    ///     fn as_any(&self) -> &dyn Any { self }
    ///     fn into_any(self: Box<Self>) -> Box<dyn Any> { self }
    /// }
    ///
    /// struct TestListener;
    ///
    /// impl EventListener<TestEvent> for TestListener {
    ///     fn on_event(&self, _event: &TestEvent) {
    ///         println!("Event received!");
    ///     }
    /// }
    ///
    /// let mut context = ApplicationContext::new();
    /// context.subscribe_to_events(TestListener);
    /// ```
    /// Subscribes to events
    pub fn subscribe_to_events<T: Event + 'static, L: EventListener<T> + 'static>(
        &self,
        listener: L,
    ) {
        self.event_publisher.subscribe(listener);
    }

    /// Gets environment information
    ///
    /// # Returns
    ///
    /// A string representing the current environment
    ///
    /// # Examples
    ///
    /// ```rust
    /// use verdure_context::ApplicationContext;
    ///
    /// let context = ApplicationContext::new();
    /// println!("Environment: {}", context.environment());
    /// ```
    pub fn environment(&self) -> String {
        "default".to_string()
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;

    #[test]
    fn test_application_context_creation() {
        let context = ApplicationContext::new();
        // Context created successfully
        assert_eq!(context.environment(), "default");
    }

    #[test]
    fn test_application_context_builder() {
        let context = ApplicationContext::builder()
            .with_property("app.name", "TestApp")
            .build()
            .unwrap();

        assert_eq!(context.get_config("app.name"), "TestApp");
    }

    #[test]
    fn test_configuration_management() {
        let context = ApplicationContext::new();

        let mut props = HashMap::new();
        props.insert(
            "database.url".to_string(),
            "postgres://localhost/test".to_string(),
        );
        props.insert("server.port".to_string(), "3000".to_string());
        props.insert("debug.enabled".to_string(), "true".to_string());

        context
            .add_config_source(ConfigSource::Properties(props))
            .unwrap();

        assert_eq!(
            context.get_config("database.url"),
            "postgres://localhost/test"
        );

        let port: i64 = context.get_config_as("server.port").unwrap();
        assert_eq!(port, 3000);

        let debug: bool = context.get_config_as("debug.enabled").unwrap();
        assert_eq!(debug, true);
    }

    #[test]
    fn test_configuration_with_defaults() {
        let context = ApplicationContext::new();

        assert_eq!(context.get_config("missing.key"), "");
        assert_eq!(
            context.get_config_or_default("missing.key", "default"),
            "default"
        );
    }

    #[test]
    fn test_runtime_configuration() {
        let context = ApplicationContext::new();

        context.set_config("runtime.property", "runtime.value");
        assert_eq!(context.get_config("runtime.property"), "runtime.value");
    }


    #[test]
    fn test_environment_default() {
        let context = ApplicationContext::new();
        assert_eq!(context.environment(), "default");
    }

    #[test]
    fn test_container_integration() {
        let context = ApplicationContext::new();
        let container = context.container();

        // Test that we can access the container
        assert!(container.get_component::<String>().is_none());
    }

    // Test event system integration
    use std::any::Any;

    #[derive(Debug, Clone)]
    struct TestContextEvent {
        message: String,
    }

    impl Event for TestContextEvent {
        fn name(&self) -> &'static str {
            "TestContextEvent"
        }

        fn as_any(&self) -> &dyn Any {
            self
        }

        fn into_any(self: Box<Self>) -> Box<dyn Any> {
            self
        }
    }

    struct TestContextListener {
        received: Arc<std::sync::Mutex<Vec<String>>>,
    }

    impl EventListener<TestContextEvent> for TestContextListener {
        fn on_event(&self, event: &TestContextEvent) {
            let mut received = self.received.lock().unwrap();
            received.push(event.message.clone());
        }
    }

    #[test]
    fn test_event_system_integration() {
        let received = Arc::new(std::sync::Mutex::new(Vec::new()));
        let listener = TestContextListener {
            received: received.clone(),
        };

        let context = ApplicationContext::new();
        context.subscribe_to_events(listener);

        let event = TestContextEvent {
            message: "test message".to_string(),
        };

        context.publish_event(&event);

        let received_messages = received.lock().unwrap();
        assert_eq!(received_messages.len(), 1);
        assert_eq!(received_messages[0], "test message");
    }

    #[test]
    fn test_built_in_context_events() {
        use crate::event::{
            ConfigurationChangedEvent, ContextInitializedEvent, ContextInitializingEvent,
        };
        use std::sync::{Arc, Mutex};

        // Event collectors
        let initializing_events = Arc::new(Mutex::new(Vec::new()));
        let initialized_events = Arc::new(Mutex::new(Vec::new()));
        let config_events = Arc::new(Mutex::new(Vec::new()));

        // Event listeners
        struct InitializingListener(Arc<Mutex<Vec<ContextInitializingEvent>>>);
        impl EventListener<ContextInitializingEvent> for InitializingListener {
            fn on_event(&self, event: &ContextInitializingEvent) {
                let mut events = self.0.lock().unwrap();
                events.push(event.clone());
            }
        }

        struct InitializedListener(Arc<Mutex<Vec<ContextInitializedEvent>>>);
        impl EventListener<ContextInitializedEvent> for InitializedListener {
            fn on_event(&self, event: &ContextInitializedEvent) {
                let mut events = self.0.lock().unwrap();
                events.push(event.clone());
            }
        }

        struct ConfigListener(Arc<Mutex<Vec<ConfigurationChangedEvent>>>);
        impl EventListener<ConfigurationChangedEvent> for ConfigListener {
            fn on_event(&self, event: &ConfigurationChangedEvent) {
                let mut events = self.0.lock().unwrap();
                events.push(event.clone());
            }
        }

        // Create context with configuration
        let context = ApplicationContext::builder()
            .with_property("initial.key", "initial.value")
            .build()
            .unwrap();

        // Subscribe to events BEFORE initialization
        context.subscribe_to_events(InitializingListener(initializing_events.clone()));
        context.subscribe_to_events(InitializedListener(initialized_events.clone()));
        context.subscribe_to_events(ConfigListener(config_events.clone()));

        // Initialize context (should fire both ContextInitializingEvent and ContextInitializedEvent)
        context.initialize().unwrap();

        // Change configuration (should fire ConfigurationChangedEvent)
        context.set_config("runtime.key", "runtime.value");
        context.set_config("initial.key", "updated.value");

        // Verify initializing events were fired
        let initializing_events = initializing_events.lock().unwrap();
        assert_eq!(initializing_events.len(), 1);
        assert!(initializing_events[0].config_sources_count > 0);

        // Verify initialized events were fired
        let initialized_events = initialized_events.lock().unwrap();
        assert_eq!(initialized_events.len(), 1);
        assert!(initialized_events[0].config_sources_count > 0);

        // Verify the initializing event was fired before the initialized event
        assert!(initializing_events[0].timestamp <= initialized_events[0].timestamp);

        let config_events = config_events.lock().unwrap();
        assert_eq!(config_events.len(), 2);

        // First config change (new key)
        assert_eq!(config_events[0].key, "runtime.key");
        assert_eq!(config_events[0].old_value, None);
        assert_eq!(config_events[0].new_value, "runtime.value");

        // Second config change (update existing key)
        assert_eq!(config_events[1].key, "initial.key");
        assert_eq!(
            config_events[1].old_value,
            Some("initial.value".to_string())
        );
        assert_eq!(config_events[1].new_value, "updated.value");
    }

    #[test]
    fn test_context_aware_event_listeners() {
        use crate::event::{ContextAwareEventListener, ContextInitializedEvent};
        use std::sync::{Arc, Mutex};

        // Track events and context access
        let events_received = Arc::new(Mutex::new(Vec::new()));
        let context_data_accessed = Arc::new(Mutex::new(Vec::new()));

        // Context-aware event listener
        struct ContextAwareListener {
            events: Arc<Mutex<Vec<String>>>,
            context_data: Arc<Mutex<Vec<String>>>,
        }

        impl ContextAwareEventListener<ContextInitializedEvent> for ContextAwareListener {
            fn on_context_event(
                &self,
                event: &ContextInitializedEvent,
                context: &crate::context::ApplicationContext,
            ) {
                // Record the event
                let mut events = self.events.lock().unwrap();
                events.push(format!(
                    "Initialized with {} sources",
                    event.config_sources_count
                ));

                // Access context data
                let mut context_data = self.context_data.lock().unwrap();
                context_data.push(context.get_config("test.key"));
                context_data.push(context.environment());
            }
        }

        // Create context with some configuration
        let context = ApplicationContext::builder()
            .with_property("test.key", "test.value")
            .with_property("app.name", "TestApp")
            .build()
            .unwrap();

        // Register context-aware listener
        let listener = ContextAwareListener {
            events: events_received.clone(),
            context_data: context_data_accessed.clone(),
        };
        context.subscribe_to_context_events(listener);

        // Initialize context - this should trigger the context-aware event
        context.initialize().unwrap();

        // Verify the context-aware listener received the event and could access context
        let events = events_received.lock().unwrap();
        assert_eq!(events.len(), 1);
        assert!(events[0].contains("Initialized with"));

        let context_data = context_data_accessed.lock().unwrap();
        assert_eq!(context_data.len(), 2);
        assert_eq!(context_data[0], "test.value"); // Successfully accessed config
        assert_eq!(context_data[1], "default"); // Successfully accessed environment
    }
}