alien-bindings 1.10.1

Alien platform runtime bindings
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
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
//! Unified BindingsProvider implementation that supports multiple cloud providers

use crate::{
    error::{ErrorData, Result},
    traits::{
        ArtifactRegistry, BindingsProviderApi, Build, Container, Kv, Queue, ServiceAccount,
        Storage, Vault, Worker,
    },
};

use alien_client_config::ClientConfigExt;
use alien_core::{ClientConfig, Platform, StackState, ENV_ALIEN_BASE_PLATFORM};
use alien_error::{AlienError, Context, IntoAlienError};
use async_trait::async_trait;
use std::{any::Any, collections::HashMap, sync::Arc};
use tokio::sync::{OnceCell, RwLock};

/// Direct platform-specific bindings provider.
/// Routes to appropriate platform implementations based on binding configuration.
///
/// Caches all loaded bindings by name. Each `load_*` call creates cloud clients
/// (HTTP connection pools, token caches) which are expensive to initialize. Since
/// the binding configuration is immutable for the provider's lifetime, the same
/// binding name always produces the same client — so we cache on first load.
#[derive(Debug, Clone)]
pub struct BindingsProvider {
    client_config: ClientConfig,
    bindings: HashMap<String, serde_json::Value>,
    /// Per-binding-name cache of loaded binding instances. Keyed by
    /// `"{trait_name}:{binding_name}"` to avoid collisions across types.
    /// Each value is a `Box<Arc<dyn Trait>>` erased via `Any`.
    cache: Arc<RwLock<HashMap<String, Box<dyn Any + Send + Sync>>>>,
}

/// Environment-backed provider that defers cloud client configuration until the
/// first binding is actually used.
///
/// Long-running HTTP daemons can be wrapped by alien-runtime only for commands,
/// logs, or future binding access. They should still start when no startup
/// secret needs loading, even if cloud metadata is temporarily unavailable.
#[derive(Debug)]
pub struct LazyEnvBindingsProvider {
    env: HashMap<String, String>,
    provider: OnceCell<BindingsProvider>,
}

impl BindingsProvider {
    /// Creates a new BindingsProvider with explicit credentials and bindings.
    ///
    /// This is the base constructor used by all other convenience constructors.
    pub fn new(
        client_config: ClientConfig,
        bindings: HashMap<String, serde_json::Value>,
    ) -> Result<Self> {
        Ok(Self {
            client_config,
            bindings,
            cache: Arc::new(RwLock::new(HashMap::new())),
        })
    }

    /// Get a cached binding by type and name, or return None.
    async fn get_cached<T: Clone + Send + Sync + 'static>(
        &self,
        trait_name: &str,
        binding_name: &str,
    ) -> Option<T> {
        let cache_key = format!("{}:{}", trait_name, binding_name);
        let cache = self.cache.read().await;
        cache
            .get(&cache_key)
            .and_then(|boxed| boxed.downcast_ref::<T>())
            .cloned()
    }

    /// Store a binding in the cache.
    async fn put_cache<T: Clone + Send + Sync + 'static>(
        &self,
        trait_name: &str,
        binding_name: &str,
        value: T,
    ) {
        let cache_key = format!("{}:{}", trait_name, binding_name);
        let mut cache = self.cache.write().await;
        cache.insert(cache_key, Box::new(value));
    }

    /// Creates a BindingsProvider from environment variables (for runtime use).
    ///
    /// This parses the platform from ALIEN_DEPLOYMENT_TYPE, loads ClientConfig from environment,
    /// and extracts all ALIEN_*_BINDING environment variables.
    pub async fn from_env(env: HashMap<String, String>) -> Result<Self> {
        // 1. Parse platform from ALIEN_DEPLOYMENT_TYPE
        let platform = crate::get_platform_from_env(&env)?;

        // 2. Load ClientConfig from environment
        let client_config = Self::client_config_from_env(platform, &env).await?;

        // 3. Parse all ALIEN_*_BINDING environment variables
        let bindings = Self::parse_bindings_from_env(&env)?;

        Self::new(client_config, bindings)
    }

    /// Creates an environment-backed provider without resolving cloud client
    /// configuration yet.
    ///
    /// Startup still validates the platform and binding JSON, but credentials
    /// are loaded only if application code asks for a binding or runtime-owned
    /// startup secrets need to be fetched.
    pub fn from_env_lazy(env: HashMap<String, String>) -> Result<LazyEnvBindingsProvider> {
        crate::get_platform_from_env(&env)?;
        Self::parse_bindings_from_env(&env)?;

        Ok(LazyEnvBindingsProvider {
            env,
            provider: OnceCell::new(),
        })
    }

    async fn client_config_from_env(
        platform: Platform,
        env: &HashMap<String, String>,
    ) -> Result<ClientConfig> {
        if platform != Platform::Kubernetes {
            return Self::load_client_config_from_env(platform, env).await;
        }

        let Some(base_platform) = Self::base_platform_from_env(env)? else {
            return Self::load_client_config_from_env(platform, env).await;
        };

        let kubernetes = match Self::load_client_config_from_env(Platform::Kubernetes, env).await? {
            ClientConfig::Kubernetes(kubernetes) => kubernetes,
            _ => unreachable!("kubernetes platform must produce a Kubernetes client config"),
        };
        let cloud = Self::load_client_config_from_env(base_platform, env).await?;

        Ok(ClientConfig::KubernetesCloud {
            kubernetes,
            cloud: Box::new(cloud),
        })
    }

    fn base_platform_from_env(env: &HashMap<String, String>) -> Result<Option<Platform>> {
        let Some(base_platform) = env.get(ENV_ALIEN_BASE_PLATFORM) else {
            return Ok(None);
        };

        let parsed: Platform = base_platform.parse().map_err(|reason| {
            AlienError::new(ErrorData::InvalidEnvironmentVariable {
                variable_name: ENV_ALIEN_BASE_PLATFORM.to_string(),
                value: base_platform.clone(),
                reason,
            })
        })?;

        if !matches!(parsed, Platform::Aws | Platform::Gcp | Platform::Azure) {
            return Err(AlienError::new(ErrorData::InvalidEnvironmentVariable {
                variable_name: ENV_ALIEN_BASE_PLATFORM.to_string(),
                value: base_platform.clone(),
                reason: "Kubernetes base platform must be aws, gcp, or azure".to_string(),
            }));
        }

        Ok(Some(parsed))
    }

    async fn load_client_config_from_env(
        platform: Platform,
        env: &HashMap<String, String>,
    ) -> Result<ClientConfig> {
        ClientConfig::from_env(platform, env).await.map_err(|e| {
            AlienError::new(ErrorData::ClientConfigInvalid {
                platform,
                message: format!("Failed to load client config: {}", e),
            })
        })
    }

    /// Parses all ALIEN_*_BINDING environment variables into a map.
    fn parse_bindings_from_env(
        env: &HashMap<String, String>,
    ) -> Result<HashMap<String, serde_json::Value>> {
        let mut bindings = HashMap::new();
        for (key, value) in env {
            if key.starts_with("ALIEN_") && key.ends_with("_BINDING") {
                let binding_name = key
                    .strip_prefix("ALIEN_")
                    .unwrap()
                    .strip_suffix("_BINDING")
                    .unwrap()
                    .to_lowercase()
                    .replace('_', "-");
                let parsed: serde_json::Value = serde_json::from_str(value)
                    .into_alien_error()
                    .context(ErrorData::BindingConfigInvalid {
                        binding_name: binding_name.clone(),
                        reason: "Failed to parse binding JSON".to_string(),
                    })?;
                bindings.insert(binding_name, parsed);
            }
        }
        Ok(bindings)
    }

    /// Pattern 1: Creates a BindingsProvider from stack state and client config.
    ///
    /// Convenience helper that extracts bindings from stack state's remote_binding_params.
    /// Only resources with `remote_access: true` will have binding params available.
    ///
    /// **When to use:** You already have `ClientConfig` and `StackState`.
    ///
    /// **Example use cases:**
    /// - alien-deployment (has credentials from RemoteAccessResolver)
    /// - Platform API backend (has stack state from DB)
    pub fn from_stack_state(stack_state: &StackState, client_config: ClientConfig) -> Result<Self> {
        let bindings = stack_state
            .resources
            .iter()
            .filter_map(|(id, state)| {
                state
                    .remote_binding_params
                    .as_ref()
                    .map(|p| (id.clone(), p.clone()))
            })
            .collect();

        Self::new(client_config, bindings)
    }

    /// Pattern 2: Creates a BindingsProvider for remote deployment access.
    ///
    /// Fetches credentials remotely using deployment ID and auth token, then creates the provider.
    ///
    /// **When to use:** You have a deployment ID and auth token, but no credentials yet.
    ///
    /// **Example use cases:**
    /// - CLI commands (e.g., `alien secrets set`)
    /// - External applications connecting to deployment
    /// - Local development tools
    ///
    /// **What it does internally:**
    /// 1. GET /api/deployments/{id} - Returns deployment info (stackState, platform, managerId)
    /// 2. GET /api/managers/{managerId} - Returns manager URL
    /// 3. POST {managerUrl}/v1/deployment/resolve-credentials - Resolves credentials
    /// 4. Creates BindingsProvider using from_stack_state()
    #[cfg(feature = "platform-sdk")]
    pub async fn for_remote_deployment(
        deployment_id: &str,
        token: &str,
        api_base_url: Option<&str>,
    ) -> Result<Self> {
        let base_url = api_base_url.unwrap_or("https://api.alien.dev");

        // Build an authenticated SDK client so deployment/manager lookups are
        // scoped to the caller's permissions.
        let auth_value = format!("Bearer {}", token);
        let mut headers = reqwest::header::HeaderMap::new();
        headers.insert(
            reqwest::header::AUTHORIZATION,
            reqwest::header::HeaderValue::from_str(&auth_value)
                .into_alien_error()
                .context(ErrorData::RemoteAccessFailed {
                    operation: "build Platform API client with token".to_string(),
                })?,
        );

        let authed_http_client = reqwest::Client::builder()
            .default_headers(headers)
            .build()
            .into_alien_error()
            .context(ErrorData::RemoteAccessFailed {
                operation: "build Platform API HTTP client".to_string(),
            })?;

        let sdk_client = alien_platform_api::Client::new_with_client(base_url, authed_http_client);

        // 1. Get deployment info (caller-scoped)
        let deployment_response = sdk_client
            .get_deployment()
            .id(deployment_id)
            .send()
            .await
            .into_alien_error()
            .context(ErrorData::RemoteAccessFailed {
                operation: "fetch deployment from Platform API".to_string(),
            })?
            .into_inner();

        // 2. Get manager URL (caller-scoped)
        let manager_id = deployment_response.manager_id.ok_or_else(|| {
            AlienError::new(ErrorData::RemoteAccessFailed {
                operation: "fetch manager from Platform API".to_string(),
            })
        })?;

        let manager_response = sdk_client
            .get_manager()
            .id(&manager_id.to_string())
            .send()
            .await
            .into_alien_error()
            .context(ErrorData::RemoteAccessFailed {
                operation: "fetch manager from Platform API".to_string(),
            })?
            .into_inner();

        // 3. Convert SDK stack state to alien-core StackState (used locally to extract
        // binding configuration; the manager re-fetches the canonical stack state itself
        // when resolving credentials).
        let stack_state = deployment_response.stack_state.as_ref().ok_or_else(|| {
            AlienError::new(ErrorData::RemoteAccessFailed {
                operation: "Deployment has no stack state (not deployed yet)".to_string(),
            })
        })?;

        let alien_stack_state = conversions::convert_stack_state(stack_state)?;

        // 4. Resolve client config from manager. We send only the deploymentId; the
        // manager fetches stackState/platform from Platform API using our forwarded
        // bearer token so an attacker cannot direct it at an arbitrary cloud identity.
        let manager_url = manager_response.url.ok_or_else(|| {
            AlienError::new(ErrorData::RemoteAccessFailed {
                operation: "fetch manager URL from Platform API".to_string(),
            })
        })?;

        let http_client = reqwest::Client::new();
        let client_config = http_client
            .post(format!("{}/v1/deployment/resolve-credentials", manager_url))
            .bearer_auth(token)
            .json(&serde_json::json!({
                "deploymentId": deployment_id,
            }))
            .send()
            .await
            .into_alien_error()
            .context(ErrorData::RemoteAccessFailed {
                operation: "resolve credentials from manager".to_string(),
            })?
            .json::<ResolveCredentialsResponse>()
            .await
            .into_alien_error()
            .context(ErrorData::RemoteAccessFailed {
                operation: "parse credentials response".to_string(),
            })?
            .client_config;

        // 5. Create provider using from_stack_state (which extracts bindings from stack_state)
        Self::from_stack_state(&alien_stack_state, client_config)
    }
}

impl LazyEnvBindingsProvider {
    async fn provider(&self) -> Result<&BindingsProvider> {
        self.provider
            .get_or_try_init(|| async { BindingsProvider::from_env(self.env.clone()).await })
            .await
    }
}

#[async_trait]
impl BindingsProviderApi for LazyEnvBindingsProvider {
    async fn load_storage(&self, binding_name: &str) -> Result<Arc<dyn Storage>> {
        self.provider().await?.load_storage(binding_name).await
    }

    async fn load_build(&self, binding_name: &str) -> Result<Arc<dyn Build>> {
        self.provider().await?.load_build(binding_name).await
    }

    async fn load_artifact_registry(
        &self,
        binding_name: &str,
    ) -> Result<Arc<dyn ArtifactRegistry>> {
        self.provider()
            .await?
            .load_artifact_registry(binding_name)
            .await
    }

    async fn load_vault(&self, binding_name: &str) -> Result<Arc<dyn Vault>> {
        self.provider().await?.load_vault(binding_name).await
    }

    async fn load_kv(&self, binding_name: &str) -> Result<Arc<dyn Kv>> {
        self.provider().await?.load_kv(binding_name).await
    }

    async fn load_queue(&self, binding_name: &str) -> Result<Arc<dyn Queue>> {
        self.provider().await?.load_queue(binding_name).await
    }

    async fn load_worker(&self, binding_name: &str) -> Result<Arc<dyn Worker>> {
        self.provider().await?.load_worker(binding_name).await
    }

    async fn load_container(&self, binding_name: &str) -> Result<Arc<dyn Container>> {
        self.provider().await?.load_container(binding_name).await
    }

    async fn load_service_account(&self, binding_name: &str) -> Result<Arc<dyn ServiceAccount>> {
        self.provider()
            .await?
            .load_service_account(binding_name)
            .await
    }
}

#[cfg(feature = "platform-sdk")]
#[derive(serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct ResolveCredentialsResponse {
    client_config: ClientConfig,
}

#[async_trait]
impl BindingsProviderApi for BindingsProvider {
    async fn load_storage(&self, binding_name: &str) -> Result<Arc<dyn Storage>> {
        if let Some(cached) = self
            .get_cached::<Arc<dyn Storage>>("storage", binding_name)
            .await
        {
            return Ok(cached);
        }

        use alien_core::bindings::StorageBinding;

        // Get binding JSON from our pre-parsed map
        let binding_json = self.bindings.get(binding_name).ok_or_else(|| {
            AlienError::new(ErrorData::BindingConfigInvalid {
                binding_name: binding_name.to_string(),
                reason: "Binding not found".to_string(),
            })
        })?;

        // Parse to strongly-typed binding
        let binding: StorageBinding = serde_json::from_value(binding_json.clone())
            .into_alien_error()
            .context(ErrorData::BindingConfigInvalid {
                binding_name: binding_name.to_string(),
                reason: "Failed to parse storage binding".to_string(),
            })?;

        let result: Arc<dyn Storage> = match binding {
            #[cfg(feature = "aws")]
            StorageBinding::S3(config) => {
                use crate::providers::storage::aws_s3::S3Storage;

                // Get AWS config from our stored ClientConfig
                let aws_config = self.client_config.aws_config().ok_or_else(|| {
                    AlienError::new(ErrorData::ClientConfigInvalid {
                        platform: Platform::Aws,
                        message: "AWS config not available".to_string(),
                    })
                })?;

                let credentials =
                    alien_aws_clients::AwsCredentialProvider::from_config(aws_config.clone())
                        .await
                        .context(ErrorData::BindingSetupFailed {
                            binding_type: "AWS S3 storage".to_string(),
                            reason: "Failed to create credential provider".to_string(),
                        })?;

                // Extract bucket name from binding
                let bucket_name = config
                    .bucket_name
                    .into_value(binding_name, "bucket_name")
                    .context(ErrorData::BindingConfigInvalid {
                        binding_name: binding_name.to_string(),
                        reason: "Failed to extract bucket_name from S3 binding".to_string(),
                    })?;

                let storage: Arc<dyn Storage> = Arc::new(S3Storage::new(bucket_name, credentials)?);
                Ok(storage)
            }
            #[cfg(not(feature = "aws"))]
            StorageBinding::S3 { .. } => Err(AlienError::new(ErrorData::FeatureNotEnabled {
                feature: "aws".to_string(),
            })),

            #[cfg(feature = "azure")]
            StorageBinding::Blob(config) => {
                use crate::providers::storage::azure_blob::BlobStorage;

                let azure_config = self.client_config.azure_config().ok_or_else(|| {
                    AlienError::new(ErrorData::ClientConfigInvalid {
                        platform: Platform::Azure,
                        message: "Azure config not available".to_string(),
                    })
                })?;

                // Extract container and account names from binding
                let container_name = config
                    .container_name
                    .into_value(binding_name, "container_name")
                    .context(ErrorData::BindingConfigInvalid {
                        binding_name: binding_name.to_string(),
                        reason: "Failed to extract container_name from Blob binding".to_string(),
                    })?;

                let account_name = config
                    .account_name
                    .into_value(binding_name, "account_name")
                    .context(ErrorData::BindingConfigInvalid {
                        binding_name: binding_name.to_string(),
                        reason: "Failed to extract account_name from Blob binding".to_string(),
                    })?;

                let storage: Arc<dyn Storage> = Arc::new(BlobStorage::new(
                    container_name,
                    account_name,
                    azure_config,
                )?);
                Ok(storage)
            }
            #[cfg(not(feature = "azure"))]
            StorageBinding::Blob { .. } => Err(AlienError::new(ErrorData::FeatureNotEnabled {
                feature: "azure".to_string(),
            })),

            #[cfg(feature = "gcp")]
            StorageBinding::Gcs(config) => {
                use crate::providers::storage::gcp_gcs::GcsStorage;

                let gcp_config = self.client_config.gcp_config().ok_or_else(|| {
                    AlienError::new(ErrorData::ClientConfigInvalid {
                        platform: Platform::Gcp,
                        message: "GCP config not available".to_string(),
                    })
                })?;

                // Extract bucket name from binding
                let bucket_name = config
                    .bucket_name
                    .into_value(binding_name, "bucket_name")
                    .context(ErrorData::BindingConfigInvalid {
                        binding_name: binding_name.to_string(),
                        reason: "Failed to extract bucket_name from Gcs binding".to_string(),
                    })?;

                let storage: Arc<dyn Storage> = Arc::new(GcsStorage::new(bucket_name, gcp_config)?);
                Ok(storage)
            }
            #[cfg(not(feature = "gcp"))]
            StorageBinding::Gcs { .. } => Err(AlienError::new(ErrorData::FeatureNotEnabled {
                feature: "gcp".to_string(),
            })),

            #[cfg(feature = "local")]
            StorageBinding::Local(config) => {
                use crate::providers::storage::local::LocalStorage;

                // Extract storage path from binding
                let storage_path = config
                    .storage_path
                    .into_value(binding_name, "storage_path")
                    .context(ErrorData::BindingConfigInvalid {
                        binding_name: binding_name.to_string(),
                        reason: "Failed to extract storage_path from Local binding".to_string(),
                    })?;

                let storage: Arc<dyn Storage> = Arc::new(LocalStorage::new(storage_path)?);
                Ok(storage)
            }
            #[cfg(not(feature = "local"))]
            StorageBinding::Local { .. } => Err(AlienError::new(ErrorData::FeatureNotEnabled {
                feature: "local".to_string(),
            })),
        }?;

        self.put_cache("storage", binding_name, result.clone())
            .await;
        Ok(result)
    }

    async fn load_build(&self, binding_name: &str) -> Result<Arc<dyn Build>> {
        use alien_core::bindings::BuildBinding;

        let binding_json = self.bindings.get(binding_name).ok_or_else(|| {
            AlienError::new(ErrorData::BindingConfigInvalid {
                binding_name: binding_name.to_string(),
                reason: "Binding not found".to_string(),
            })
        })?;

        let binding: BuildBinding = serde_json::from_value(binding_json.clone())
            .into_alien_error()
            .context(ErrorData::BindingConfigInvalid {
                binding_name: binding_name.to_string(),
                reason: "Failed to parse build binding".to_string(),
            })?;

        match binding {
            #[cfg(feature = "aws")]
            BuildBinding::Codebuild { .. } => {
                use crate::providers::build::codebuild::CodebuildBuild;

                let aws_config = self.client_config.aws_config().ok_or_else(|| {
                    AlienError::new(ErrorData::ClientConfigInvalid {
                        platform: Platform::Aws,
                        message: "AWS config not available".to_string(),
                    })
                })?;
                let credentials =
                    alien_aws_clients::AwsCredentialProvider::from_config(aws_config.clone())
                        .await
                        .context(ErrorData::ClientConfigInvalid {
                            platform: Platform::Aws,
                            message: "Failed to create AWS credential provider".to_string(),
                        })?;

                let build = Arc::new(
                    CodebuildBuild::new(binding_name.to_string(), binding, &credentials)
                        .await
                        .context(ErrorData::BindingConfigInvalid {
                            binding_name: binding_name.to_string(),
                            reason: "Failed to initialize AWS CodeBuild client".to_string(),
                        })?,
                );
                Ok(build)
            }
            #[cfg(not(feature = "aws"))]
            BuildBinding::Codebuild { .. } => Err(AlienError::new(ErrorData::FeatureNotEnabled {
                feature: "aws".to_string(),
            })),

            #[cfg(feature = "azure")]
            BuildBinding::Aca { .. } => {
                use crate::providers::build::aca::AcaBuild;

                let azure_config = self.client_config.azure_config().ok_or_else(|| {
                    AlienError::new(ErrorData::ClientConfigInvalid {
                        platform: Platform::Azure,
                        message: "Azure config not available".to_string(),
                    })
                })?;

                let build = Arc::new(
                    AcaBuild::new(binding_name.to_string(), binding, azure_config)
                        .await
                        .context(ErrorData::BindingConfigInvalid {
                            binding_name: binding_name.to_string(),
                            reason: "Failed to initialize Azure Container Apps build".to_string(),
                        })?,
                );
                Ok(build)
            }
            #[cfg(not(feature = "azure"))]
            BuildBinding::Aca { .. } => Err(AlienError::new(ErrorData::FeatureNotEnabled {
                feature: "azure".to_string(),
            })),

            #[cfg(feature = "gcp")]
            BuildBinding::Cloudbuild { .. } => {
                use crate::providers::build::cloudbuild::CloudbuildBuild;

                let gcp_config = self.client_config.gcp_config().ok_or_else(|| {
                    AlienError::new(ErrorData::ClientConfigInvalid {
                        platform: Platform::Gcp,
                        message: "GCP config not available".to_string(),
                    })
                })?;

                let build = Arc::new(
                    CloudbuildBuild::new(binding_name.to_string(), binding, gcp_config)
                        .await
                        .context(ErrorData::BindingConfigInvalid {
                            binding_name: binding_name.to_string(),
                            reason: "Failed to initialize GCP Cloud Build client".to_string(),
                        })?,
                );
                Ok(build)
            }
            #[cfg(not(feature = "gcp"))]
            BuildBinding::Cloudbuild { .. } => Err(AlienError::new(ErrorData::FeatureNotEnabled {
                feature: "gcp".to_string(),
            })),

            #[cfg(feature = "local")]
            BuildBinding::Local { .. } => {
                use crate::providers::build::local::LocalBuild;

                let build = Arc::new(LocalBuild::new(binding_name.to_string(), binding)?);
                Ok(build)
            }
            #[cfg(not(feature = "local"))]
            BuildBinding::Local { .. } => Err(AlienError::new(ErrorData::FeatureNotEnabled {
                feature: "local".to_string(),
            })),

            #[cfg(feature = "kubernetes")]
            BuildBinding::Kubernetes { .. } => {
                use crate::providers::build::kubernetes::KubernetesBuild;

                let build =
                    Arc::new(KubernetesBuild::new(binding_name.to_string(), binding).await?);
                Ok(build)
            }
            #[cfg(not(feature = "kubernetes"))]
            BuildBinding::Kubernetes { .. } => Err(AlienError::new(ErrorData::FeatureNotEnabled {
                feature: "kubernetes".to_string(),
            })),
        }
    }

    async fn load_artifact_registry(
        &self,
        binding_name: &str,
    ) -> Result<Arc<dyn ArtifactRegistry>> {
        if let Some(cached) = self
            .get_cached::<Arc<dyn ArtifactRegistry>>("artifact_registry", binding_name)
            .await
        {
            return Ok(cached);
        }

        use alien_core::bindings::ArtifactRegistryBinding;

        let binding_json = self.bindings.get(binding_name).ok_or_else(|| {
            AlienError::new(ErrorData::BindingConfigInvalid {
                binding_name: binding_name.to_string(),
                reason: "Binding not found".to_string(),
            })
        })?;

        let binding: ArtifactRegistryBinding = serde_json::from_value(binding_json.clone())
            .into_alien_error()
            .context(ErrorData::BindingConfigInvalid {
                binding_name: binding_name.to_string(),
                reason: "Failed to parse artifact registry binding".to_string(),
            })?;

        let registry: Arc<dyn ArtifactRegistry> = match binding {
            #[cfg(feature = "aws")]
            ArtifactRegistryBinding::Ecr { .. } => {
                use crate::providers::artifact_registry::ecr::EcrArtifactRegistry;

                let aws_config = self.client_config.aws_config().ok_or_else(|| {
                    AlienError::new(ErrorData::ClientConfigInvalid {
                        platform: Platform::Aws,
                        message: "AWS config not available".to_string(),
                    })
                })?;
                let credentials =
                    alien_aws_clients::AwsCredentialProvider::from_config(aws_config.clone())
                        .await
                        .context(ErrorData::ClientConfigInvalid {
                            platform: Platform::Aws,
                            message: "Failed to create AWS credential provider".to_string(),
                        })?;

                let registry: Arc<dyn ArtifactRegistry> = Arc::new(
                    EcrArtifactRegistry::new(binding_name.to_string(), binding, &credentials)
                        .await
                        .context(ErrorData::BindingConfigInvalid {
                            binding_name: binding_name.to_string(),
                            reason: "Failed to initialize AWS ECR artifact registry".to_string(),
                        })?,
                );
                Ok(registry)
            }
            #[cfg(not(feature = "aws"))]
            ArtifactRegistryBinding::Ecr { .. } => {
                Err(AlienError::new(ErrorData::FeatureNotEnabled {
                    feature: "aws".to_string(),
                }))
            }

            #[cfg(feature = "azure")]
            ArtifactRegistryBinding::Acr { .. } => {
                use crate::providers::artifact_registry::acr::AcrArtifactRegistry;

                let azure_config = self.client_config.azure_config().ok_or_else(|| {
                    AlienError::new(ErrorData::ClientConfigInvalid {
                        platform: Platform::Azure,
                        message: "Azure config not available".to_string(),
                    })
                })?;

                let registry: Arc<dyn ArtifactRegistry> = Arc::new(
                    AcrArtifactRegistry::new(binding_name.to_string(), binding, azure_config)
                        .await
                        .context(ErrorData::BindingConfigInvalid {
                            binding_name: binding_name.to_string(),
                            reason: "Failed to initialize Azure ACR artifact registry".to_string(),
                        })?,
                );
                Ok(registry)
            }
            #[cfg(not(feature = "azure"))]
            ArtifactRegistryBinding::Acr { .. } => {
                Err(AlienError::new(ErrorData::FeatureNotEnabled {
                    feature: "azure".to_string(),
                }))
            }

            #[cfg(feature = "gcp")]
            ArtifactRegistryBinding::Gar { .. } => {
                use crate::providers::artifact_registry::gar::GarArtifactRegistry;

                let gcp_config = self.client_config.gcp_config().ok_or_else(|| {
                    AlienError::new(ErrorData::ClientConfigInvalid {
                        platform: Platform::Gcp,
                        message: "GCP config not available".to_string(),
                    })
                })?;

                let registry: Arc<dyn ArtifactRegistry> = Arc::new(
                    GarArtifactRegistry::new(binding_name.to_string(), binding, gcp_config)
                        .await
                        .context(ErrorData::BindingConfigInvalid {
                            binding_name: binding_name.to_string(),
                            reason: "Failed to initialize GCP GAR artifact registry".to_string(),
                        })?,
                );
                Ok(registry)
            }
            #[cfg(not(feature = "gcp"))]
            ArtifactRegistryBinding::Gar { .. } => {
                Err(AlienError::new(ErrorData::FeatureNotEnabled {
                    feature: "gcp".to_string(),
                }))
            }

            #[cfg(feature = "local")]
            ArtifactRegistryBinding::Local { .. } => {
                use crate::providers::artifact_registry::local::LocalArtifactRegistry;

                let registry: Arc<dyn ArtifactRegistry> = Arc::new(
                    LocalArtifactRegistry::new(binding_name.to_string(), binding.clone()).await?,
                );
                Ok(registry)
            }
            #[cfg(not(feature = "local"))]
            ArtifactRegistryBinding::Local { .. } => {
                Err(AlienError::new(ErrorData::FeatureNotEnabled {
                    feature: "local".to_string(),
                }))
            }
        }?;

        self.put_cache("artifact_registry", binding_name, registry.clone())
            .await;
        Ok(registry)
    }

    async fn load_vault(&self, binding_name: &str) -> Result<Arc<dyn Vault>> {
        if let Some(cached) = self
            .get_cached::<Arc<dyn Vault>>("vault", binding_name)
            .await
        {
            return Ok(cached);
        }

        use alien_core::bindings::VaultBinding;

        let binding_json = self.bindings.get(binding_name).ok_or_else(|| {
            AlienError::new(ErrorData::BindingConfigInvalid {
                binding_name: binding_name.to_string(),
                reason: "Binding not found".to_string(),
            })
        })?;

        let binding: VaultBinding = serde_json::from_value(binding_json.clone())
            .into_alien_error()
            .context(ErrorData::BindingConfigInvalid {
                binding_name: binding_name.to_string(),
                reason: "Failed to parse vault binding".to_string(),
            })?;

        let result: Arc<dyn Vault> = match binding {
            #[cfg(feature = "aws")]
            VaultBinding::ParameterStore(config) => {
                use crate::providers::vault::aws_parameter_store::AwsParameterStoreVault;
                use alien_aws_clients::ssm::SsmClient;

                let aws_config = self.client_config.aws_config().ok_or_else(|| {
                    AlienError::new(ErrorData::ClientConfigInvalid {
                        platform: Platform::Aws,
                        message: "AWS config not available".to_string(),
                    })
                })?;
                let credentials =
                    alien_aws_clients::AwsCredentialProvider::from_config(aws_config.clone())
                        .await
                        .context(ErrorData::ClientConfigInvalid {
                            platform: Platform::Aws,
                            message: "Failed to create AWS credential provider".to_string(),
                        })?;

                let client = Arc::new(SsmClient::new(
                    crate::http_client::create_http_client(),
                    credentials,
                ));

                // Extract the vault prefix from the binding configuration
                let vault_prefix = config
                    .vault_prefix
                    .into_value(&binding_name, "vault_prefix")
                    .context(ErrorData::BindingConfigInvalid {
                        binding_name: binding_name.to_string(),
                        reason: "Failed to extract vault_prefix from ParameterStore binding"
                            .to_string(),
                    })?;

                let vault: Arc<dyn Vault> =
                    Arc::new(AwsParameterStoreVault::new(client, vault_prefix));
                Ok(vault)
            }
            #[cfg(not(feature = "aws"))]
            VaultBinding::ParameterStore(_) => Err(AlienError::new(ErrorData::FeatureNotEnabled {
                feature: "aws".to_string(),
            })),

            #[cfg(feature = "azure")]
            VaultBinding::KeyVault(config) => {
                use crate::providers::vault::azure_key_vault::AzureKeyVault;
                use alien_azure_clients::keyvault::AzureKeyVaultSecretsClient;
                use alien_azure_clients::AzureTokenCache;

                let azure_config = self.client_config.azure_config().ok_or_else(|| {
                    AlienError::new(ErrorData::ClientConfigInvalid {
                        platform: Platform::Azure,
                        message: "Azure config not available".to_string(),
                    })
                })?;

                let client = Arc::new(AzureKeyVaultSecretsClient::new(
                    crate::http_client::create_http_client(),
                    AzureTokenCache::new(azure_config.clone()),
                ));

                // Extract the vault name from the binding configuration
                let vault_name = config
                    .vault_name
                    .into_value(&binding_name, "vault_name")
                    .context(ErrorData::BindingConfigInvalid {
                        binding_name: binding_name.to_string(),
                        reason: "Failed to extract vault_name from KeyVault binding".to_string(),
                    })?;

                // Construct the vault base URL
                // Azure Key Vault URLs typically follow: https://{vault-name}.vault.azure.net/
                let vault_base_url = format!("https://{}.vault.azure.net", vault_name);

                let vault: Arc<dyn Vault> = Arc::new(AzureKeyVault::new(client, vault_base_url));
                Ok(vault)
            }
            #[cfg(not(feature = "azure"))]
            VaultBinding::KeyVault(_) => Err(AlienError::new(ErrorData::FeatureNotEnabled {
                feature: "azure".to_string(),
            })),

            #[cfg(feature = "gcp")]
            VaultBinding::SecretManager(config) => {
                use crate::providers::vault::gcp_secret_manager::GcpSecretManagerVault;
                use alien_gcp_clients::secret_manager::SecretManagerClient;

                let gcp_config = self.client_config.gcp_config().ok_or_else(|| {
                    AlienError::new(ErrorData::ClientConfigInvalid {
                        platform: Platform::Gcp,
                        message: "GCP config not available".to_string(),
                    })
                })?;

                let client = Arc::new(SecretManagerClient::new(
                    crate::http_client::create_http_client(),
                    gcp_config.clone(),
                ));

                // Extract the vault prefix from the binding configuration
                let vault_prefix = config
                    .vault_prefix
                    .into_value(&binding_name, "vault_prefix")
                    .context(ErrorData::BindingConfigInvalid {
                        binding_name: binding_name.to_string(),
                        reason: "Failed to extract vault_prefix from SecretManager binding"
                            .to_string(),
                    })?;

                let vault: Arc<dyn Vault> = Arc::new(GcpSecretManagerVault::new(
                    client,
                    vault_prefix,
                    gcp_config.project_id.clone(),
                ));
                Ok(vault)
            }
            #[cfg(not(feature = "gcp"))]
            VaultBinding::SecretManager(_) => Err(AlienError::new(ErrorData::FeatureNotEnabled {
                feature: "gcp".to_string(),
            })),

            #[cfg(feature = "local")]
            VaultBinding::Local(config) => {
                use crate::providers::vault::local::LocalVault;

                let vault_dir = config
                    .data_dir
                    .into_value(binding_name, "data_dir")
                    .context(ErrorData::BindingConfigInvalid {
                        binding_name: binding_name.to_string(),
                        reason: "Failed to extract data_dir from vault binding".to_string(),
                    })?;

                let vault: Arc<dyn Vault> = Arc::new(LocalVault::new(
                    binding_name.to_string(),
                    std::path::PathBuf::from(vault_dir),
                ));
                Ok(vault)
            }
            #[cfg(not(feature = "local"))]
            VaultBinding::Local { .. } => Err(AlienError::new(ErrorData::FeatureNotEnabled {
                feature: "local".to_string(),
            })),

            #[cfg(feature = "kubernetes")]
            VaultBinding::KubernetesSecret(config) => {
                use crate::providers::vault::kubernetes_secret::KubernetesSecretVault;
                use alien_k8s_clients::{secrets::SecretsApi, KubernetesClient};

                let kubernetes_config =
                    self.client_config.kubernetes_config().ok_or_else(|| {
                        AlienError::new(ErrorData::ClientConfigInvalid {
                            platform: Platform::Kubernetes,
                            message: "Kubernetes config not available".to_string(),
                        })
                    })?;

                let kubernetes_client = KubernetesClient::new(kubernetes_config.clone())
                    .await
                    .context(ErrorData::CloudPlatformError {
                        message: "Failed to create Kubernetes client for vault".to_string(),
                        resource_id: None,
                    })?;

                let client: Arc<dyn SecretsApi> = Arc::new(kubernetes_client);

                // Extract namespace and vault prefix from binding
                let namespace = config
                    .namespace
                    .into_value(binding_name, "namespace")
                    .context(ErrorData::BindingConfigInvalid {
                        binding_name: binding_name.to_string(),
                        reason: "Failed to extract namespace from KubernetesSecret binding"
                            .to_string(),
                    })?;

                let vault_prefix = config
                    .vault_prefix
                    .into_value(binding_name, "vault_prefix")
                    .context(ErrorData::BindingConfigInvalid {
                        binding_name: binding_name.to_string(),
                        reason: "Failed to extract vault_prefix from KubernetesSecret binding"
                            .to_string(),
                    })?;

                let vault: Arc<dyn Vault> =
                    Arc::new(KubernetesSecretVault::new(client, namespace, vault_prefix));
                Ok(vault)
            }
            #[cfg(not(feature = "kubernetes"))]
            VaultBinding::KubernetesSecret(_) => {
                Err(AlienError::new(ErrorData::FeatureNotEnabled {
                    feature: "kubernetes".to_string(),
                }))
            }
        }?;

        self.put_cache("vault", binding_name, result.clone()).await;
        Ok(result)
    }

    async fn load_kv(&self, binding_name: &str) -> Result<Arc<dyn Kv>> {
        if let Some(cached) = self.get_cached::<Arc<dyn Kv>>("kv", binding_name).await {
            return Ok(cached);
        }

        use alien_core::bindings::KvBinding;

        let binding_json = self.bindings.get(binding_name).ok_or_else(|| {
            AlienError::new(ErrorData::BindingConfigInvalid {
                binding_name: binding_name.to_string(),
                reason: "Binding not found".to_string(),
            })
        })?;

        let binding: KvBinding = serde_json::from_value(binding_json.clone())
            .into_alien_error()
            .context(ErrorData::BindingConfigInvalid {
                binding_name: binding_name.to_string(),
                reason: "Failed to parse KV binding".to_string(),
            })?;

        let result: Arc<dyn Kv> = match binding {
            #[cfg(feature = "aws")]
            KvBinding::Dynamodb(config) => {
                use crate::providers::kv::aws_dynamodb::AwsDynamodbKv;

                let table_name = config
                    .table_name
                    .into_value(binding_name, "table_name")
                    .context(ErrorData::BindingConfigInvalid {
                        binding_name: binding_name.to_string(),
                        reason: "Failed to extract table_name from DynamoDB binding".to_string(),
                    })?;

                let aws_config = self.client_config.aws_config().ok_or_else(|| {
                    AlienError::new(ErrorData::ClientConfigInvalid {
                        platform: Platform::Aws,
                        message: "AWS config not available".to_string(),
                    })
                })?;

                let credentials =
                    alien_aws_clients::AwsCredentialProvider::from_config(aws_config.clone())
                        .await
                        .context(ErrorData::ClientConfigInvalid {
                            platform: Platform::Aws,
                            message: "Failed to create AWS credential provider".to_string(),
                        })?;
                let dynamodb_client = alien_aws_clients::dynamodb::DynamoDbClient::new(
                    crate::http_client::create_http_client(),
                    credentials,
                );
                let kv_impl = AwsDynamodbKv::new(table_name, dynamodb_client);
                let kv: Arc<dyn Kv> = Arc::new(kv_impl);
                Ok(kv)
            }
            #[cfg(not(feature = "aws"))]
            KvBinding::Dynamodb(_) => Err(AlienError::new(ErrorData::FeatureNotEnabled {
                feature: "aws".to_string(),
            })),

            #[cfg(feature = "gcp")]
            KvBinding::Firestore(config) => {
                use crate::providers::kv::gcp_firestore::GcpFirestoreKv;
                use alien_gcp_clients::firestore::FirestoreClient;

                let gcp_config = self.client_config.gcp_config().ok_or_else(|| {
                    AlienError::new(ErrorData::ClientConfigInvalid {
                        platform: Platform::Gcp,
                        message: "GCP config not available".to_string(),
                    })
                })?;

                let client = FirestoreClient::new(
                    crate::http_client::create_http_client(),
                    gcp_config.clone(),
                );

                let project_id = config
                    .project_id
                    .into_value(binding_name, "project_id")
                    .context(ErrorData::BindingConfigInvalid {
                        binding_name: binding_name.to_string(),
                        reason: "Failed to extract project_id from Firestore binding".to_string(),
                    })?;

                let database_id = config
                    .database_id
                    .into_value(binding_name, "database_id")
                    .context(ErrorData::BindingConfigInvalid {
                        binding_name: binding_name.to_string(),
                        reason: "Failed to extract database_id from Firestore binding".to_string(),
                    })?;

                let collection_name = config
                    .collection_name
                    .into_value(binding_name, "collection_name")
                    .context(ErrorData::BindingConfigInvalid {
                        binding_name: binding_name.to_string(),
                        reason: "Failed to extract collection_name from Firestore binding"
                            .to_string(),
                    })?;

                let kv: Arc<dyn Kv> = Arc::new(GcpFirestoreKv::new(
                    client,
                    project_id,
                    database_id,
                    collection_name,
                )?);
                Ok(kv)
            }
            #[cfg(not(feature = "gcp"))]
            KvBinding::Firestore(_) => Err(AlienError::new(ErrorData::FeatureNotEnabled {
                feature: "gcp".to_string(),
            })),

            #[cfg(feature = "azure")]
            KvBinding::TableStorage(config) => {
                use crate::providers::kv::azure_table_storage::AzureTableStorageKv;
                use alien_azure_clients::tables::AzureTableStorageClient;
                use alien_azure_clients::AzureTokenCache;

                let azure_config = self.client_config.azure_config().ok_or_else(|| {
                    AlienError::new(ErrorData::ClientConfigInvalid {
                        platform: Platform::Azure,
                        message: "Azure config not available".to_string(),
                    })
                })?;

                let resource_group_name = config
                    .resource_group_name
                    .into_value(binding_name, "resource_group_name")
                    .context(ErrorData::BindingConfigInvalid {
                        binding_name: binding_name.to_string(),
                        reason: "Failed to extract resource_group_name from TableStorage binding"
                            .to_string(),
                    })?;

                let account_name = config
                    .account_name
                    .into_value(binding_name, "account_name")
                    .context(ErrorData::BindingConfigInvalid {
                        binding_name: binding_name.to_string(),
                        reason: "Failed to extract account_name from TableStorage binding"
                            .to_string(),
                    })?;

                let table_name = config
                    .table_name
                    .into_value(binding_name, "table_name")
                    .context(ErrorData::BindingConfigInvalid {
                        binding_name: binding_name.to_string(),
                        reason: "Failed to extract table_name from TableStorage binding"
                            .to_string(),
                    })?;

                let client = AzureTableStorageClient::new(
                    crate::http_client::create_http_client(),
                    AzureTokenCache::new(azure_config.clone()),
                );

                let kv_impl =
                    AzureTableStorageKv::new(client, resource_group_name, account_name, table_name);
                let kv: Arc<dyn Kv> = Arc::new(kv_impl);
                Ok(kv)
            }
            #[cfg(not(feature = "azure"))]
            KvBinding::TableStorage(_) => Err(AlienError::new(ErrorData::FeatureNotEnabled {
                feature: "azure".to_string(),
            })),

            #[cfg(feature = "local")]
            KvBinding::Local(local_binding) => {
                use crate::providers::kv::local::LocalKv;
                use std::path::PathBuf;

                // Get data directory from binding
                let data_dir = PathBuf::from(
                    local_binding
                        .data_dir
                        .into_value(binding_name, "data_dir")
                        .context(ErrorData::BindingConfigInvalid {
                            binding_name: binding_name.to_string(),
                            reason: "Failed to extract data_dir from Local binding".to_string(),
                        })?,
                );

                // Create local disk-persisted KV implementation
                let kv_impl = LocalKv::new(data_dir).await?;

                let kv: Arc<dyn Kv> = Arc::new(kv_impl);
                Ok(kv)
            }
            #[cfg(not(feature = "local"))]
            KvBinding::Local { .. } => Err(AlienError::new(ErrorData::FeatureNotEnabled {
                feature: "local".to_string(),
            })),

            KvBinding::Redis(_) => Err(AlienError::new(ErrorData::NotImplemented {
                operation: "Redis KV binding".to_string(),
                reason: "Redis KV provider is not yet implemented".to_string(),
            })),
        }?;

        self.put_cache("kv", binding_name, result.clone()).await;
        Ok(result)
    }

    async fn load_queue(&self, binding_name: &str) -> Result<Arc<dyn Queue>> {
        if let Some(cached) = self
            .get_cached::<Arc<dyn Queue>>("queue", binding_name)
            .await
        {
            return Ok(cached);
        }

        use alien_core::bindings::QueueBinding;

        let binding_json = self.bindings.get(binding_name).ok_or_else(|| {
            AlienError::new(ErrorData::BindingConfigInvalid {
                binding_name: binding_name.to_string(),
                reason: "Binding not found".to_string(),
            })
        })?;

        let binding: QueueBinding = serde_json::from_value(binding_json.clone())
            .into_alien_error()
            .context(ErrorData::BindingConfigInvalid {
                binding_name: binding_name.to_string(),
                reason: "Failed to parse Queue binding".to_string(),
            })?;

        let result: Arc<dyn Queue> = match binding {
            #[cfg(feature = "aws")]
            QueueBinding::Sqs(config) => {
                use crate::providers::queue::aws_sqs::AwsSqsQueue;

                let queue_url = config
                    .queue_url
                    .into_value(binding_name, "queue_url")
                    .context(ErrorData::BindingConfigInvalid {
                        binding_name: binding_name.to_string(),
                        reason: "Failed to extract queue_url from SQS binding".to_string(),
                    })?;

                let aws_config = self.client_config.aws_config().ok_or_else(|| {
                    AlienError::new(ErrorData::ClientConfigInvalid {
                        platform: Platform::Aws,
                        message: "AWS config not available".to_string(),
                    })
                })?;
                let credentials =
                    alien_aws_clients::AwsCredentialProvider::from_config(aws_config.clone())
                        .await
                        .context(ErrorData::ClientConfigInvalid {
                            platform: Platform::Aws,
                            message: "Failed to create AWS credential provider".to_string(),
                        })?;
                let client = alien_aws_clients::sqs::SqsClient::new(
                    crate::http_client::create_http_client(),
                    credentials,
                );
                let q: Arc<dyn Queue> = Arc::new(AwsSqsQueue::new(queue_url, client));
                Ok(q)
            }
            #[cfg(not(feature = "aws"))]
            QueueBinding::Sqs(_) => Err(AlienError::new(ErrorData::FeatureNotEnabled {
                feature: "aws".to_string(),
            })),

            #[cfg(feature = "gcp")]
            QueueBinding::Pubsub(config) => {
                use crate::providers::queue::gcp_pubsub::GcpPubSubQueue;
                let topic_name = config.topic.into_value(binding_name, "topic").context(
                    ErrorData::BindingConfigInvalid {
                        binding_name: binding_name.to_string(),
                        reason: "Failed to extract topic".to_string(),
                    },
                )?;
                let subscription_name = config
                    .subscription
                    .into_value(binding_name, "subscription")
                    .context(ErrorData::BindingConfigInvalid {
                        binding_name: binding_name.to_string(),
                        reason: "Failed to extract subscription".to_string(),
                    })?;
                let gcp_config = self.client_config.gcp_config().ok_or_else(|| {
                    AlienError::new(ErrorData::ClientConfigInvalid {
                        platform: Platform::Gcp,
                        message: "GCP config not available".to_string(),
                    })
                })?;

                // Pass short names — PubSubClient methods prepend the project prefix
                let topic = if let Some(short) =
                    topic_name.strip_prefix(&format!("projects/{}/topics/", gcp_config.project_id))
                {
                    short.to_string()
                } else {
                    topic_name
                };
                let subscription = if let Some(short) = subscription_name.strip_prefix(&format!(
                    "projects/{}/subscriptions/",
                    gcp_config.project_id
                )) {
                    short.to_string()
                } else {
                    subscription_name
                };

                let q: Arc<dyn Queue> =
                    Arc::new(GcpPubSubQueue::new(topic, subscription, gcp_config.clone()).await?);
                Ok(q)
            }
            #[cfg(not(feature = "gcp"))]
            QueueBinding::Pubsub(_) => Err(AlienError::new(ErrorData::FeatureNotEnabled {
                feature: "gcp".to_string(),
            })),

            #[cfg(feature = "azure")]
            QueueBinding::Servicebus(config) => {
                use crate::providers::queue::azure_service_bus::AzureServiceBusQueue;
                let namespace = config
                    .namespace
                    .into_value(binding_name, "namespace")
                    .context(ErrorData::BindingConfigInvalid {
                        binding_name: binding_name.to_string(),
                        reason: "Failed to extract namespace".to_string(),
                    })?;
                let queue_name = config
                    .queue_name
                    .into_value(binding_name, "queue_name")
                    .context(ErrorData::BindingConfigInvalid {
                        binding_name: binding_name.to_string(),
                        reason: "Failed to extract queue_name".to_string(),
                    })?;
                let azure_config = self.client_config.azure_config().ok_or_else(|| {
                    AlienError::new(ErrorData::ClientConfigInvalid {
                        platform: Platform::Azure,
                        message: "Azure config not available".to_string(),
                    })
                })?;
                let q: Arc<dyn Queue> = Arc::new(
                    AzureServiceBusQueue::new(namespace, queue_name, azure_config.clone()).await?,
                );
                Ok(q)
            }
            #[cfg(not(feature = "azure"))]
            QueueBinding::Servicebus(_) => Err(AlienError::new(ErrorData::FeatureNotEnabled {
                feature: "azure".to_string(),
            })),

            #[cfg(feature = "local")]
            QueueBinding::Local(config) => {
                use crate::providers::queue::local::LocalQueue;

                let queue = LocalQueue::from_binding(config).await?;
                let q: Arc<dyn Queue> = Arc::new(queue);
                Ok(q)
            }
            #[cfg(not(feature = "local"))]
            QueueBinding::Local(_) => Err(AlienError::new(ErrorData::FeatureNotEnabled {
                feature: "local".to_string(),
            })),
        }?;

        self.put_cache("queue", binding_name, result.clone()).await;
        Ok(result)
    }

    async fn load_worker(&self, binding_name: &str) -> Result<Arc<dyn Worker>> {
        use alien_core::bindings::WorkerBinding;

        let binding_json = self.bindings.get(binding_name).ok_or_else(|| {
            AlienError::new(ErrorData::BindingConfigInvalid {
                binding_name: binding_name.to_string(),
                reason: "Binding not found".to_string(),
            })
        })?;

        let binding: WorkerBinding = serde_json::from_value(binding_json.clone())
            .into_alien_error()
            .context(ErrorData::BindingConfigInvalid {
                binding_name: binding_name.to_string(),
                reason: "Failed to parse worker binding".to_string(),
            })?;

        match binding {
            #[cfg(feature = "aws")]
            WorkerBinding::Lambda(lambda_binding) => {
                use crate::providers::worker::LambdaWorker;

                let aws_config = self.client_config.aws_config().ok_or_else(|| {
                    AlienError::new(ErrorData::ClientConfigInvalid {
                        platform: Platform::Aws,
                        message: "AWS config not available".to_string(),
                    })
                })?;
                let credentials =
                    alien_aws_clients::AwsCredentialProvider::from_config(aws_config.clone())
                        .await
                        .context(ErrorData::ClientConfigInvalid {
                            platform: Platform::Aws,
                            message: "Failed to create AWS credential provider".to_string(),
                        })?;
                let client = crate::http_client::create_http_client();

                let function_impl = LambdaWorker::new(client, credentials, lambda_binding);
                let function: Arc<dyn Worker> = Arc::new(function_impl);
                Ok(function)
            }
            #[cfg(not(feature = "aws"))]
            WorkerBinding::Lambda(_) => Err(AlienError::new(ErrorData::FeatureNotEnabled {
                feature: "aws".to_string(),
            })),

            #[cfg(feature = "gcp")]
            WorkerBinding::CloudRun(cloudrun_binding) => {
                use crate::providers::worker::CloudRunWorker;

                let gcp_config = self.client_config.gcp_config().ok_or_else(|| {
                    AlienError::new(ErrorData::ClientConfigInvalid {
                        platform: Platform::Gcp,
                        message: "GCP config not available".to_string(),
                    })
                })?;
                let client = crate::http_client::create_http_client();

                let function_impl =
                    CloudRunWorker::new(client, gcp_config.clone(), cloudrun_binding);
                let function: Arc<dyn Worker> = Arc::new(function_impl);
                Ok(function)
            }
            #[cfg(not(feature = "gcp"))]
            WorkerBinding::CloudRun(_) => Err(AlienError::new(ErrorData::FeatureNotEnabled {
                feature: "gcp".to_string(),
            })),

            #[cfg(feature = "azure")]
            WorkerBinding::ContainerApp(container_app_binding) => {
                use crate::providers::worker::ContainerAppWorker;

                let azure_config = self.client_config.azure_config().ok_or_else(|| {
                    AlienError::new(ErrorData::ClientConfigInvalid {
                        platform: Platform::Azure,
                        message: "Azure config not available".to_string(),
                    })
                })?;
                let client = crate::http_client::create_http_client();

                let function_impl =
                    ContainerAppWorker::new(client, azure_config.clone(), container_app_binding);
                let function: Arc<dyn Worker> = Arc::new(function_impl);
                Ok(function)
            }
            #[cfg(not(feature = "azure"))]
            WorkerBinding::ContainerApp(_) => Err(AlienError::new(ErrorData::FeatureNotEnabled {
                feature: "azure".to_string(),
            })),

            #[cfg(feature = "local")]
            WorkerBinding::Local(local_binding) => {
                use crate::providers::worker::LocalWorker;

                let function_impl = LocalWorker::new(local_binding);
                let function: Arc<dyn Worker> = Arc::new(function_impl);
                Ok(function)
            }
            #[cfg(not(feature = "local"))]
            WorkerBinding::Local(_) => Err(AlienError::new(ErrorData::FeatureNotEnabled {
                feature: "local".to_string(),
            })),

            #[cfg(feature = "kubernetes")]
            WorkerBinding::Kubernetes(kubernetes_binding) => {
                use crate::providers::worker::KubernetesWorker;

                let function_impl =
                    KubernetesWorker::new(binding_name.to_string(), kubernetes_binding)?;
                let function: Arc<dyn Worker> = Arc::new(function_impl);
                Ok(function)
            }
            #[cfg(not(feature = "kubernetes"))]
            WorkerBinding::Kubernetes(_) => Err(AlienError::new(ErrorData::FeatureNotEnabled {
                feature: "kubernetes".to_string(),
            })),
        }
    }

    async fn load_container(
        &self,
        binding_name: &str,
    ) -> Result<Arc<dyn crate::traits::Container>> {
        use alien_core::bindings::ContainerBinding;

        let binding_json = self.bindings.get(binding_name).ok_or_else(|| {
            AlienError::new(ErrorData::BindingConfigInvalid {
                binding_name: binding_name.to_string(),
                reason: "Binding not found".to_string(),
            })
        })?;

        let binding: ContainerBinding = serde_json::from_value(binding_json.clone())
            .into_alien_error()
            .context(ErrorData::BindingConfigInvalid {
                binding_name: binding_name.to_string(),
                reason: "Failed to parse container binding".to_string(),
            })?;

        match binding {
            ContainerBinding::Horizon(horizon_binding) => {
                use crate::providers::container::HorizonContainer;

                let container_impl = HorizonContainer::new(horizon_binding)?;
                let container: Arc<dyn crate::traits::Container> = Arc::new(container_impl);
                Ok(container)
            }

            #[cfg(feature = "local")]
            ContainerBinding::Local(local_binding) => {
                use crate::providers::container::LocalContainer;

                let container_impl = LocalContainer::new(local_binding)?;
                let container: Arc<dyn crate::traits::Container> = Arc::new(container_impl);
                Ok(container)
            }
            #[cfg(not(feature = "local"))]
            ContainerBinding::Local(_) => Err(AlienError::new(ErrorData::FeatureNotEnabled {
                feature: "local".to_string(),
            })),

            #[cfg(feature = "kubernetes")]
            ContainerBinding::Kubernetes(kubernetes_binding) => {
                use crate::providers::container::KubernetesContainer;

                let container_impl =
                    KubernetesContainer::new(binding_name.to_string(), kubernetes_binding)?;
                let container: Arc<dyn crate::traits::Container> = Arc::new(container_impl);
                Ok(container)
            }
            #[cfg(not(feature = "kubernetes"))]
            ContainerBinding::Kubernetes(_) => Err(AlienError::new(ErrorData::FeatureNotEnabled {
                feature: "kubernetes".to_string(),
            })),
        }
    }

    async fn load_service_account(
        &self,
        binding_name: &str,
    ) -> Result<Arc<dyn crate::traits::ServiceAccount>> {
        use alien_core::bindings::ServiceAccountBinding;

        let binding_json = self.bindings.get(binding_name).ok_or_else(|| {
            AlienError::new(ErrorData::BindingConfigInvalid {
                binding_name: binding_name.to_string(),
                reason: "Binding not found".to_string(),
            })
        })?;

        let binding: ServiceAccountBinding = serde_json::from_value(binding_json.clone())
            .into_alien_error()
            .context(ErrorData::BindingConfigInvalid {
                binding_name: binding_name.to_string(),
                reason: "Failed to parse service account binding".to_string(),
            })?;

        match binding {
            #[cfg(feature = "aws")]
            ServiceAccountBinding::AwsIam(aws_binding) => {
                use crate::providers::service_account::aws_iam::AwsIamServiceAccount;

                let aws_config = self.client_config.aws_config().ok_or_else(|| {
                    AlienError::new(ErrorData::ClientConfigInvalid {
                        platform: Platform::Aws,
                        message: "AWS config not available".to_string(),
                    })
                })?;
                let client = crate::http_client::create_http_client();

                let service_account_impl =
                    AwsIamServiceAccount::new(client, aws_config.clone(), aws_binding);
                let service_account: Arc<dyn crate::traits::ServiceAccount> =
                    Arc::new(service_account_impl);
                Ok(service_account)
            }
            #[cfg(not(feature = "aws"))]
            ServiceAccountBinding::AwsIam(_) => {
                Err(AlienError::new(ErrorData::FeatureNotEnabled {
                    feature: "aws".to_string(),
                }))
            }

            #[cfg(feature = "gcp")]
            ServiceAccountBinding::GcpServiceAccount(gcp_binding) => {
                use crate::providers::service_account::gcp_service_account::GcpServiceAccount;

                let gcp_config = self.client_config.gcp_config().ok_or_else(|| {
                    AlienError::new(ErrorData::ClientConfigInvalid {
                        platform: Platform::Gcp,
                        message: "GCP config not available".to_string(),
                    })
                })?;
                let client = crate::http_client::create_http_client();

                let service_account_impl =
                    GcpServiceAccount::new(client, gcp_config.clone(), gcp_binding);
                let service_account: Arc<dyn crate::traits::ServiceAccount> =
                    Arc::new(service_account_impl);
                Ok(service_account)
            }
            #[cfg(not(feature = "gcp"))]
            ServiceAccountBinding::GcpServiceAccount(_) => {
                Err(AlienError::new(ErrorData::FeatureNotEnabled {
                    feature: "gcp".to_string(),
                }))
            }

            #[cfg(feature = "azure")]
            ServiceAccountBinding::AzureManagedIdentity(azure_binding) => {
                use crate::providers::service_account::azure_managed_identity::AzureManagedIdentityServiceAccount;

                let azure_config = self.client_config.azure_config().ok_or_else(|| {
                    AlienError::new(ErrorData::ClientConfigInvalid {
                        platform: Platform::Azure,
                        message: "Azure config not available".to_string(),
                    })
                })?;

                let service_account_impl =
                    AzureManagedIdentityServiceAccount::new(azure_config.clone(), azure_binding);
                let service_account: Arc<dyn crate::traits::ServiceAccount> =
                    Arc::new(service_account_impl);
                Ok(service_account)
            }
            #[cfg(not(feature = "azure"))]
            ServiceAccountBinding::AzureManagedIdentity(_) => {
                Err(AlienError::new(ErrorData::FeatureNotEnabled {
                    feature: "azure".to_string(),
                }))
            }
        }
    }
}

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

    fn kubernetes_aws_env() -> HashMap<String, String> {
        HashMap::from([
            (
                ENV_ALIEN_DEPLOYMENT_TYPE.to_string(),
                Platform::Kubernetes.as_str().to_string(),
            ),
            (
                ENV_ALIEN_BASE_PLATFORM.to_string(),
                Platform::Aws.as_str().to_string(),
            ),
            (
                "KUBERNETES_SERVICE_HOST".to_string(),
                "10.0.0.1".to_string(),
            ),
            ("KUBERNETES_SERVICE_PORT".to_string(), "443".to_string()),
            ("AWS_REGION".to_string(), "us-east-1".to_string()),
            ("AWS_ACCOUNT_ID".to_string(), "123456789012".to_string()),
            ("AWS_ACCESS_KEY_ID".to_string(), "test".to_string()),
            ("AWS_SECRET_ACCESS_KEY".to_string(), "test".to_string()),
        ])
    }

    fn kubernetes_azure_env() -> HashMap<String, String> {
        HashMap::from([
            (
                ENV_ALIEN_DEPLOYMENT_TYPE.to_string(),
                Platform::Kubernetes.as_str().to_string(),
            ),
            (
                ENV_ALIEN_BASE_PLATFORM.to_string(),
                Platform::Azure.as_str().to_string(),
            ),
            (
                "KUBERNETES_SERVICE_HOST".to_string(),
                "10.0.0.1".to_string(),
            ),
            ("KUBERNETES_SERVICE_PORT".to_string(), "443".to_string()),
            (
                "AZURE_SUBSCRIPTION_ID".to_string(),
                "00000000-0000-0000-0000-000000000000".to_string(),
            ),
            (
                "AZURE_TENANT_ID".to_string(),
                "11111111-1111-1111-1111-111111111111".to_string(),
            ),
            ("AZURE_REGION".to_string(), "eastus".to_string()),
            (
                "AZURE_CLIENT_ID".to_string(),
                "22222222-2222-2222-2222-222222222222".to_string(),
            ),
            (
                "AZURE_FEDERATED_TOKEN_FILE".to_string(),
                "/var/run/secrets/azure/tokens/azure-identity-token".to_string(),
            ),
            (
                "AZURE_AUTHORITY_HOST".to_string(),
                "https://login.microsoftonline.com/".to_string(),
            ),
        ])
    }

    #[tokio::test]
    async fn lazy_env_provider_defers_cloud_client_config_until_binding_use() {
        let env = HashMap::from([
            (
                ENV_ALIEN_DEPLOYMENT_TYPE.to_string(),
                Platform::Aws.as_str().to_string(),
            ),
            ("AWS_EC2_METADATA_DISABLED".to_string(), "true".to_string()),
            (
                "AWS_PROFILE".to_string(),
                "__alien_missing_test_profile__".to_string(),
            ),
            (
                "ALIEN_SECRETS_BINDING".to_string(),
                r#"{"service":"parameter-store","vaultPrefix":"test-secrets"}"#.to_string(),
            ),
        ]);

        let provider = BindingsProvider::from_env_lazy(env)
            .expect("lazy provider construction should validate binding JSON without AWS config");

        let error = provider
            .load_vault("secrets")
            .await
            .expect_err("binding use should still require AWS client config");

        assert_eq!(error.code, "CLIENT_CONFIG_INVALID");
    }

    #[tokio::test]
    async fn from_env_builds_kubernetes_cloud_config_when_base_platform_is_set() {
        let provider = BindingsProvider::from_env(kubernetes_aws_env())
            .await
            .unwrap();

        assert!(provider.client_config.kubernetes_config().is_some());
        assert!(provider.client_config.aws_config().is_some());
        assert!(matches!(
            provider.client_config,
            ClientConfig::KubernetesCloud { .. }
        ));
    }

    #[tokio::test]
    async fn from_env_builds_kubernetes_cloud_config_for_azure_workload_identity() {
        let provider = BindingsProvider::from_env(kubernetes_azure_env())
            .await
            .unwrap();

        assert!(provider.client_config.kubernetes_config().is_some());
        assert!(provider.client_config.azure_config().is_some());
        assert!(matches!(
            provider.client_config,
            ClientConfig::KubernetesCloud { .. }
        ));
    }

    #[tokio::test]
    async fn from_env_rejects_non_cloud_kubernetes_base_platform() {
        let mut env = kubernetes_aws_env();
        env.insert(
            ENV_ALIEN_BASE_PLATFORM.to_string(),
            Platform::Kubernetes.as_str().to_string(),
        );

        let error = BindingsProvider::from_env(env).await.unwrap_err();

        assert!(error.to_string().contains(ENV_ALIEN_BASE_PLATFORM));
    }
}

/// Conversion functions between SDK types and alien-core types
#[cfg(feature = "platform-sdk")]
mod conversions {
    use super::*;
    use serde::Serialize;

    /// Convert SDK AgentStackState to alien-core StackState
    /// Generic over any serializable type since we convert via JSON
    pub fn convert_stack_state<T: Serialize>(sdk_stack_state: &T) -> Result<StackState> {
        // Convert via JSON serialization/deserialization (same pattern as deploy.rs)
        let stack_state: StackState = serde_json::from_value(
            serde_json::to_value(sdk_stack_state)
                .into_alien_error()
                .context(ErrorData::BindingConfigInvalid {
                    binding_name: "stack_state".to_string(),
                    reason: "Failed to serialize SDK stack state".to_string(),
                })?,
        )
        .into_alien_error()
        .context(ErrorData::BindingConfigInvalid {
            binding_name: "stack_state".to_string(),
            reason: "Failed to parse stack state".to_string(),
        })?;

        Ok(stack_state)
    }
}