elif-core 0.7.1

Core architecture foundation for the elif.rs LLM-friendly web framework
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
use crate::container::autowiring::Injectable;
use crate::container::descriptor::{ServiceDescriptor, ServiceDescriptorFactoryBuilder, ServiceId};
use crate::container::scope::ServiceScope;
use crate::errors::CoreError;

/// Conditional binding function type
pub type ConditionFn = Box<dyn Fn() -> bool + Send + Sync>;

/// Environment condition type
pub type EnvCondition = (&'static str, String);

/// Binding configuration for advanced features
pub struct BindingConfig {
    /// Named/tagged identifier
    pub name: Option<String>,
    /// Service lifetime
    pub lifetime: ServiceScope,
    /// Environment-based conditions
    pub env_conditions: Vec<EnvCondition>,
    /// Feature flag conditions
    pub feature_conditions: Vec<(String, bool)>,
    /// Custom condition functions
    pub conditions: Vec<ConditionFn>,
    /// Whether this is the default implementation
    pub is_default: bool,
    /// Profile-based conditions
    pub profile_conditions: Vec<String>,
}

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

impl BindingConfig {
    pub fn new() -> Self {
        Self {
            name: None,
            lifetime: ServiceScope::Transient,
            env_conditions: Vec::new(),
            feature_conditions: Vec::new(),
            conditions: Vec::new(),
            is_default: false,
            profile_conditions: Vec::new(),
        }
    }

    /// Check if all conditions are met
    pub fn evaluate_conditions(&self) -> bool {
        // Check environment conditions
        for (key, expected_value) in &self.env_conditions {
            if let Ok(actual_value) = std::env::var(key) {
                if actual_value != *expected_value {
                    return false;
                }
            } else {
                return false;
            }
        }

        // Check feature conditions
        for (feature, expected) in &self.feature_conditions {
            let feature_enabled =
                std::env::var(format!("FEATURE_{}", feature.to_uppercase())).is_ok();
            if feature_enabled != *expected {
                return false;
            }
        }

        // Check profile conditions
        if !self.profile_conditions.is_empty() {
            let current_profile =
                std::env::var("PROFILE").unwrap_or_else(|_| "development".to_string());
            if !self.profile_conditions.contains(&current_profile) {
                return false;
            }
        }

        // Check custom conditions
        for condition in &self.conditions {
            if !condition() {
                return false;
            }
        }

        true
    }
}

/// Advanced binding builder for fluent configuration
pub struct AdvancedBindingBuilder<TInterface: ?Sized + 'static> {
    config: BindingConfig,
    _phantom: std::marker::PhantomData<*const TInterface>,
}

impl<TInterface: ?Sized + 'static> Default for AdvancedBindingBuilder<TInterface> {
    fn default() -> Self {
        Self::new()
    }
}

impl<TInterface: ?Sized + 'static> AdvancedBindingBuilder<TInterface> {
    pub fn new() -> Self {
        Self {
            config: BindingConfig::new(),
            _phantom: std::marker::PhantomData,
        }
    }

    /// Set service name/tag
    pub fn named(mut self, name: impl Into<String>) -> Self {
        self.config.name = Some(name.into());
        self
    }

    /// Set service lifetime
    pub fn with_lifetime(mut self, lifetime: ServiceScope) -> Self {
        self.config.lifetime = lifetime;
        self
    }

    /// Add environment condition
    pub fn when_env(mut self, key: &'static str, value: impl Into<String>) -> Self {
        self.config.env_conditions.push((key, value.into()));
        self
    }

    /// Add feature flag condition
    pub fn when_feature(mut self, feature: impl Into<String>) -> Self {
        self.config.feature_conditions.push((feature.into(), true));
        self
    }

    /// Add inverse feature flag condition
    pub fn when_not_feature(mut self, feature: impl Into<String>) -> Self {
        self.config.feature_conditions.push((feature.into(), false));
        self
    }

    /// Add custom condition
    pub fn when<F>(mut self, condition: F) -> Self
    where
        F: Fn() -> bool + Send + Sync + 'static,
    {
        self.config.conditions.push(Box::new(condition));
        self
    }

    /// Mark as default implementation
    pub fn as_default(mut self) -> Self {
        self.config.is_default = true;
        self
    }

    /// Add profile condition
    pub fn in_profile(mut self, profile: impl Into<String>) -> Self {
        self.config.profile_conditions.push(profile.into());
        self
    }

    /// Get the configuration
    pub fn config(self) -> BindingConfig {
        self.config
    }
}

/// Binding API for the IoC container
pub trait ServiceBinder {
    /// Add a pre-built service descriptor
    fn add_service_descriptor(
        &mut self,
        descriptor: crate::container::descriptor::ServiceDescriptor,
    ) -> Result<&mut Self, crate::errors::CoreError>;

    /// Bind an interface to an implementation
    fn bind<TInterface: ?Sized + 'static, TImpl: Send + Sync + Default + 'static>(
        &mut self,
    ) -> &mut Self;

    /// Bind an interface to an implementation with singleton lifetime
    fn bind_singleton<TInterface: ?Sized + 'static, TImpl: Send + Sync + Default + 'static>(
        &mut self,
    ) -> &mut Self;

    /// Bind an interface to an implementation with transient lifetime
    fn bind_transient<TInterface: ?Sized + 'static, TImpl: Send + Sync + Default + 'static>(
        &mut self,
    ) -> &mut Self;

    /// Bind a service using a factory function
    fn bind_factory<TInterface: ?Sized + 'static, F, T>(&mut self, factory: F) -> &mut Self
    where
        F: Fn() -> Result<T, CoreError> + Send + Sync + 'static,
        T: Send + Sync + 'static;

    /// Bind a pre-created instance
    fn bind_instance<TInterface: ?Sized + 'static, TImpl: Send + Sync + Clone + 'static>(
        &mut self,
        instance: TImpl,
    ) -> &mut Self;

    /// Bind a named service
    fn bind_named<TInterface: ?Sized + 'static, TImpl: Send + Sync + Default + 'static>(
        &mut self,
        name: &str,
    ) -> &mut Self;

    /// Bind an Injectable service with auto-wiring
    fn bind_injectable<T: Injectable>(&mut self) -> &mut Self;

    /// Bind an Injectable service as singleton with auto-wiring  
    fn bind_injectable_singleton<T: Injectable>(&mut self) -> &mut Self;

    // Advanced binding methods

    /// Advanced bind with fluent configuration - returns builder for chaining
    fn bind_with<TInterface: ?Sized + 'static, TImpl: Send + Sync + Default + 'static>(
        &mut self,
    ) -> AdvancedBindingBuilder<TInterface>;

    /// Complete advanced binding with implementation
    fn with_implementation<TInterface: ?Sized + 'static, TImpl: Send + Sync + Default + 'static>(
        &mut self,
        config: BindingConfig,
    ) -> &mut Self;

    /// Bind a lazy service using factory that gets called only when needed
    fn bind_lazy<TInterface: ?Sized + 'static, F, T>(&mut self, factory: F) -> &mut Self
    where
        F: Fn() -> T + Send + Sync + 'static,
        T: Send + Sync + 'static;

    /// Bind with parameterized factory
    fn bind_parameterized_factory<TInterface: ?Sized + 'static, P, F, T>(
        &mut self,
        factory: F,
    ) -> &mut Self
    where
        F: Fn(P) -> Result<T, CoreError> + Send + Sync + 'static,
        T: Send + Sync + 'static,
        P: Send + Sync + 'static;

    /// Bind a collection of services using a closure-based configuration
    fn bind_collection<TInterface: ?Sized + 'static, F>(&mut self, configure: F) -> &mut Self
    where
        F: FnOnce(&mut CollectionBindingBuilder<TInterface>);
}

/// Builder for collection bindings that works with closure-based configuration
pub struct CollectionBindingBuilder<TInterface: ?Sized + 'static> {
    services: Vec<ServiceDescriptor>,
    _phantom: std::marker::PhantomData<*const TInterface>,
}

impl<TInterface: ?Sized + 'static> Default for CollectionBindingBuilder<TInterface> {
    fn default() -> Self {
        Self::new()
    }
}

impl<TInterface: ?Sized + 'static> CollectionBindingBuilder<TInterface> {
    pub fn new() -> Self {
        Self {
            services: Vec::new(),
            _phantom: std::marker::PhantomData,
        }
    }

    /// Add a service to the collection
    pub fn add<TImpl: Send + Sync + Default + 'static>(&mut self) -> &mut Self {
        let descriptor = ServiceDescriptor::bind::<TInterface, TImpl>()
            .with_lifetime(ServiceScope::Transient)
            .build();
        self.services.push(descriptor);
        self
    }

    /// Add a named service to the collection
    pub fn add_named<TImpl: Send + Sync + Default + 'static>(
        &mut self,
        name: impl Into<String>,
    ) -> &mut Self {
        let descriptor = ServiceDescriptor::bind_named::<TInterface, TImpl>(name)
            .with_lifetime(ServiceScope::Transient)
            .build();
        self.services.push(descriptor);
        self
    }

    /// Add a service with singleton lifetime
    pub fn add_singleton<TImpl: Send + Sync + Default + 'static>(&mut self) -> &mut Self {
        let descriptor = ServiceDescriptor::bind::<TInterface, TImpl>()
            .with_lifetime(ServiceScope::Singleton)
            .build();
        self.services.push(descriptor);
        self
    }

    /// Add a named singleton service
    pub fn add_named_singleton<TImpl: Send + Sync + Default + 'static>(
        &mut self,
        name: impl Into<String>,
    ) -> &mut Self {
        let descriptor = ServiceDescriptor::bind_named::<TInterface, TImpl>(name)
            .with_lifetime(ServiceScope::Singleton)
            .build();
        self.services.push(descriptor);
        self
    }

    /// Get the collection of service descriptors (internal use)
    pub(crate) fn into_services(self) -> Vec<ServiceDescriptor> {
        self.services
    }
}

/// Collection of service bindings
#[derive(Debug)]
pub struct ServiceBindings {
    descriptors: Vec<ServiceDescriptor>,
}

impl ServiceBindings {
    /// Create a new service bindings collection
    pub fn new() -> Self {
        Self {
            descriptors: Vec::new(),
        }
    }

    /// Add a service descriptor
    pub fn add_descriptor(&mut self, descriptor: ServiceDescriptor) {
        self.descriptors.push(descriptor);
    }

    /// Get all service descriptors
    pub fn descriptors(&self) -> &[ServiceDescriptor] {
        &self.descriptors
    }

    /// Get service descriptors by service ID
    pub fn get_descriptor(&self, service_id: &ServiceId) -> Option<&ServiceDescriptor> {
        self.descriptors
            .iter()
            .find(|d| d.service_id == *service_id)
    }

    /// Get service descriptor by type and name without allocation
    pub fn get_descriptor_named<T: 'static + ?Sized>(
        &self,
        name: &str,
    ) -> Option<&ServiceDescriptor> {
        self.descriptors
            .iter()
            .find(|d| d.service_id.matches_named::<T>(name))
    }

    /// Get all service IDs
    pub fn service_ids(&self) -> Vec<ServiceId> {
        self.descriptors
            .iter()
            .map(|d| d.service_id.clone())
            .collect()
    }

    /// Check if a service is registered
    pub fn contains(&self, service_id: &ServiceId) -> bool {
        self.descriptors.iter().any(|d| d.service_id == *service_id)
    }

    /// Check if a named service is registered without allocation
    pub fn contains_named<T: 'static + ?Sized>(&self, name: &str) -> bool {
        self.descriptors
            .iter()
            .any(|d| d.service_id.matches_named::<T>(name))
    }

    /// Get the number of registered services
    pub fn count(&self) -> usize {
        self.descriptors.len()
    }

    /// Consume self and return all descriptors
    pub fn into_descriptors(self) -> Vec<ServiceDescriptor> {
        self.descriptors
    }
}

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

impl ServiceBinder for ServiceBindings {
    fn add_service_descriptor(
        &mut self,
        descriptor: crate::container::descriptor::ServiceDescriptor,
    ) -> Result<&mut Self, crate::errors::CoreError> {
        self.add_descriptor(descriptor);
        Ok(self)
    }

    fn bind<TInterface: ?Sized + 'static, TImpl: Send + Sync + Default + 'static>(
        &mut self,
    ) -> &mut Self {
        let descriptor = ServiceDescriptor::bind::<TInterface, TImpl>()
            .with_lifetime(ServiceScope::Transient)
            .build();
        self.add_descriptor(descriptor);
        self
    }

    fn bind_singleton<TInterface: ?Sized + 'static, TImpl: Send + Sync + Default + 'static>(
        &mut self,
    ) -> &mut Self {
        let descriptor = ServiceDescriptor::bind::<TInterface, TImpl>()
            .with_lifetime(ServiceScope::Singleton)
            .build();
        self.add_descriptor(descriptor);
        self
    }

    fn bind_transient<TInterface: ?Sized + 'static, TImpl: Send + Sync + Default + 'static>(
        &mut self,
    ) -> &mut Self {
        let descriptor = ServiceDescriptor::bind::<TInterface, TImpl>()
            .with_lifetime(ServiceScope::Transient)
            .build();
        self.add_descriptor(descriptor);
        self
    }

    fn bind_factory<TInterface: ?Sized + 'static, F, T>(&mut self, factory: F) -> &mut Self
    where
        F: Fn() -> Result<T, CoreError> + Send + Sync + 'static,
        T: Send + Sync + 'static,
    {
        let descriptor = ServiceDescriptorFactoryBuilder::<TInterface>::new()
            .with_factory(factory)
            .build()
            .expect("Failed to build factory descriptor");
        self.add_descriptor(descriptor);
        self
    }

    fn bind_instance<TInterface: ?Sized + 'static, TImpl: Send + Sync + Clone + 'static>(
        &mut self,
        instance: TImpl,
    ) -> &mut Self {
        let descriptor = ServiceDescriptorFactoryBuilder::<TInterface>::new()
            .with_lifetime(ServiceScope::Singleton)
            .with_factory({
                let instance = instance.clone();
                move || -> Result<TImpl, CoreError> { Ok(instance.clone()) }
            })
            .build()
            .expect("Failed to build instance descriptor");
        self.add_descriptor(descriptor);
        self
    }

    fn bind_named<TInterface: ?Sized + 'static, TImpl: Send + Sync + Default + 'static>(
        &mut self,
        name: &str,
    ) -> &mut Self {
        let descriptor = ServiceDescriptor::bind_named::<TInterface, TImpl>(name)
            .with_lifetime(ServiceScope::Transient)
            .build();
        self.add_descriptor(descriptor);
        self
    }

    fn bind_injectable<T: Injectable>(&mut self) -> &mut Self {
        let dependencies = T::dependencies();
        let descriptor = ServiceDescriptor::autowired::<T>(dependencies);
        self.add_descriptor(descriptor);
        self
    }

    fn bind_injectable_singleton<T: Injectable>(&mut self) -> &mut Self {
        let dependencies = T::dependencies();
        let descriptor = ServiceDescriptor::autowired_singleton::<T>(dependencies);
        self.add_descriptor(descriptor);
        self
    }

    // Advanced binding methods implementation

    fn bind_with<TInterface: ?Sized + 'static, TImpl: Send + Sync + Default + 'static>(
        &mut self,
    ) -> AdvancedBindingBuilder<TInterface> {
        AdvancedBindingBuilder::new()
    }

    fn with_implementation<TInterface: ?Sized + 'static, TImpl: Send + Sync + Default + 'static>(
        &mut self,
        config: BindingConfig,
    ) -> &mut Self {
        // Only add binding if conditions are met
        if config.evaluate_conditions() {
            let mut builder = if let Some(name) = &config.name {
                ServiceDescriptor::bind_named::<TInterface, TImpl>(name.clone())
            } else {
                ServiceDescriptor::bind::<TInterface, TImpl>()
            };

            builder = builder.with_lifetime(config.lifetime);
            let descriptor = builder.build();
            self.add_descriptor(descriptor);
        }
        self
    }

    fn bind_lazy<TInterface: ?Sized + 'static, F, T>(&mut self, factory: F) -> &mut Self
    where
        F: Fn() -> T + Send + Sync + 'static,
        T: Send + Sync + 'static,
    {
        let lazy_factory = move || -> Result<T, CoreError> { Ok(factory()) };

        let descriptor = ServiceDescriptorFactoryBuilder::<TInterface>::new()
            .with_factory(lazy_factory)
            .build()
            .expect("Failed to build lazy factory descriptor");
        self.add_descriptor(descriptor);
        self
    }

    fn bind_parameterized_factory<TInterface: ?Sized + 'static, P, F, T>(
        &mut self,
        _factory: F,
    ) -> &mut Self
    where
        F: Fn(P) -> Result<T, CoreError> + Send + Sync + 'static,
        T: Send + Sync + 'static,
        P: Send + Sync + 'static,
    {
        // For now, parameterized factory stores the factory but requires parameter injection
        // This is a complex feature that would need parameter resolution at runtime
        let descriptor = ServiceDescriptorFactoryBuilder::<TInterface>::new()
            .with_factory(move || -> Result<T, CoreError> {
                // This would need to be resolved at runtime with proper parameter injection
                // For now, this is a placeholder implementation
                Err(CoreError::ServiceNotFound {
                    service_type: format!(
                        "Parameterized factory for {} requires runtime parameter resolution",
                        std::any::type_name::<TInterface>()
                    ),
                })
            })
            .build()
            .expect("Failed to build parameterized factory descriptor");
        self.add_descriptor(descriptor);
        self
    }

    fn bind_collection<TInterface: ?Sized + 'static, F>(&mut self, configure: F) -> &mut Self
    where
        F: FnOnce(&mut CollectionBindingBuilder<TInterface>),
    {
        let mut builder = CollectionBindingBuilder::new();
        configure(&mut builder);
        let services = builder.into_services();
        for service in services {
            self.add_descriptor(service);
        }
        self
    }
}

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

    #[allow(dead_code)]
    trait TestRepository: Send + Sync {
        fn find(&self, id: u32) -> Option<String>;
    }

    #[derive(Default)]
    struct PostgresRepository;

    unsafe impl Send for PostgresRepository {}
    unsafe impl Sync for PostgresRepository {}

    impl TestRepository for PostgresRepository {
        fn find(&self, _id: u32) -> Option<String> {
            Some("postgres".to_string())
        }
    }

    #[allow(dead_code)]
    trait TestService: Send + Sync {
        fn get_data(&self) -> String;
    }

    #[derive(Default)]
    struct UserService;

    unsafe impl Send for UserService {}
    unsafe impl Sync for UserService {}

    impl TestService for UserService {
        fn get_data(&self) -> String {
            "user_data".to_string()
        }
    }

    #[test]
    fn test_service_bindings() {
        let mut bindings = ServiceBindings::new();

        bindings
            .bind::<PostgresRepository, PostgresRepository>()
            .bind_singleton::<UserService, UserService>()
            .bind_named::<PostgresRepository, PostgresRepository>("postgres");

        assert_eq!(bindings.count(), 3);

        let service_ids = bindings.service_ids();
        assert_eq!(service_ids.len(), 3);

        // Check that we have the expected services
        assert!(bindings.contains(&ServiceId::of::<PostgresRepository>()));
        assert!(bindings.contains(&ServiceId::of::<UserService>()));
        assert!(bindings.contains(&ServiceId::named::<PostgresRepository>("postgres")));
    }

    #[test]
    fn test_factory_binding() {
        let mut bindings = ServiceBindings::new();

        bindings.bind_factory::<UserService, _, _>(|| Ok(UserService::default()));

        assert_eq!(bindings.count(), 1);
        assert!(bindings.contains(&ServiceId::of::<UserService>()));
    }

    #[test]
    #[serial]
    fn test_advanced_binding_with_environment_conditions() {
        let mut bindings = ServiceBindings::new();

        // Set up environment for test
        std::env::set_var("CACHE_PROVIDER", "redis");

        let config = AdvancedBindingBuilder::<dyn TestRepository>::new()
            .named("redis")
            .when_env("CACHE_PROVIDER", "redis")
            .with_lifetime(ServiceScope::Singleton)
            .config();

        bindings.with_implementation::<dyn TestRepository, PostgresRepository>(config);

        assert_eq!(bindings.count(), 1);
        assert!(bindings.contains_named::<dyn TestRepository>("redis"));

        // Clean up environment
        std::env::remove_var("CACHE_PROVIDER");
    }

    #[test]
    fn test_conditional_binding_not_met() {
        let mut bindings = ServiceBindings::new();

        // Environment condition not met
        let config = AdvancedBindingBuilder::<dyn TestRepository>::new()
            .named("nonexistent")
            .when_env("NON_EXISTENT_VAR", "value")
            .config();

        bindings.with_implementation::<dyn TestRepository, PostgresRepository>(config);

        // Should not add binding since condition is not met
        assert_eq!(bindings.count(), 0);
    }

    #[test]
    #[serial]
    fn test_feature_flag_conditions() {
        let mut bindings = ServiceBindings::new();

        // Set up feature flag
        std::env::set_var("FEATURE_ADVANCED_CACHE", "1");

        let config = AdvancedBindingBuilder::<dyn TestRepository>::new()
            .when_feature("advanced_cache")
            .config();

        bindings.with_implementation::<dyn TestRepository, PostgresRepository>(config);

        assert_eq!(bindings.count(), 1);

        // Clean up
        std::env::remove_var("FEATURE_ADVANCED_CACHE");
    }

    #[test]
    #[serial]
    fn test_profile_conditions() {
        let mut bindings = ServiceBindings::new();

        // Test with development profile
        std::env::set_var("PROFILE", "development");

        let config = AdvancedBindingBuilder::<dyn TestService>::new()
            .in_profile("development")
            .config();

        bindings.with_implementation::<dyn TestService, UserService>(config);

        assert_eq!(bindings.count(), 1);

        // Test with production profile (should not bind)
        std::env::set_var("PROFILE", "production");

        let config2 = AdvancedBindingBuilder::<dyn TestRepository>::new()
            .in_profile("development")
            .config();

        bindings.with_implementation::<dyn TestRepository, PostgresRepository>(config2);

        // Should still be 1, not 2
        assert_eq!(bindings.count(), 1);

        // Clean up
        std::env::remove_var("PROFILE");
    }

    #[test]
    fn test_custom_conditions() {
        let mut bindings = ServiceBindings::new();

        let config = AdvancedBindingBuilder::<dyn TestService>::new()
            .when(|| true) // Always true
            .config();

        bindings.with_implementation::<dyn TestService, UserService>(config);

        assert_eq!(bindings.count(), 1);

        let config2 = AdvancedBindingBuilder::<dyn TestRepository>::new()
            .when(|| false) // Always false
            .config();

        bindings.with_implementation::<dyn TestRepository, PostgresRepository>(config2);

        // Should still be 1, not 2
        assert_eq!(bindings.count(), 1);
    }

    #[test]
    fn test_lazy_binding() {
        let mut bindings = ServiceBindings::new();

        bindings.bind_lazy::<UserService, _, _>(|| UserService::default());

        assert_eq!(bindings.count(), 1);
        assert!(bindings.contains(&ServiceId::of::<UserService>()));
    }

    #[test]
    fn test_collection_binding() {
        let mut bindings = ServiceBindings::new();

        // Use the new closure-based API that actually registers services
        bindings.bind_collection::<dyn TestService, _>(|collection| {
            collection
                .add::<UserService>()
                .add_named::<UserService>("named_user_service");
        });

        // Verify that the services were actually registered in the bindings
        assert_eq!(bindings.count(), 2);
        assert!(bindings.contains(&ServiceId::of::<dyn TestService>()));
        assert!(bindings.contains(&ServiceId::named::<dyn TestService>("named_user_service")));
    }

    #[test]
    #[serial]
    fn test_multiple_conditions() {
        let mut bindings = ServiceBindings::new();

        // Set up multiple conditions
        std::env::set_var("ENV_VAR", "test_value");
        std::env::set_var("FEATURE_TEST", "1");
        std::env::set_var("PROFILE", "test");

        let config = AdvancedBindingBuilder::<dyn TestService>::new()
            .when_env("ENV_VAR", "test_value")
            .when_feature("test")
            .in_profile("test")
            .when(|| true)
            .named("complex_service")
            .with_lifetime(ServiceScope::Singleton)
            .config();

        bindings.with_implementation::<dyn TestService, UserService>(config);

        assert_eq!(bindings.count(), 1);
        assert!(bindings.contains_named::<dyn TestService>("complex_service"));

        // Clean up
        std::env::remove_var("ENV_VAR");
        std::env::remove_var("FEATURE_TEST");
        std::env::remove_var("PROFILE");
    }
}