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
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
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
use std::any::Any;
use std::collections::HashMap;
use std::sync::{Arc, RwLock};

use crate::container::autowiring::{DependencyResolver, Injectable};
use crate::container::binding::{ServiceBinder, ServiceBindings};
use crate::container::descriptor::ServiceId;
use crate::container::lifecycle::ServiceLifecycleManager;
use crate::container::resolver::DependencyResolver as GraphDependencyResolver;
use crate::container::scope::{ScopeId, ScopedServiceManager, ServiceScope};
use crate::container::tokens::{ServiceToken, TokenRegistry};
use crate::errors::CoreError;

/// Service instance storage
#[derive(Debug)]
enum ServiceInstance {
    /// Singleton instance
    Singleton(Arc<dyn Any + Send + Sync>),
    /// Scoped instances by scope ID
    Scoped(HashMap<ScopeId, Arc<dyn Any + Send + Sync>>),
}

/// Modern IoC container with proper dependency injection
#[derive(Debug)]
pub struct IocContainer {
    /// Service bindings and descriptors
    bindings: ServiceBindings,
    /// Token-based service registry
    tokens: TokenRegistry,
    /// Dependency resolver
    resolver: Option<GraphDependencyResolver>,
    /// Instantiated services
    instances: Arc<RwLock<HashMap<ServiceId, ServiceInstance>>>,
    /// Service lifecycle manager
    lifecycle_manager: ServiceLifecycleManager,
    /// Active scopes
    scopes: Arc<RwLock<HashMap<ScopeId, Arc<ScopedServiceManager>>>>,
    /// Whether the container is built and ready
    is_built: bool,
}

impl IocContainer {
    /// Create a new IoC container
    pub fn new() -> Self {
        Self {
            bindings: ServiceBindings::new(),
            tokens: TokenRegistry::new(),
            resolver: None,
            instances: Arc::new(RwLock::new(HashMap::new())),
            lifecycle_manager: ServiceLifecycleManager::new(),
            scopes: Arc::new(RwLock::new(HashMap::new())),
            is_built: false,
        }
    }

    /// Create IoC container from existing bindings
    pub fn from_bindings(bindings: ServiceBindings) -> Self {
        Self {
            bindings,
            tokens: TokenRegistry::new(),
            resolver: None,
            instances: Arc::new(RwLock::new(HashMap::new())),
            lifecycle_manager: ServiceLifecycleManager::new(),
            scopes: Arc::new(RwLock::new(HashMap::new())),
            is_built: false,
        }
    }

    /// Build the container and prepare for service resolution
    pub fn build(&mut self) -> Result<(), CoreError> {
        if self.is_built {
            return Ok(());
        }

        // Build dependency resolver
        let resolver = GraphDependencyResolver::new(self.bindings.descriptors())?;
        self.resolver = Some(resolver);

        // Validate dependencies
        let service_ids = self.bindings.service_ids().into_iter().collect();
        if let Some(resolver) = &self.resolver {
            resolver.validate_dependencies(&service_ids)?;
        }

        self.is_built = true;
        Ok(())
    }

    /// Initialize all async services
    pub async fn initialize_async(&mut self) -> Result<(), CoreError> {
        self.lifecycle_manager.initialize_all().await
    }

    /// Initialize all async services with timeout
    pub async fn initialize_async_with_timeout(
        &mut self,
        timeout: std::time::Duration,
    ) -> Result<(), CoreError> {
        self.lifecycle_manager
            .initialize_all_with_timeout(timeout)
            .await
    }

    /// Create a new service scope
    pub fn create_scope(&self) -> Result<ScopeId, CoreError> {
        let scope_manager = Arc::new(ScopedServiceManager::new());
        let scope_id = scope_manager.scope_id().clone();

        let mut scopes = self.scopes.write().map_err(|_| CoreError::LockError {
            resource: "scopes".to_string(),
        })?;

        scopes.insert(scope_id.clone(), scope_manager);
        Ok(scope_id)
    }

    /// Create a child scope from an existing scope
    pub fn create_child_scope(&self, parent_scope_id: &ScopeId) -> Result<ScopeId, CoreError> {
        let mut scopes = self.scopes.write().map_err(|_| CoreError::LockError {
            resource: "scopes".to_string(),
        })?;

        let parent_scope = scopes
            .get(parent_scope_id)
            .ok_or_else(|| CoreError::ServiceNotFound {
                service_type: format!("parent scope {}", parent_scope_id),
            })?
            .clone(); // Clone the Arc, not the ScopedServiceManager

        let child_scope = Arc::new(ScopedServiceManager::create_child(parent_scope));
        let child_scope_id = child_scope.scope_id().clone();

        scopes.insert(child_scope_id.clone(), child_scope);
        Ok(child_scope_id)
    }

    /// Dispose of a scope and all its services
    pub async fn dispose_scope(&self, scope_id: &ScopeId) -> Result<(), CoreError> {
        let was_removed = {
            let mut scopes = self.scopes.write().map_err(|_| CoreError::LockError {
                resource: "scopes".to_string(),
            })?;
            scopes.remove(scope_id).is_some()
        };

        if was_removed {
            // Remove scoped instances for this scope
            let mut instances = self.instances.write().map_err(|_| CoreError::LockError {
                resource: "service_instances".to_string(),
            })?;

            for (_, instance) in instances.iter_mut() {
                if let ServiceInstance::Scoped(scoped_instances) = instance {
                    scoped_instances.remove(scope_id);
                }
            }
        }

        Ok(())
    }

    /// Dispose all scoped services and lifecycle managed services
    pub async fn dispose_all(&mut self) -> Result<(), CoreError> {
        // Dispose all scoped services first
        let scope_ids: Vec<ScopeId> = {
            let scopes = self.scopes.read().map_err(|_| CoreError::LockError {
                resource: "scopes".to_string(),
            })?;
            scopes.keys().cloned().collect()
        };

        for scope_id in scope_ids {
            self.dispose_scope(&scope_id).await?;
        }

        // Dispose lifecycle managed services
        self.lifecycle_manager.dispose_all().await?;

        Ok(())
    }

    /// Get a reference to the lifecycle manager
    pub fn lifecycle_manager(&self) -> &ServiceLifecycleManager {
        &self.lifecycle_manager
    }

    /// Get a mutable reference to the lifecycle manager
    pub fn lifecycle_manager_mut(&mut self) -> &mut ServiceLifecycleManager {
        &mut self.lifecycle_manager
    }

    /// Resolve a service by type
    pub fn resolve<T: Send + Sync + 'static>(&self) -> Result<Arc<T>, CoreError> {
        let service_id = ServiceId::of::<T>();
        self.resolve_by_id(&service_id)
    }

    /// Resolve a scoped service by type
    pub fn resolve_scoped<T: Send + Sync + 'static>(
        &self,
        scope_id: &ScopeId,
    ) -> Result<Arc<T>, CoreError> {
        let service_id = ServiceId::of::<T>();
        self.resolve_by_id_scoped(&service_id, scope_id)
    }

    /// Resolve a named service
    pub fn resolve_named<T: Send + Sync + 'static>(&self, name: &str) -> Result<Arc<T>, CoreError> {
        self.resolve_named_by_str::<T>(name)
    }

    /// Resolve a named service efficiently without allocating ServiceId
    fn resolve_named_by_str<T: Send + Sync + 'static>(
        &self,
        name: &str,
    ) -> Result<Arc<T>, CoreError> {
        if !self.is_built {
            return Err(CoreError::InvalidServiceDescriptor {
                message: "Container must be built before resolving services".to_string(),
            });
        }

        // Check if we have a cached instance - we need to create ServiceId for lookup in instances
        let service_id = ServiceId::named::<T>(name.to_string());
        {
            let instances = self.instances.read().map_err(|_| CoreError::LockError {
                resource: "service_instances".to_string(),
            })?;

            if let Some(ServiceInstance::Singleton(instance)) = instances.get(&service_id) {
                return instance
                    .clone()
                    .downcast::<T>()
                    .map_err(|_| CoreError::ServiceNotFound {
                        service_type: format!("{}({})", std::any::type_name::<T>(), name),
                    });
            }
        }

        // Get service descriptor efficiently without allocating ServiceId
        let descriptor = self
            .bindings
            .get_descriptor_named::<T>(name)
            .ok_or_else(|| CoreError::ServiceNotFound {
                service_type: format!("{}({})", std::any::type_name::<T>(), name),
            })?;

        // Resolve dependencies first
        self.resolve_dependencies(&descriptor.dependencies)?;

        // Create the service instance based on activation strategy
        let arc_instance = match &descriptor.activation_strategy {
            crate::container::descriptor::ServiceActivationStrategy::Factory(factory) => {
                let instance = factory()?;
                let typed_instance =
                    instance
                        .downcast::<T>()
                        .map_err(|_| CoreError::ServiceNotFound {
                            service_type: format!("{}({})", std::any::type_name::<T>(), name),
                        })?;
                Arc::new(*typed_instance)
            }
            crate::container::descriptor::ServiceActivationStrategy::AutoWired => {
                return Err(CoreError::InvalidServiceDescriptor {
                    message: format!(
                        "Service {}({}) is marked as auto-wired but resolve_named was called instead of resolve_injectable. Use resolve_injectable() for auto-wired services.",
                        std::any::type_name::<T>(),
                        name
                    ),
                });
            }
        };

        // Cache if singleton (we already have the ServiceId)
        if descriptor.lifetime == ServiceScope::Singleton {
            let mut instances = self.instances.write().map_err(|_| CoreError::LockError {
                resource: "service_instances".to_string(),
            })?;
            instances.insert(service_id, ServiceInstance::Singleton(arc_instance.clone()));
        }

        Ok(arc_instance)
    }

    /// Resolve a service by service ID
    fn resolve_by_id<T: Send + Sync + 'static>(
        &self,
        service_id: &ServiceId,
    ) -> Result<Arc<T>, CoreError> {
        if !self.is_built {
            return Err(CoreError::InvalidServiceDescriptor {
                message: "Container must be built before resolving services".to_string(),
            });
        }

        // Check if we have a cached instance
        {
            let instances = self.instances.read().map_err(|_| CoreError::LockError {
                resource: "service_instances".to_string(),
            })?;

            if let Some(ServiceInstance::Singleton(instance)) = instances.get(service_id) {
                return instance
                    .clone()
                    .downcast::<T>()
                    .map_err(|_| CoreError::ServiceNotFound {
                        service_type: format!(
                            "{}({})",
                            std::any::type_name::<T>(),
                            service_id.name.as_deref().unwrap_or("default")
                        ),
                    });
            }
        }

        // Get service descriptor
        let descriptor =
            self.bindings
                .get_descriptor(service_id)
                .ok_or_else(|| CoreError::ServiceNotFound {
                    service_type: format!(
                        "{}({})",
                        std::any::type_name::<T>(),
                        service_id.name.as_deref().unwrap_or("default")
                    ),
                })?;

        // Resolve dependencies first
        self.resolve_dependencies(&descriptor.dependencies)?;

        // Create the service instance based on activation strategy
        let arc_instance = match &descriptor.activation_strategy {
            crate::container::descriptor::ServiceActivationStrategy::Factory(factory) => {
                let instance = factory()?;
                let typed_instance =
                    instance
                        .downcast::<T>()
                        .map_err(|_| CoreError::ServiceNotFound {
                            service_type: format!(
                                "{}({})",
                                std::any::type_name::<T>(),
                                service_id.name.as_deref().unwrap_or("default")
                            ),
                        })?;
                Arc::new(*typed_instance)
            }
            crate::container::descriptor::ServiceActivationStrategy::AutoWired => {
                return Err(CoreError::InvalidServiceDescriptor {
                    message: format!(
                        "Service {} is marked as auto-wired but resolve_by_id was called instead of resolve_injectable. Use resolve_injectable() for auto-wired services.",
                        std::any::type_name::<T>()
                    ),
                });
            }
        };

        // Cache if singleton
        if descriptor.lifetime == ServiceScope::Singleton {
            let mut instances = self.instances.write().map_err(|_| CoreError::LockError {
                resource: "service_instances".to_string(),
            })?;
            instances.insert(
                service_id.clone(),
                ServiceInstance::Singleton(arc_instance.clone()),
            );
        }

        Ok(arc_instance)
    }

    /// Resolve a service by service ID in a specific scope
    fn resolve_by_id_scoped<T: Send + Sync + 'static>(
        &self,
        service_id: &ServiceId,
        scope_id: &ScopeId,
    ) -> Result<Arc<T>, CoreError> {
        if !self.is_built {
            return Err(CoreError::InvalidServiceDescriptor {
                message: "Container must be built before resolving services".to_string(),
            });
        }

        // Get service descriptor first to check lifetime
        let descriptor =
            self.bindings
                .get_descriptor(service_id)
                .ok_or_else(|| CoreError::ServiceNotFound {
                    service_type: format!(
                        "{}({})",
                        std::any::type_name::<T>(),
                        service_id.name.as_deref().unwrap_or("default")
                    ),
                })?;

        // Handle based on lifetime
        match descriptor.lifetime {
            ServiceScope::Singleton => {
                // For singleton, ignore scope and use regular resolution
                self.resolve_by_id(service_id)
            }
            ServiceScope::Transient => {
                // For transient, create new instance every time
                self.create_service_instance::<T>(service_id, descriptor)
            }
            ServiceScope::Scoped => {
                // Check if we have a cached instance for this scope
                {
                    let instances = self.instances.read().map_err(|_| CoreError::LockError {
                        resource: "service_instances".to_string(),
                    })?;

                    if let Some(ServiceInstance::Scoped(scoped_instances)) =
                        instances.get(service_id)
                    {
                        if let Some(instance) = scoped_instances.get(scope_id) {
                            return instance.clone().downcast::<T>().map_err(|_| {
                                CoreError::ServiceNotFound {
                                    service_type: format!(
                                        "{}({})",
                                        std::any::type_name::<T>(),
                                        service_id.name.as_deref().unwrap_or("default")
                                    ),
                                }
                            });
                        }
                    }
                }

                // Create new scoped instance
                let arc_instance = self.create_service_instance::<T>(service_id, descriptor)?;

                // Cache it for this scope
                let mut instances = self.instances.write().map_err(|_| CoreError::LockError {
                    resource: "service_instances".to_string(),
                })?;

                use std::collections::hash_map::Entry;
                match instances.entry(service_id.clone()) {
                    Entry::Occupied(mut entry) => match entry.get_mut() {
                        ServiceInstance::Scoped(scoped_instances) => {
                            scoped_instances.insert(
                                scope_id.clone(),
                                arc_instance.clone() as Arc<dyn Any + Send + Sync>,
                            );
                        }
                        ServiceInstance::Singleton(_) => {
                            return Err(CoreError::InvalidServiceDescriptor {
                                    message: format!(
                                        "Service {} is registered as both Singleton and Scoped. This is a configuration error.",
                                        std::any::type_name::<T>()
                                    ),
                                });
                        }
                    },
                    Entry::Vacant(entry) => {
                        let mut scoped_map = HashMap::new();
                        scoped_map.insert(
                            scope_id.clone(),
                            arc_instance.clone() as Arc<dyn Any + Send + Sync>,
                        );
                        entry.insert(ServiceInstance::Scoped(scoped_map));
                    }
                }

                Ok(arc_instance)
            }
        }
    }

    /// Create a service instance
    fn create_service_instance<T: Send + Sync + 'static>(
        &self,
        service_id: &ServiceId,
        descriptor: &crate::container::descriptor::ServiceDescriptor,
    ) -> Result<Arc<T>, CoreError> {
        // Resolve dependencies first
        self.resolve_dependencies(&descriptor.dependencies)?;

        // Create the service instance based on activation strategy
        match &descriptor.activation_strategy {
            crate::container::descriptor::ServiceActivationStrategy::Factory(factory) => {
                let instance = factory()?;
                let typed_instance = instance.downcast::<T>()
                    .map_err(|_| CoreError::ServiceNotFound {
                        service_type: format!("{}({})", 
                            std::any::type_name::<T>(),
                            service_id.name.as_deref().unwrap_or("default")
                        ),
                    })?;
                Ok(Arc::new(*typed_instance))
            },
            crate::container::descriptor::ServiceActivationStrategy::AutoWired => {
                Err(CoreError::InvalidServiceDescriptor {
                    message: format!(
                        "Service {} is marked as auto-wired but create_service_instance was called. Use resolve_injectable() for auto-wired services.",
                        std::any::type_name::<T>()
                    ),
                })
            }
        }
    }

    /// Resolve all dependencies for a service
    fn resolve_dependencies(&self, dependencies: &[ServiceId]) -> Result<(), CoreError> {
        for dep_id in dependencies {
            // For now, we'll just validate that the dependency exists
            if !self.bindings.contains(dep_id) {
                return Err(CoreError::ServiceNotFound {
                    service_type: format!(
                        "{}({})",
                        dep_id.type_name(),
                        dep_id.name.as_deref().unwrap_or("default")
                    ),
                });
            }
        }
        Ok(())
    }

    /// Try to resolve a service, returning None if not found
    pub fn try_resolve<T: Send + Sync + 'static>(&self) -> Option<Arc<T>> {
        self.resolve::<T>().ok()
    }

    /// Try to resolve a named service, returning None if not found
    pub fn try_resolve_named<T: Send + Sync + 'static>(&self, name: &str) -> Option<Arc<T>> {
        self.resolve_named::<T>(name).ok()
    }

    /// Resolve a service using the Injectable trait (auto-wiring)
    pub fn resolve_injectable<T: Injectable>(&self) -> Result<Arc<T>, CoreError> {
        if !self.is_built {
            return Err(CoreError::InvalidServiceDescriptor {
                message: "Container must be built before resolving services".to_string(),
            });
        }

        let service_id = ServiceId::of::<T>();

        // Check if we have a cached instance
        {
            let instances = self.instances.read().map_err(|_| CoreError::LockError {
                resource: "service_instances".to_string(),
            })?;

            if let Some(ServiceInstance::Singleton(instance)) = instances.get(&service_id) {
                return instance
                    .clone()
                    .downcast::<T>()
                    .map_err(|_| CoreError::ServiceNotFound {
                        service_type: std::any::type_name::<T>().to_string(),
                    });
            }
        }

        // Verify the service is configured for auto-wiring
        let descriptor = self.bindings.get_descriptor(&service_id).ok_or_else(|| {
            CoreError::ServiceNotFound {
                service_type: std::any::type_name::<T>().to_string(),
            }
        })?;

        let arc_instance = match &descriptor.activation_strategy {
            crate::container::descriptor::ServiceActivationStrategy::AutoWired => {
                // Create the service using Injectable
                let service_instance = T::create(self)?;
                Arc::new(service_instance)
            }
            crate::container::descriptor::ServiceActivationStrategy::Factory(_) => {
                return Err(CoreError::InvalidServiceDescriptor {
                    message: format!(
                        "Service {} is configured with a factory but resolve_injectable was called. Use resolve() for factory-based services.",
                        std::any::type_name::<T>()
                    ),
                });
            }
        };

        // Cache if singleton
        if descriptor.lifetime == ServiceScope::Singleton {
            let mut instances = self.instances.write().map_err(|_| CoreError::LockError {
                resource: "service_instances".to_string(),
            })?;
            instances.insert(service_id, ServiceInstance::Singleton(arc_instance.clone()));
        }

        Ok(arc_instance)
    }

    /// Resolve a trait object by downcasting from a concrete implementation
    pub fn resolve_trait<T: ?Sized + Send + Sync + 'static>(&self) -> Result<Arc<T>, CoreError> {
        // For trait objects, we need special handling
        // This is a placeholder - in a real implementation, we'd need metadata about
        // which concrete type implements which trait
        Err(CoreError::ServiceNotFound {
            service_type: std::any::type_name::<T>().to_string(),
        })
    }

    /// Bind a service token to a concrete implementation with transient lifetime
    ///
    /// This creates a mapping from a service token to a concrete implementation,
    /// enabling semantic dependency resolution through tokens.
    ///
    /// ## Example
    /// ```rust
    /// use elif_core::container::{IocContainer, ServiceToken};
    ///
    /// // Define service trait and token
    /// trait EmailService: Send + Sync {}
    /// struct EmailToken;
    /// impl ServiceToken for EmailToken {
    ///     type Service = dyn EmailService;
    /// }
    ///
    /// // Implementation
    /// #[derive(Default)]
    /// struct SmtpService;
    /// impl EmailService for SmtpService {}
    ///
    /// // Bind token to implementation
    /// let mut container = IocContainer::new();
    /// container.bind_token::<EmailToken, SmtpService>()?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn bind_token<Token, Impl>(&mut self) -> Result<&mut Self, CoreError>
    where
        Token: ServiceToken,
        Impl: Send + Sync + Default + 'static,
    {
        self.bind_token_with_lifetime::<Token, Impl>(ServiceScope::Transient)
    }

    /// Bind a service token to a concrete implementation as a singleton
    pub fn bind_token_singleton<Token, Impl>(&mut self) -> Result<&mut Self, CoreError>
    where
        Token: ServiceToken,
        Impl: Send + Sync + Default + 'static,
    {
        self.bind_token_with_lifetime::<Token, Impl>(ServiceScope::Singleton)
    }

    /// Bind a service token to a concrete implementation as a scoped service
    pub fn bind_token_scoped<Token, Impl>(&mut self) -> Result<&mut Self, CoreError>
    where
        Token: ServiceToken,
        Impl: Send + Sync + Default + 'static,
    {
        self.bind_token_with_lifetime::<Token, Impl>(ServiceScope::Scoped)
    }

    /// Bind a service token to a concrete implementation with a specific lifetime
    pub fn bind_token_with_lifetime<Token, Impl>(
        &mut self,
        lifetime: ServiceScope,
    ) -> Result<&mut Self, CoreError>
    where
        Token: ServiceToken,
        Impl: Send + Sync + Default + 'static,
    {
        if self.is_built {
            return Err(CoreError::InvalidServiceDescriptor {
                message: "Cannot bind tokens after container is built".to_string(),
            });
        }

        // Register the token binding
        self.tokens
            .register::<Token, Impl>()
            .map_err(|e| CoreError::InvalidServiceDescriptor {
                message: format!("Failed to register token binding: {}", e),
            })?;

        // Get the token binding to create a service descriptor
        let token_binding = self.tokens.get_default::<Token>().ok_or_else(|| {
            CoreError::InvalidServiceDescriptor {
                message: "Failed to retrieve token binding after registration".to_string(),
            }
        })?;

        // Create service descriptor for the implementation
        let service_id = token_binding.to_service_id();

        // Create a service descriptor directly with the token's service ID and specified lifetime
        let descriptor = crate::container::descriptor::ServiceDescriptor {
            service_id,
            implementation_id: std::any::TypeId::of::<Impl>(),
            lifetime,
            activation_strategy: crate::container::descriptor::ServiceActivationStrategy::Factory(
                Box::new(|| Ok(Box::new(Impl::default()) as Box<dyn Any + Send + Sync>)),
            ),
            dependencies: Vec::new(),
        };

        self.bindings.add_descriptor(descriptor);

        Ok(self)
    }

    /// Bind a named service token to a concrete implementation
    pub fn bind_token_named<Token, Impl>(
        &mut self,
        name: impl Into<String>,
    ) -> Result<&mut Self, CoreError>
    where
        Token: ServiceToken,
        Impl: Send + Sync + Default + 'static,
    {
        if self.is_built {
            return Err(CoreError::InvalidServiceDescriptor {
                message: "Cannot bind tokens after container is built".to_string(),
            });
        }

        let name = name.into();

        // Register the named token binding
        self.tokens
            .register_named::<Token, Impl>(&name)
            .map_err(|e| CoreError::InvalidServiceDescriptor {
                message: format!("Failed to register named token binding: {}", e),
            })?;

        // Get the token binding to create a service descriptor
        let token_binding = self.tokens.get_named::<Token>(&name).ok_or_else(|| {
            CoreError::InvalidServiceDescriptor {
                message: "Failed to retrieve named token binding after registration".to_string(),
            }
        })?;

        // Create service descriptor for the implementation
        let service_id = token_binding.to_service_id();

        // Create a service descriptor directly with the token's service ID
        let descriptor = crate::container::descriptor::ServiceDescriptor {
            service_id,
            implementation_id: std::any::TypeId::of::<Impl>(),
            lifetime: ServiceScope::Transient,
            activation_strategy: crate::container::descriptor::ServiceActivationStrategy::Factory(
                Box::new(|| Ok(Box::new(Impl::default()) as Box<dyn Any + Send + Sync>)),
            ),
            dependencies: Vec::new(),
        };

        self.bindings.add_descriptor(descriptor);

        Ok(self)
    }

    /// Resolve a service by its token type
    ///
    /// This enables semantic dependency resolution where services are identified
    /// by tokens rather than concrete types, enabling true dependency inversion.
    ///
    /// ## Example
    /// ```rust
    /// use std::sync::Arc;
    /// use elif_core::container::{IocContainer, ServiceToken};
    ///
    /// // Define service trait and token
    /// trait EmailService: Send + Sync {
    ///     fn send(&self, to: &str, subject: &str, body: &str) -> Result<(), String>;
    /// }
    /// struct EmailToken;
    /// impl ServiceToken for EmailToken {
    ///     type Service = dyn EmailService;
    /// }
    ///
    /// // Implementation
    /// #[derive(Default)]
    /// struct SmtpService;
    /// impl EmailService for SmtpService {
    ///     fn send(&self, _to: &str, _subject: &str, _body: &str) -> Result<(), String> {
    ///         Ok(()) // Mock implementation
    ///     }
    /// }
    ///
    /// // Setup and resolve
    /// let mut container = IocContainer::new();
    /// container.bind_token::<EmailToken, SmtpService>()?;
    /// container.build()?;
    /// 
    /// // Note: Trait object resolution is not yet fully implemented
    /// // This will be available in a future version:
    /// // let service: Arc<dyn EmailService> = container.resolve_by_token::<EmailToken>()?;
    /// // service.send("user@example.com", "Welcome", "Hello world!")?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn resolve_by_token<Token>(&self) -> Result<Arc<Token::Service>, CoreError>
    where
        Token: ServiceToken,
        Token::Service: 'static,
    {
        if !self.is_built {
            return Err(CoreError::InvalidServiceDescriptor {
                message: "Container must be built before resolving services".to_string(),
            });
        }

        // Get the token binding
        let token_binding =
            self.tokens
                .get_default::<Token>()
                .ok_or_else(|| CoreError::ServiceNotFound {
                    service_type: format!(
                        "token {} -> {}",
                        Token::token_type_name(),
                        Token::service_type_name()
                    ),
                })?;

        // Create service ID and resolve
        let service_id = token_binding.to_service_id();

        // Use a type-erased approach for trait object resolution
        // We need to resolve the concrete implementation and cast it to the trait
        self.resolve_by_id_as_trait::<Token::Service>(&service_id)
    }

    /// Resolve a named service by its token type
    pub fn resolve_by_token_named<Token>(
        &self,
        name: &str,
    ) -> Result<Arc<Token::Service>, CoreError>
    where
        Token: ServiceToken,
        Token::Service: 'static,
    {
        if !self.is_built {
            return Err(CoreError::InvalidServiceDescriptor {
                message: "Container must be built before resolving services".to_string(),
            });
        }

        // Get the named token binding
        let token_binding =
            self.tokens
                .get_named::<Token>(name)
                .ok_or_else(|| CoreError::ServiceNotFound {
                    service_type: format!(
                        "named token {}({}) -> {}",
                        Token::token_type_name(),
                        name,
                        Token::service_type_name()
                    ),
                })?;

        // Create service ID and resolve
        let service_id = token_binding.to_service_id();

        // Use a type-erased approach for trait object resolution
        self.resolve_by_id_as_trait::<Token::Service>(&service_id)
    }

    /// Try to resolve a service by its token type, returning None if not found
    pub fn try_resolve_by_token<Token>(&self) -> Option<Arc<Token::Service>>
    where
        Token: ServiceToken,
        Token::Service: 'static,
    {
        self.resolve_by_token::<Token>().ok()
    }

    /// Try to resolve a named service by its token type, returning None if not found
    pub fn try_resolve_by_token_named<Token>(&self, name: &str) -> Option<Arc<Token::Service>>
    where
        Token: ServiceToken,
        Token::Service: 'static,
    {
        self.resolve_by_token_named::<Token>(name).ok()
    }

    /// Resolve a scoped service by its token type
    ///
    /// This resolves services within a specific scope, maintaining the lifecycle
    /// and cleanup patterns expected by the existing scope management system.
    pub fn resolve_by_token_scoped<Token>(
        &self,
        scope_id: &ScopeId,
    ) -> Result<Arc<Token::Service>, CoreError>
    where
        Token: ServiceToken,
        Token::Service: 'static,
    {
        if !self.is_built {
            return Err(CoreError::InvalidServiceDescriptor {
                message: "Container must be built before resolving services".to_string(),
            });
        }

        // Get the token binding
        let token_binding =
            self.tokens
                .get_default::<Token>()
                .ok_or_else(|| CoreError::ServiceNotFound {
                    service_type: format!(
                        "token {} -> {}",
                        Token::token_type_name(),
                        Token::service_type_name()
                    ),
                })?;

        // Create service ID and resolve in the specified scope
        let service_id = token_binding.to_service_id();

        // Use a type-erased approach for trait object resolution in scoped context
        self.resolve_by_id_as_trait_scoped::<Token::Service>(&service_id, scope_id)
    }

    /// Resolve a named scoped service by its token type
    pub fn resolve_by_token_named_scoped<Token>(
        &self,
        name: &str,
        scope_id: &ScopeId,
    ) -> Result<Arc<Token::Service>, CoreError>
    where
        Token: ServiceToken,
        Token::Service: 'static,
    {
        if !self.is_built {
            return Err(CoreError::InvalidServiceDescriptor {
                message: "Container must be built before resolving services".to_string(),
            });
        }

        // Get the named token binding
        let token_binding =
            self.tokens
                .get_named::<Token>(name)
                .ok_or_else(|| CoreError::ServiceNotFound {
                    service_type: format!(
                        "named token {}({}) -> {}",
                        Token::token_type_name(),
                        name,
                        Token::service_type_name()
                    ),
                })?;

        // Create service ID and resolve in the specified scope
        let service_id = token_binding.to_service_id();

        // Use a type-erased approach for trait object resolution in scoped context
        self.resolve_by_id_as_trait_scoped::<Token::Service>(&service_id, scope_id)
    }

    /// Try to resolve a scoped service by its token type, returning None if not found
    pub fn try_resolve_by_token_scoped<Token>(
        &self,
        scope_id: &ScopeId,
    ) -> Option<Arc<Token::Service>>
    where
        Token: ServiceToken,
        Token::Service: 'static,
    {
        self.resolve_by_token_scoped::<Token>(scope_id).ok()
    }

    /// Try to resolve a named scoped service by its token type, returning None if not found
    pub fn try_resolve_by_token_named_scoped<Token>(
        &self,
        name: &str,
        scope_id: &ScopeId,
    ) -> Option<Arc<Token::Service>>
    where
        Token: ServiceToken,
        Token::Service: 'static,
    {
        self.resolve_by_token_named_scoped::<Token>(name, scope_id)
            .ok()
    }

    /// Check if a token is registered
    pub fn contains_token<Token: ServiceToken>(&self) -> bool {
        self.tokens.contains::<Token>()
    }

    /// Check if a named token is registered
    pub fn contains_token_named<Token: ServiceToken>(&self, name: &str) -> bool {
        self.tokens.contains_named::<Token>(name)
    }

    /// Get token registry statistics
    pub fn token_stats(&self) -> crate::container::tokens::TokenRegistryStats {
        self.tokens.stats()
    }

    /// Internal method to resolve services as trait objects
    ///
    /// This handles the complex type casting required for trait object resolution
    fn resolve_by_id_as_trait<T: ?Sized + Send + Sync + 'static>(
        &self,
        service_id: &ServiceId,
    ) -> Result<Arc<T>, CoreError> {
        // For now, this is a simplified implementation
        // In a full implementation, we would need more sophisticated trait object handling
        // that involves storing metadata about how to cast concrete types to trait objects

        // This is a placeholder that shows the intended API
        // The actual implementation would require additional metadata in the token bindings
        Err(CoreError::ServiceNotFound {
            service_type: format!(
                "trait object resolution not yet fully implemented for service {}",
                service_id.type_name()
            ),
        })
    }

    /// Internal method to resolve scoped services as trait objects
    ///
    /// This handles scoped trait object resolution with proper lifecycle management
    fn resolve_by_id_as_trait_scoped<T: ?Sized + Send + Sync + 'static>(
        &self,
        service_id: &ServiceId,
        _scope_id: &ScopeId,
    ) -> Result<Arc<T>, CoreError> {
        // For now, this is a simplified implementation
        // In a full implementation, this would integrate with the scoped service resolution
        // and maintain proper lifecycle management within the specified scope

        // This is a placeholder that shows the intended API
        // The actual implementation would require additional metadata in the token bindings
        // and proper integration with the scope management system
        Err(CoreError::ServiceNotFound {
            service_type: format!(
                "scoped trait object resolution not yet fully implemented for service {}",
                service_id.type_name()
            ),
        })
    }

    /// Check if a service is registered
    pub fn contains<T: 'static>(&self) -> bool {
        let service_id = ServiceId::of::<T>();
        self.bindings.contains(&service_id)
    }

    /// Check if a named service is registered
    pub fn contains_named<T: 'static>(&self, name: &str) -> bool {
        self.bindings.contains_named::<T>(name)
    }

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

    /// Get all registered service IDs
    pub fn registered_services(&self) -> Vec<ServiceId> {
        self.bindings.service_ids()
    }

    /// Check if the container is built and ready
    pub fn is_built(&self) -> bool {
        self.is_built
    }

    /// Validate the container configuration
    pub fn validate(&self) -> Result<(), CoreError> {
        if !self.is_built {
            return Err(CoreError::InvalidServiceDescriptor {
                message: "Container must be built before validation".to_string(),
            });
        }

        // Validate dependency resolution
        if let Some(resolver) = &self.resolver {
            let service_ids = self.bindings.service_ids().into_iter().collect();
            resolver.validate_dependencies(&service_ids)?;
        }

        Ok(())
    }

    /// Resolve all implementations of an interface as a vector
    pub fn resolve_all<T: Send + Sync + 'static>(&self) -> Result<Vec<Arc<T>>, CoreError> {
        if !self.is_built {
            return Err(CoreError::InvalidServiceDescriptor {
                message: "Container must be built before resolving services".to_string(),
            });
        }

        let mut implementations = Vec::new();

        // Find all descriptors that match the type
        for descriptor in self.bindings.descriptors() {
            if descriptor.service_id.type_id == std::any::TypeId::of::<T>() {
                match self.resolve_by_id::<T>(&descriptor.service_id) {
                    Ok(instance) => implementations.push(instance),
                    Err(_) => continue, // Skip failed resolutions
                }
            }
        }

        if implementations.is_empty() {
            return Err(CoreError::ServiceNotFound {
                service_type: std::any::type_name::<T>().to_string(),
            });
        }

        Ok(implementations)
    }

    /// Resolve all implementations of an interface as a HashMap with their names
    pub fn resolve_all_named<T: Send + Sync + 'static>(
        &self,
    ) -> Result<std::collections::HashMap<String, Arc<T>>, CoreError> {
        if !self.is_built {
            return Err(CoreError::InvalidServiceDescriptor {
                message: "Container must be built before resolving services".to_string(),
            });
        }

        let mut implementations = std::collections::HashMap::new();

        // Find all named descriptors that match the type
        for descriptor in self.bindings.descriptors() {
            if descriptor.service_id.type_id == std::any::TypeId::of::<T>() {
                if let Some(name) = &descriptor.service_id.name {
                    match self.resolve_by_id::<T>(&descriptor.service_id) {
                        Ok(instance) => {
                            implementations.insert(name.clone(), instance);
                        }
                        Err(_) => continue, // Skip failed resolutions
                    }
                }
            }
        }

        if implementations.is_empty() {
            return Err(CoreError::ServiceNotFound {
                service_type: format!("named implementations of {}", std::any::type_name::<T>()),
            });
        }

        Ok(implementations)
    }

    /// Get default implementation for a type (marked with is_default in BindingConfig)
    pub fn resolve_default<T: Send + Sync + 'static>(&self) -> Result<Arc<T>, CoreError> {
        // For now, just resolve the first unnamed implementation
        // In a full implementation, we'd track which binding was marked as default
        self.resolve::<T>()
    }

    /// Get service information for debugging
    pub fn get_service_info<T: 'static>(&self) -> Option<String> {
        let service_id = ServiceId::of::<T>();
        self.bindings
            .get_descriptor(&service_id)
            .map(|desc| format!("{:?}", desc))
    }

    /// Get all registered service IDs for debugging
    pub fn get_registered_services(&self) -> Vec<String> {
        self.bindings
            .service_ids()
            .into_iter()
            .map(|id| {
                format!(
                    "{} ({})",
                    id.type_name(),
                    id.name.unwrap_or_else(|| "default".to_string())
                )
            })
            .collect()
    }

    /// Validate that all registered services can be resolved
    pub fn validate_all_services(&self) -> Result<(), Vec<CoreError>> {
        if !self.is_built {
            return Err(vec![CoreError::InvalidServiceDescriptor {
                message: "Container must be built before validation".to_string(),
            }]);
        }

        let mut errors = Vec::new();

        for descriptor in self.bindings.descriptors() {
            // Validate dependencies exist
            for dependency in &descriptor.dependencies {
                if !self.bindings.contains(dependency) {
                    errors.push(CoreError::ServiceNotFound {
                        service_type: format!(
                            "{} (dependency of {})",
                            dependency.type_name(),
                            descriptor.service_id.type_name()
                        ),
                    });
                }
            }
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }

    /// Get service statistics
    pub fn get_statistics(&self) -> ServiceStatistics {
        let mut stats = ServiceStatistics::default();

        stats.total_services = self.bindings.count();
        stats.singleton_services = 0;
        stats.transient_services = 0;
        stats.scoped_services = 0;
        stats.cached_instances = 0;

        for descriptor in self.bindings.descriptors() {
            match descriptor.lifetime {
                crate::container::scope::ServiceScope::Singleton => stats.singleton_services += 1,
                crate::container::scope::ServiceScope::Transient => stats.transient_services += 1,
                crate::container::scope::ServiceScope::Scoped => stats.scoped_services += 1,
            }
        }

        if let Ok(instances) = self.instances.read() {
            stats.cached_instances = instances.len();
        }

        stats
    }
}

/// Service statistics for monitoring and debugging
#[derive(Debug, Default)]
pub struct ServiceStatistics {
    pub total_services: usize,
    pub singleton_services: usize,
    pub transient_services: usize,
    pub scoped_services: usize,
    pub cached_instances: usize,
}

impl ServiceBinder for IocContainer {
    fn add_service_descriptor(
        &mut self,
        descriptor: crate::container::descriptor::ServiceDescriptor,
    ) -> Result<&mut Self, CoreError> {
        if self.is_built {
            return Err(CoreError::InvalidServiceDescriptor {
                message: "Cannot add service descriptors after container is built".to_string(),
            });
        }
        self.bindings.add_descriptor(descriptor);
        Ok(self)
    }

    fn bind<TInterface: ?Sized + 'static, TImpl: Send + Sync + Default + 'static>(
        &mut self,
    ) -> &mut Self {
        if self.is_built {
            panic!("Cannot add bindings after container is built");
        }
        self.bindings.bind::<TInterface, TImpl>();
        self
    }

    fn bind_singleton<TInterface: ?Sized + 'static, TImpl: Send + Sync + Default + 'static>(
        &mut self,
    ) -> &mut Self {
        if self.is_built {
            panic!("Cannot add bindings after container is built");
        }
        self.bindings.bind_singleton::<TInterface, TImpl>();
        self
    }

    fn bind_transient<TInterface: ?Sized + 'static, TImpl: Send + Sync + Default + 'static>(
        &mut self,
    ) -> &mut Self {
        if self.is_built {
            panic!("Cannot add bindings after container is built");
        }
        self.bindings.bind_transient::<TInterface, TImpl>();
        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,
    {
        if self.is_built {
            panic!("Cannot add bindings after container is built");
        }
        self.bindings.bind_factory::<TInterface, _, _>(factory);
        self
    }

    fn bind_instance<TInterface: ?Sized + 'static, TImpl: Send + Sync + Clone + 'static>(
        &mut self,
        instance: TImpl,
    ) -> &mut Self {
        if self.is_built {
            panic!("Cannot add bindings after container is built");
        }
        self.bindings.bind_instance::<TInterface, TImpl>(instance);
        self
    }

    fn bind_named<TInterface: ?Sized + 'static, TImpl: Send + Sync + Default + 'static>(
        &mut self,
        name: &str,
    ) -> &mut Self {
        if self.is_built {
            panic!("Cannot add bindings after container is built");
        }
        self.bindings.bind_named::<TInterface, TImpl>(name);
        self
    }

    fn bind_injectable<T: Injectable>(&mut self) -> &mut Self {
        if self.is_built {
            panic!("Cannot add bindings after container is built");
        }
        self.bindings.bind_injectable::<T>();
        self
    }

    fn bind_injectable_singleton<T: Injectable>(&mut self) -> &mut Self {
        if self.is_built {
            panic!("Cannot add bindings after container is built");
        }
        self.bindings.bind_injectable_singleton::<T>();
        self
    }

    // Advanced binding methods implementation

    fn bind_with<TInterface: ?Sized + 'static, TImpl: Send + Sync + Default + 'static>(
        &mut self,
    ) -> crate::container::binding::AdvancedBindingBuilder<TInterface> {
        if self.is_built {
            panic!("Cannot add bindings after container is built");
        }
        self.bindings.bind_with::<TInterface, TImpl>()
    }

    fn with_implementation<TInterface: ?Sized + 'static, TImpl: Send + Sync + Default + 'static>(
        &mut self,
        config: crate::container::binding::BindingConfig,
    ) -> &mut Self {
        if self.is_built {
            panic!("Cannot add bindings after container is built");
        }
        self.bindings
            .with_implementation::<TInterface, TImpl>(config);
        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,
    {
        if self.is_built {
            panic!("Cannot add bindings after container is built");
        }
        self.bindings.bind_lazy::<TInterface, F, T>(factory);
        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,
    {
        if self.is_built {
            panic!("Cannot add bindings after container is built");
        }
        self.bindings
            .bind_parameterized_factory::<TInterface, P, F, T>(factory);
        self
    }

    fn bind_collection<TInterface: ?Sized + 'static, F>(&mut self, configure: F) -> &mut Self
    where
        F: FnOnce(&mut crate::container::binding::CollectionBindingBuilder<TInterface>),
    {
        if self.is_built {
            panic!("Cannot add bindings after container is built");
        }
        self.bindings.bind_collection::<TInterface, F>(configure);
        self
    }
}

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

impl DependencyResolver for IocContainer {
    fn resolve<T: Send + Sync + 'static>(&self) -> Result<Arc<T>, CoreError> {
        self.resolve::<T>()
    }

    fn resolve_named<T: Send + Sync + 'static>(&self, name: &str) -> Result<Arc<T>, CoreError> {
        self.resolve_named::<T>(name)
    }

    fn try_resolve<T: Send + Sync + 'static>(&self) -> Option<Arc<T>> {
        self.try_resolve::<T>()
    }

    fn try_resolve_named<T: Send + Sync + 'static>(&self, name: &str) -> Option<Arc<T>> {
        self.try_resolve_named::<T>(name)
    }
}

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

    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_data".to_string())
        }
    }

    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_basic_binding_and_resolution() {
        let mut container = IocContainer::new();

        container
            .bind::<PostgresRepository, PostgresRepository>()
            .bind_singleton::<UserService, UserService>();

        container.build().unwrap();

        let repo = container.resolve::<PostgresRepository>().unwrap();
        assert_eq!(repo.find(1), Some("postgres_data".to_string()));

        let service = container.resolve::<UserService>().unwrap();
        assert_eq!(service.get_data(), "user_data");
    }

    #[test]
    fn test_named_services() {
        let mut container = IocContainer::new();

        container
            .bind_named::<PostgresRepository, PostgresRepository>("postgres")
            .bind_named::<PostgresRepository, PostgresRepository>("backup");

        container.build().unwrap();

        let postgres_repo = container
            .resolve_named::<PostgresRepository>("postgres")
            .unwrap();
        let backup_repo = container
            .resolve_named::<PostgresRepository>("backup")
            .unwrap();

        assert_eq!(postgres_repo.find(1), Some("postgres_data".to_string()));
        assert_eq!(backup_repo.find(1), Some("postgres_data".to_string()));
    }

    #[test]
    fn test_singleton_behavior() {
        let mut container = IocContainer::new();

        container.bind_singleton::<UserService, UserService>();
        container.build().unwrap();

        let service1 = container.resolve::<UserService>().unwrap();
        let service2 = container.resolve::<UserService>().unwrap();

        // Should be the same instance
        assert!(Arc::ptr_eq(&service1, &service2));
    }

    #[test]
    fn test_transient_behavior() {
        let mut container = IocContainer::new();

        container.bind_transient::<UserService, UserService>();
        container.build().unwrap();

        let service1 = container.resolve::<UserService>().unwrap();
        let service2 = container.resolve::<UserService>().unwrap();

        // Should be different instances
        assert!(!Arc::ptr_eq(&service1, &service2));
    }

    #[test]
    #[should_panic(expected = "Cannot add bindings after container is built")]
    fn test_cannot_bind_after_build() {
        let mut container = IocContainer::new();
        container.build().unwrap();

        // This should panic
        container.bind::<UserService, UserService>();
    }

    #[test]
    fn test_service_not_found() {
        let mut container = IocContainer::new();
        container.build().unwrap();

        let result = container.resolve::<UserService>();
        assert!(result.is_err());

        if let Err(CoreError::ServiceNotFound { service_type }) = result {
            assert!(service_type.contains("UserService"));
        }
    }
}