ebman 0.30.1

k9s-style TUI for AWS Elastic Beanstalk
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
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
//! Elastic Beanstalk itself — the domain this tool is built around.
//!
//! Everything here is EB-shaped: environments and their health, the
//! application/version model, option settings, saved-configuration
//! templates, platform upgrades. The other `aws/*` modules are the
//! generic AWS surface any operator TUI would want; this one is the
//! part that makes ebman specifically an Elastic Beanstalk tool.

use super::*;

#[derive(Clone, Debug)]
pub struct Event {
    pub at: Option<DateTime<Utc>>,
    pub env: String,
    pub application: String,
    pub message: String,
    pub severity: String,
    /// Application version label this event relates to, when EB
    /// tags it (deploy events carry it). `None` for events with no
    /// associated version. Drives `:rollback`'s previous-version
    /// detection.
    pub version_label: Option<String>,
}

#[derive(Clone, Debug)]
pub struct Instance {
    pub id: String,
    pub health: String, // Ok / Warning / Degraded / Severe / Info / NoData / Unknown / Pending
    pub color: String,  // Green / Yellow / Red / Grey
    pub causes: Vec<String>,
    pub instance_type: String,
    pub availability_zone: String,
    pub launched_at: Option<DateTime<Utc>>,
}

#[derive(Clone, Debug)]
pub struct Application {
    pub name: String,
    pub description: String,
    /// Surfaced in the `:apps-info` overlay (in operator timezone)
    /// alongside `date_updated`. Was orphaned briefly when the apps
    /// table dropped its CREATED column in 0.3.3.
    pub date_created: Option<DateTime<Utc>>,
    pub date_updated: Option<DateTime<Utc>>,
    pub version_count: usize,
    pub templates: Vec<String>,
    /// Newest application version's label (from `DescribeApplicationVersions`,
    /// sorted by date_created desc). Populated by a follow-up fetch after
    /// `list_applications` — `None` while still loading or if the app has
    /// no versions yet. The EB-console "latest deployed version" matches
    /// this field, not the application-level `date_updated`.
    pub latest_version_label: Option<String>,
    /// `date_created` of the newest application version.
    pub latest_version_created: Option<DateTime<Utc>>,
}

#[derive(Clone, Debug)]
pub struct CustomPlatform {
    pub arn: String,
    pub branch: String,
    pub version: String,
    pub status: String,
    pub lifecycle: String,
}

#[derive(Clone, Debug)]
pub struct AppVersion {
    pub label: String,
    pub description: String,
    pub created: Option<DateTime<Utc>>,
}

#[derive(Clone, Debug)]
pub struct Environment {
    pub name: String,
    pub application: String,
    pub status: String,
    pub health: String,
    pub platform: String, // family + version, e.g. "Java 17"
    /// Raw solution-stack name as reported by EB, e.g. `64bit Amazon Linux
    /// 2023 v6.1.0 running Node.js 18`. Empty for platform-ARN / custom-
    /// platform envs that don't report a solution stack. Drives the
    /// stale-platform comparison against `ListAvailableSolutionStacks`.
    pub solution_stack: String,
    pub tier: String, // "Web" / "Worker" / "?"
    pub cname: String,
    pub version_label: String,
    pub arn: Option<String>,
    pub updated: Option<DateTime<Utc>>,
    /// Internal EB environment ID (e.g. `e-abcdef1234`). Required by APIs
    /// that snapshot config from a live env (CreateConfigurationTemplate).
    pub id: Option<String>,
    /// Region the env was discovered in, when results were fanned out across
    /// multiple regions. `None` in single-region mode.
    pub region: Option<String>,
}

/// Per-env summary of instance health, as surfaced in the `INST` column
/// of the main env table. `healthy` is the count EB classifies as Green
/// (Ok + Info — both are "passing health checks", Info just means an
/// operation is in progress on an otherwise-healthy instance); `total`
/// is the sum across every health bucket the env reports. `total == 0`
/// is a real signal (env has no instances right now, e.g. mid-launch),
/// rendered as `0/0` in the table.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct EnvInstanceCounts {
    pub healthy: i32,
    pub total: i32,
}

/// Parsed `DescribeEnvironmentResources` payload. The SDK returns
/// flat lists; we hold them in field-typed buckets so the
/// `:resources` renderer can format them as a hierarchical tree
/// (ASG → instances → LB → queues etc.) without re-traversing
/// the raw API shape.
#[derive(Clone, Debug, Default)]
pub struct EnvResources {
    pub asgs: Vec<String>,
    pub instances: Vec<String>,
    pub launch_configs: Vec<String>,
    pub launch_templates: Vec<String>,
    pub load_balancers: Vec<String>,
    pub triggers: Vec<String>,
    pub queues: Vec<EnvResourceQueue>,
}

#[derive(Clone, Debug)]
pub struct EnvResourceQueue {
    pub name: String,
    pub url: String,
}

/// One settable EB configuration option, as returned by
/// [`AwsClient::fetch_env_configuration_options`]. Covers both the
/// operator's currently-set value and the platform's metadata
/// (default / constraints / change severity). `:options` uses this
/// to render the full config vocabulary in one overlay.
#[derive(Clone, Debug)]
pub struct ConfigOption {
    pub namespace: String,
    pub name: String,
    /// Current value, or `None` when the operator hasn't overridden
    /// the default. EB sometimes returns `Some("")` for unset; the
    /// renderer treats both as "default" and tags accordingly.
    pub value: Option<String>,
    pub default_value: Option<String>,
    /// `"Scalar"` / `"List"` / sometimes blank. Lower-cased on
    /// the wire; we render as-is.
    pub value_type: String,
    /// Constrained value options for enum-shaped settings
    /// (e.g. `["AllAtOnce", "Rolling", "Immutable", ...]` for
    /// `DeploymentPolicy`). Empty Vec when unconstrained.
    pub value_options: Vec<String>,
    /// `"NoInterruption"` / `"RestartEnvironment"` /
    /// `"RestartApplicationServer"` / `"Unknown"`. Warns the
    /// operator that changing this option will roll instances.
    pub change_severity: Option<String>,
    /// EB exposes a "this option is operator-settable" flag —
    /// most options have this true. Currently captured but not
    /// rendered (operator-set vs default distinction is enough
    /// signal); kept on the struct because a future "hide read-only
    /// options" filter would consume it.
    #[allow(dead_code)]
    pub user_defined: Option<bool>,
    pub min_value: Option<i32>,
    pub max_value: Option<i32>,
    pub max_length: Option<i32>,
}

/// How many `DescribeEvents` pages one watermarked `:event-tail` poll
/// will follow. At `EVENT_TAIL_POLL_BATCH` (300) per page that is 1500
/// events per 5-second poll — far past any real fleet, so the cap is a
/// runaway guard rather than a limit anyone should hit. Reaching it
/// logs a warning.
const EVENT_TAIL_MAX_PAGES: usize = 5;

/// `ListPlatformVersions` summary → our `CustomPlatform` row.
///
/// Both platform listings — every custom platform, and the
/// upgrade-compatible ones for a given env — return the same shape and
/// mapped it identically.
pub(super) fn map_platform(p: aws_sdk_elasticbeanstalk::types::PlatformSummary) -> CustomPlatform {
    CustomPlatform {
        arn: p.platform_arn.unwrap_or_default(),
        branch: p.platform_branch_name.unwrap_or_default(),
        version: p.platform_version.unwrap_or_default(),
        status: p
            .platform_status
            .map(|s| s.as_str().to_string())
            .unwrap_or_default(),
        lifecycle: p.platform_lifecycle_state.unwrap_or_default(),
    }
}

pub(super) fn map_env(e: aws_sdk_elasticbeanstalk::types::EnvironmentDescription) -> Environment {
    let solution_stack = e.solution_stack_name.clone().unwrap_or_default();
    let raw_platform = e
        .solution_stack_name
        .clone()
        .or(e.platform_arn.clone())
        .unwrap_or_default();
    let tier = e
        .tier
        .as_ref()
        .and_then(|t| t.name.as_deref())
        .map(normalize_tier)
        .unwrap_or_else(|| "?".into());
    Environment {
        name: e.environment_name.unwrap_or_default(),
        application: e.application_name.unwrap_or_default(),
        status: e
            .status
            .map(|s| s.as_str().to_string())
            .unwrap_or_else(|| "-".into()),
        health: e
            .health
            .map(|h| h.as_str().to_string())
            .unwrap_or_else(|| "-".into()),
        platform: platform_family(&raw_platform),
        solution_stack,
        tier,
        cname: e.cname.unwrap_or_default(),
        version_label: e.version_label.unwrap_or_default(),
        arn: e.environment_arn,
        updated: e
            .date_updated
            .and_then(|d| DateTime::from_timestamp(d.secs(), d.subsec_nanos())),
        id: e.environment_id,
        region: None,
    }
}

/// Fan-out helper: build a transient `AwsClient` for `region` (sharing the
/// caller's profile) and pull `DescribeEnvironments` from there. Each
/// returned env has `region` stamped so the table can sort / group on it.
/// Best-effort extraction of the EB platform branch name from a solution
/// stack name or platform ARN. The names look like `64bit Amazon Linux 2023
/// v4.5.2 running Tomcat 9 Corretto 17` — we keep the "running …" tail and
/// strip any leading "running " marker. ARNs follow a separate scheme and
/// already carry the branch in their path.
pub(crate) fn platform_branch_from(stack_or_arn: &str) -> String {
    // ARN first — every real platform ARN's name segment itself
    // contains " running " (e.g. ".../platform/Python 3.9 running on
    // 64bit Amazon Linux 2023/4.0.1"), so the solution-stack split
    // below would mangle it into "on 64bit …". The second-to-last
    // path segment IS the full branch name.
    if stack_or_arn.starts_with("arn:") {
        let parts: Vec<&str> = stack_or_arn.split('/').collect();
        if parts.len() >= 2 {
            return parts[parts.len() - 2].to_string();
        }
        return String::new();
    }
    // Solution stack ("64bit Amazon Linux 2023 v4.0.1 running
    // Python 3.9") yields the branch FAMILY ("Python 3.9"). Real
    // branch names are "<family> running on <os>" — which is why the
    // PlatformBranchName filter uses begins_with, not `=` (an exact
    // match against the bare family matched nothing, so `:upgrade`
    // always reported an empty compatible-platform list).
    if let Some(rest) = stack_or_arn.split(" running ").nth(1) {
        return rest.trim().to_string();
    }
    String::new()
}

/// Pure: roll up EB's per-bucket `InstanceHealthSummary` into the
/// `(healthy, total)` shape the INST column wants. `healthy` is `ok +
/// info` (both Green per EB's docs — Info just means an operation is in
/// progress on an otherwise-healthy instance, not a problem signal).
/// `total` is the sum across every bucket including Grey buckets like
/// `no_data` / `unknown` / `pending` so an env that's mid-launch
/// reports `0/N` rather than `0/0`. Missing input (`None`) and
/// all-None buckets render as `EnvInstanceCounts::default()` (0/0).
pub fn summarise_instance_health(
    summary: Option<&aws_sdk_elasticbeanstalk::types::InstanceHealthSummary>,
) -> EnvInstanceCounts {
    let Some(s) = summary else {
        return EnvInstanceCounts::default();
    };
    let g = |v: Option<i32>| v.unwrap_or(0);
    let ok = g(s.ok);
    let info = g(s.info);
    let healthy = ok + info;
    let total = g(s.no_data)
        + g(s.unknown)
        + g(s.pending)
        + ok
        + info
        + g(s.warning)
        + g(s.degraded)
        + g(s.severe);
    EnvInstanceCounts { healthy, total }
}

/// Split a solution-stack name into `(family_key, version)`. The family key
/// is the stack name with its `vX.Y.Z` token removed and surrounding
/// whitespace collapsed, so two stacks that differ only in version share a
/// key (e.g. `64bit Amazon Linux 2023 v6.1.0 running Node.js 18` →
/// `("64bit Amazon Linux 2023 running Node.js 18", "6.1.0")`). Returns
/// `None` when no `vN.N…` token is present — platform-ARN / custom-platform
/// envs have no solution stack and so can't be version-compared.
pub fn stack_family_version(stack: &str) -> Option<(String, String)> {
    let version_token = stack.split_whitespace().find(|tok| {
        tok.strip_prefix('v')
            .map(|rest| {
                !rest.is_empty()
                    && rest
                        .split('.')
                        .all(|p| !p.is_empty() && p.chars().all(|c| c.is_ascii_digit()))
            })
            .unwrap_or(false)
    })?;
    let version = version_token.trim_start_matches('v').to_string();
    let key = stack
        .split_whitespace()
        .filter(|tok| *tok != version_token)
        .collect::<Vec<_>>()
        .join(" ");
    Some((key, version))
}

/// Build a `family_key → newest version` map from a flat
/// `ListAvailableSolutionStacks` listing. Stacks with no version token are
/// skipped.
pub fn latest_stack_versions(stacks: &[String]) -> std::collections::HashMap<String, String> {
    let mut out: std::collections::HashMap<String, String> = std::collections::HashMap::new();
    for s in stacks {
        if let Some((key, ver)) = stack_family_version(s) {
            match out.get(&key) {
                Some(cur)
                    if crate::util::compare_versions(&ver, cur) != std::cmp::Ordering::Greater => {}
                _ => {
                    out.insert(key, ver);
                }
            }
        }
    }
    out
}

/// If a strictly-newer version of `env_stack`'s platform family exists in
/// `latest`, return that version. `None` when the env is already current,
/// has no parseable stack, or its family isn't in the listing.
pub fn newer_stack_version(
    env_stack: &str,
    latest: &std::collections::HashMap<String, String>,
) -> Option<String> {
    let (key, ver) = stack_family_version(env_stack)?;
    let newest = latest.get(&key)?;
    if crate::util::compare_versions(newest, &ver) == std::cmp::Ordering::Greater {
        Some(newest.clone())
    } else {
        None
    }
}

pub async fn list_environments_in_region(
    profile: Option<String>,
    region: String,
) -> Result<Vec<Environment>> {
    // Every error out of this function carries its region. The
    // multi-region fan-out's whole purpose is to say WHICH region's
    // environments are missing, and neither `cached_client` nor
    // `list_environments` attaches one — so the notice read "some
    // regions failed … DescribeEnvironments: …" with no region in it.
    let client = super::cached_client(profile, region.clone())
        .await
        .wrap_err_with(|| format!("region {region}"))?;
    // Label with the region the client RESOLVED to, not the one asked
    // for. `AwsClient::with` detects and logs the case where the SDK
    // ignores an explicit region (an empty or whitespace value leaves
    // the env/profile chain to pick), and when that happens the
    // fan-out queries region B while labelling every row region A —
    // so the REGION column, `:find-env` results and any region-scoped
    // follow-up action all point at the wrong place.
    let resolved_region = client.context.region.clone();
    let mut envs = client
        .list_environments()
        .await
        .wrap_err_with(|| format!("region {region}"))?;
    stamp_region(&mut envs, &resolved_region);
    Ok(envs)
}

/// Stamp every row with the region its client actually resolved to.
///
/// Shared by both multi-region entry points on purpose: they diverged
/// once, one using the requested region and the other the resolved one,
/// and the difference was invisible until a region string failed to
/// bind. One function means they can't drift again.
pub(super) fn stamp_region(envs: &mut [Environment], resolved_region: &str) {
    for e in envs {
        e.region = Some(resolved_region.to_string());
    }
}

/// Sibling of `list_environments_in_region` for the AssumeRole path:
/// assumes into the named role, then lists envs. `region` overrides the
/// AccountSpec's region when supplied; otherwise the spec's own region
/// wins (or env default). Used by the multi-account fan-out in
/// `:org-health` / `:find-env`.
pub async fn list_environments_for_account(
    name: &str,
    spec: &crate::config::AccountSpec,
    region: Option<String>,
) -> Result<Vec<Environment>> {
    let mut spec = spec.clone();
    if region.is_some() {
        spec.region = region.clone();
    }
    // `cached_role_client`, not a bare `assume_role`: this runs once
    // per region on every 15-second refresh tick under `:account` plus
    // `:region all`, and once per account in `:org-health` / `:find-env`.
    // A fresh AssumeRole each time is an STS call storm for a session
    // that would be perfectly valid for another hour.
    let client = super::cached_role_client(name, &spec).await?;
    let resolved_region = client.context.region.clone();
    let mut envs = client.list_environments().await?;
    stamp_region(&mut envs, &resolved_region);
    Ok(envs)
}

/// Pulls the family + version out of either a solution_stack_name like
/// "64bit Amazon Linux 2 v3.7.0 running Tomcat 9 Corretto 17"  → "Tomcat 9 Corretto 17"
/// or a platform_arn like
/// "arn:aws:elasticbeanstalk:us-east-1::platform/Java 17 running on 64bit Amazon Linux 2/3.5.0"
///   → "Java 17"
pub(crate) fn platform_family(raw: &str) -> String {
    if raw.is_empty() {
        return String::new();
    }
    // Platform ARN form: "...platform/Family X running on 64bit Amazon Linux/3.5.0"
    // The interesting segment lives between '/' separators and contains " running on ".
    if raw.contains(" running on ") {
        for seg in raw.split('/') {
            if let Some((family, _)) = seg.split_once(" running on ") {
                return family.trim().to_string();
            }
        }
    }
    // Solution-stack form: "...64bit Amazon Linux 2 v3.5.0 running Family X"
    if let Some((_, after)) = raw.rsplit_once(" running ") {
        return after.trim().to_string();
    }
    raw.to_string()
}

pub(crate) fn normalize_tier(name: &str) -> String {
    match name {
        "WebServer" => "Web".into(),
        "Worker" => "Worker".into(),
        other => other.to_string(),
    }
}

#[derive(Clone, Debug, Default)]
pub struct WorkerQueues {
    pub main_url: Option<String>,
    pub dlq_url: Option<String>,
    pub main_stats: Option<QueueStats>,
    pub dlq_stats: Option<QueueStats>,
}

/// Result of `fetch_env_vpc_context` — the env's VPC plus the option-
/// settings selections the `:subnets` / `:elb-subnets` / `:security-groups`
/// pickers need for their pre-fill. Each field is `None` / empty when the
/// env doesn't override that option (EB uses its account-default in that
/// case).
#[derive(Clone, Debug, Default)]
pub struct EnvVpcContext {
    pub vpc_id: Option<String>,
    pub subnets: Vec<String>,
    /// ELB subnets (`aws:ec2:vpc.ELBSubnets`). Web-tier envs typically
    /// attach the ELB to a separate subnet set than the instance subnets;
    /// worker envs leave this empty.
    pub elb_subnets: Vec<String>,
    pub security_groups: Vec<String>,
}

impl AwsClient {
    pub async fn list_events(&self, max: i32) -> Result<Vec<Event>> {
        Ok(self.list_events_inner(None, None, max, 1).await?.0)
    }

    pub async fn list_events_for_env(&self, env_name: &str, max: i32) -> Result<Vec<Event>> {
        Ok(self
            .list_events_inner(Some(env_name.to_string()), None, max, 1)
            .await?
            .0)
    }

    /// Fleet-wide events newer than `since_ms` (epoch millis) — the
    /// `:event-tail` polling primitive. `start_time` keeps each poll's
    /// batch small so a busy fleet doesn't re-ship its whole history
    /// every cycle.
    pub async fn list_events_since(&self, since_ms: i64, max: i32) -> Result<(Vec<Event>, bool)> {
        self.list_events_inner(None, Some(since_ms), max, EVENT_TAIL_MAX_PAGES)
            .await
    }

    /// Shared body for the three `list_events*` entry points.
    ///
    /// `max_pages` is what separates them. `DescribeEvents` returns
    /// newest-first, so a single page is exactly right for the two
    /// display callers — they want "the newest N", and following tokens
    /// would just cost API calls for events nobody renders.
    ///
    /// The watermarked caller is different: `:event-tail` advances
    /// `start_time` past the newest event it received, so anything left
    /// behind a dropped `next_token` is never returned by any later
    /// poll. During a rolling deploy that exceeds one batch, the lines
    /// the operator opened the tail to watch were the ones lost, with
    /// no error and no gap marker. It follows pages instead.
    async fn list_events_inner(
        &self,
        env_name: Option<String>,
        since_ms: Option<i64>,
        max: i32,
        max_pages: usize,
    ) -> Result<(Vec<Event>, bool)> {
        let mut raw = Vec::new();
        let mut next_token: Option<String> = None;
        let mut pages = 0usize;
        let mut truncated = false;
        loop {
            let mut req = self.client.describe_events().max_records(max);
            if let Some(n) = env_name.clone() {
                req = req.environment_name(n);
            }
            if let Some(ms) = since_ms {
                req = req.start_time(aws_sdk_elasticbeanstalk::primitives::DateTime::from_millis(
                    ms,
                ));
            }
            if let Some(t) = next_token.take() {
                req = req.next_token(t);
            }
            let resp = req.send().await?;
            raw.extend(resp.events.unwrap_or_default());
            pages += 1;
            match resp.next_token {
                Some(t) if !t.is_empty() => {
                    if pages < max_pages {
                        next_token = Some(t);
                        continue;
                    }
                    // Stopped with more behind the token. For the
                    // display callers (`max_pages == 1`) that is the
                    // whole point — they asked for the newest N and a
                    // token is present on essentially every real
                    // account — so only the completeness-seeking caller
                    // is worth a word.
                    //
                    // The caller is told too: `list_events_since`
                    // returns this flag and `:event-tail` renders a gap
                    // marker from it. That matters because the tail
                    // advances its watermark past the newest event
                    // received, and DescribeEvents returns
                    // newest-first, so the events behind the token are
                    // OLDER — no later poll's `start_time` can reach
                    // them, and without the marker the tail would look
                    // like unbroken chronology with a hole in it.
                    truncated = true;
                    if max_pages > 1 {
                        tracing::warn!(
                            target: "ebman::aws",
                            pages,
                            collected = raw.len(),
                            "DescribeEvents page cap reached with more pages available — \
                             older events in this window were not fetched"
                        );
                    }
                    break;
                }
                _ => break,
            }
        }
        let events = raw
            .into_iter()
            .map(|e| Event {
                at: e
                    .event_date
                    .and_then(|d| DateTime::from_timestamp(d.secs(), d.subsec_nanos())),
                env: e.environment_name.unwrap_or_default(),
                application: e.application_name.unwrap_or_default(),
                message: e.message.unwrap_or_default(),
                severity: e
                    .severity
                    .map(|s| s.as_str().to_string())
                    .unwrap_or_else(|| "INFO".to_string()),
                version_label: e.version_label.filter(|v| !v.is_empty()),
            })
            .collect();
        Ok((events, truncated))
    }

    /// Full `DescribeEnvironmentResources` dump for an env, formatted as a
    /// human-readable string suitable for an overlay. Covers ASGs,
    /// instances, launch configurations, launch templates, load balancers,
    /// trigger names, and SQS queues — i.e. every infra resource EB
    /// manages for the env. Useful for "what's actually under this env?".
    /// Fetch the env's underlying AWS resources (ASGs, instances,
    /// launch config/template, load balancers, triggers, queues).
    /// Returns the parsed shape so the renderer can format as a
    /// hierarchical tree rather than a flat dump.
    pub async fn describe_env_resources(&self, env_name: &str) -> Result<EnvResources> {
        let resp = self
            .client
            .describe_environment_resources()
            .environment_name(env_name)
            .send()
            .await
            .wrap_err("DescribeEnvironmentResources failed")?;
        let res = resp
            .environment_resources
            .ok_or_else(|| eyre!("no environment_resources in response"))?;
        Ok(EnvResources {
            asgs: res
                .auto_scaling_groups
                .unwrap_or_default()
                .into_iter()
                .filter_map(|a| a.name)
                .collect(),
            instances: res
                .instances
                .unwrap_or_default()
                .into_iter()
                .filter_map(|i| i.id)
                .collect(),
            launch_configs: res
                .launch_configurations
                .unwrap_or_default()
                .into_iter()
                .filter_map(|l| l.name)
                .collect(),
            launch_templates: res
                .launch_templates
                .unwrap_or_default()
                .into_iter()
                .filter_map(|l| l.id)
                .collect(),
            load_balancers: res
                .load_balancers
                .unwrap_or_default()
                .into_iter()
                .filter_map(|l| l.name)
                .collect(),
            triggers: res
                .triggers
                .unwrap_or_default()
                .into_iter()
                .filter_map(|t| t.name)
                .collect(),
            queues: res
                .queues
                .unwrap_or_default()
                .into_iter()
                .filter_map(|q| {
                    let name = q.name?;
                    Some(EnvResourceQueue {
                        name,
                        url: q.url.unwrap_or_default(),
                    })
                })
                .collect(),
        })
    }

    /// Resolve the worker queue URL (and DLQ URL) for an env. EB autocreates
    /// queues when the user doesn't override `WorkerQueueURL`, and in that
    /// (common) case the option value comes back empty — so we ask
    /// `DescribeEnvironmentResources` first, which exposes the actual queue
    /// URLs under named entries (`WorkerQueue`, `WorkerDeadLetterQueue`).
    /// Falls back to the option-settings path for users who override the
    /// URL explicitly.
    pub async fn describe_worker_queues(
        &self,
        application_name: &str,
        env_name: &str,
    ) -> Result<WorkerQueues> {
        let mut main_url: Option<String> = None;
        let mut dlq_url: Option<String> = None;
        // Errors must stay distinguishable from "this env has no
        // queues": the pre-0.27 shape swallowed every failure into
        // an empty result, so an AccessDenied rendered as "no worker
        // queues" and silently blinded DLQ red-alerting.
        let mut discovery_err: Option<String> = None;

        // Primary path: ask EB for the env's resources. Includes the URLs of
        // the queues EB created automatically when WorkerQueueURL is empty.
        match self
            .client
            .describe_environment_resources()
            .environment_name(env_name)
            .send()
            .await
        {
            Ok(resp) => {
                if let Some(res) = resp.environment_resources {
                    for q in res.queues.unwrap_or_default() {
                        let name = q.name.unwrap_or_default();
                        let url = q.url.unwrap_or_default();
                        if url.is_empty() {
                            continue;
                        }
                        match name.as_str() {
                            "WorkerQueue" => main_url = Some(url),
                            "WorkerDeadLetterQueue" => dlq_url = Some(url),
                            _ => {}
                        }
                    }
                }
            }
            Err(e) => discovery_err = Some(format!("DescribeEnvironmentResources: {e}")),
        }

        // Fallback / override: look at user-supplied option settings in case
        // the env explicitly points at a queue the user manages outside EB.
        if main_url.is_none() || dlq_url.is_none() {
            match self
                .client
                .describe_configuration_settings()
                .application_name(application_name)
                .environment_name(env_name)
                .send()
                .await
            {
                Err(e) => {
                    // Record the fallback failure too — resolution
                    // below decides whether it matters.
                    let msg = format!("DescribeConfigurationSettings: {e}");
                    discovery_err = Some(match discovery_err.take() {
                        Some(prior) => format!("{prior} + {msg}"),
                        None => msg,
                    });
                }
                Ok(resp) => {
                    for setting in resp.configuration_settings.unwrap_or_default() {
                        for opt in setting.option_settings.unwrap_or_default() {
                            let ns = opt.namespace.unwrap_or_default();
                            let name = opt.option_name.unwrap_or_default();
                            if ns != "aws:elasticbeanstalk:sqsd" {
                                continue;
                            }
                            match name.as_str() {
                                "WorkerQueueURL" => {
                                    let v = opt.value.unwrap_or_default();
                                    if !v.is_empty() && main_url.is_none() {
                                        main_url = Some(v);
                                    }
                                }
                                "DeadLetterQueueURL" => {
                                    let v = opt.value.unwrap_or_default();
                                    if !v.is_empty() && dlq_url.is_none() {
                                        dlq_url = Some(v);
                                    }
                                }
                                _ => {}
                            }
                        }
                    }
                }
            }
        }

        // A discovery error with nothing found must surface as an
        // error: "no queues" is only trustworthy when at least one
        // discovery call succeeded AND we found nothing — a failed
        // primary may have hidden real EB-created queues (0.27
        // re-review: the first cut only errored when BOTH calls
        // failed, so AccessDenied-on-primary + empty-fallback — the
        // common autocreated-queue case — still read as "no queues"
        // and silently cleared DLQ alerting).
        if main_url.is_none() {
            if let Some(err) = discovery_err {
                return Err(eyre!(err));
            }
        }

        // If we still have a main queue but no DLQ URL, derive one by SQS naming convention.
        if let (Some(main), None) = (&main_url, &dlq_url) {
            dlq_url = derive_dlq_url(main);
        }

        // Stats failures must stay distinguishable from "queue empty"
        // / "no DLQ": SQS permissions are separate from EB's, and an
        // AccessDenied here previously produced dlq_stats=None → the
        // depth cache treated it as "no DLQ" and cleared the alert.
        // NonExistentQueue on the DERIVED DLQ url is the one genuine
        // "no DLQ" error (the naming-convention guess missed).
        let main_stats = match &main_url {
            Some(u) => match self.queue_stats(u).await {
                Ok(st) => Some(st),
                Err(e) => {
                    let text = format!("{e:#}");
                    if text.contains("NonExistentQueue") {
                        None
                    } else {
                        return Err(eyre!("main queue stats: {text}"));
                    }
                }
            },
            None => None,
        };
        let dlq_stats = match &dlq_url {
            Some(u) => match self.queue_stats(u).await {
                Ok(st) => Some(st),
                Err(e) => {
                    let text = format!("{e:#}");
                    if text.contains("NonExistentQueue") {
                        None
                    } else {
                        return Err(eyre!("dlq stats: {text}"));
                    }
                }
            },
            None => None,
        };

        Ok(WorkerQueues {
            main_url,
            dlq_url,
            main_stats,
            dlq_stats,
        })
    }

    /// Fetch the current env vars for an environment from
    /// `DescribeConfigurationSettings` filtered to the
    /// `aws:elasticbeanstalk:application:environment` namespace. Returns
    /// sorted `(KEY, VALUE)` pairs.
    /// Fetch every option setting for a live env. Used by the modal-form
    /// pre-fill: callers filter the result down to the `(namespace, option_name)`
    /// pairs their form cares about. Returns `(namespace, option_name, value)`
    /// triples.
    pub async fn fetch_env_option_settings(
        &self,
        application_name: &str,
        env_name: &str,
    ) -> Result<Vec<(String, String, String)>> {
        let resp = self
            .client
            .describe_configuration_settings()
            .application_name(application_name)
            .environment_name(env_name)
            .send()
            .await
            .wrap_err("DescribeConfigurationSettings(env) failed")?;
        let out = resp
            .configuration_settings
            .unwrap_or_default()
            .into_iter()
            .flat_map(|c| c.option_settings.unwrap_or_default())
            .map(|o| {
                (
                    o.namespace.unwrap_or_default(),
                    o.option_name.unwrap_or_default(),
                    o.value.unwrap_or_default(),
                )
            })
            .collect();
        Ok(out)
    }

    /// Pull the env's VPC id plus the currently-selected subnet and
    /// security-group IDs from EB option settings in a single round-trip.
    /// `:subnets` and `:security-groups` both call this — VPC id drives
    /// the subsequent EC2 list call, the existing selections drive the
    /// MultiSelect pre-fill.
    pub async fn fetch_env_vpc_context(
        &self,
        application_name: &str,
        env_name: &str,
    ) -> Result<EnvVpcContext> {
        let resp = self
            .client
            .describe_configuration_settings()
            .application_name(application_name)
            .environment_name(env_name)
            .send()
            .await
            .wrap_err("DescribeConfigurationSettings(env) failed")?;
        let mut ctx = EnvVpcContext::default();
        for setting in resp.configuration_settings.unwrap_or_default() {
            for opt in setting.option_settings.unwrap_or_default() {
                let ns = opt.namespace.unwrap_or_default();
                let name = opt.option_name.unwrap_or_default();
                let value = opt.value.unwrap_or_default();
                match (ns.as_str(), name.as_str()) {
                    ("aws:ec2:vpc", "VPCId") if !value.is_empty() => {
                        ctx.vpc_id = Some(value);
                    }
                    ("aws:ec2:vpc", "Subnets") if !value.is_empty() => {
                        ctx.subnets = crate::util::split_csv(&value);
                    }
                    ("aws:ec2:vpc", "ELBSubnets") if !value.is_empty() => {
                        ctx.elb_subnets = crate::util::split_csv(&value);
                    }
                    ("aws:autoscaling:launchconfiguration", "SecurityGroups")
                        if !value.is_empty() =>
                    {
                        ctx.security_groups = crate::util::split_csv(&value);
                    }
                    _ => {}
                }
            }
        }
        Ok(ctx)
    }

    /// Fetch RDS dbinstance option settings for an env. EB envs
    /// optionally have an attached RDS instance (via
    /// `aws:rds:dbinstance.*` option settings + auto-managed
    /// security group); this returns the configured settings as
    /// `(option_name, value)` pairs sorted alphabetically.
    ///
    /// Empty result = no RDS attached. Caller should distinguish
    /// "no RDS" from "fetch failed" via the Result type.
    pub async fn fetch_env_rds_config(
        &self,
        application_name: &str,
        env_name: &str,
    ) -> Result<Vec<(String, String)>> {
        let resp = self
            .client
            .describe_configuration_settings()
            .application_name(application_name)
            .environment_name(env_name)
            .send()
            .await
            .wrap_err("DescribeConfigurationSettings(rds) failed")?;
        let mut out: Vec<(String, String)> = resp
            .configuration_settings
            .unwrap_or_default()
            .into_iter()
            .flat_map(|c| c.option_settings.unwrap_or_default())
            .filter_map(|o| {
                let ns = o.namespace?;
                if ns != "aws:rds:dbinstance" {
                    return None;
                }
                let opt = o.option_name?;
                let value = o.value.unwrap_or_default();
                if value.is_empty() {
                    return None;
                }
                Some((opt, value))
            })
            .collect();
        out.sort();
        Ok(out)
    }

    /// Fetch every settable EB option for an env — namespace, name,
    /// current value (when set), default, type, constraints.
    ///
    /// Two SDK calls correlated by (namespace, name):
    ///
    ///   - `describe_configuration_options` is the canonical
    ///     "what's the full config vocabulary for this env's
    ///     platform?" API. Returns ~hundreds of option metadata
    ///     rows (default value, value type, change severity,
    ///     constraints) — but no current values.
    ///   - `describe_configuration_settings` returns the current
    ///     values for *every* option, including ones still at
    ///     their default.
    ///
    /// Merged on namespace+name so each row carries both the
    /// metadata and the live value. This is what closes the
    /// operator's "how do I know what I can set?" question.
    /// Caller should treat as on-demand (run via `:options`), not
    /// part of the background refresh — both calls are slow for
    /// platforms with deep option trees.
    pub async fn fetch_env_configuration_options(
        &self,
        application_name: &str,
        env_name: &str,
    ) -> Result<Vec<ConfigOption>> {
        // Parallel fetch of both shapes. The vocabulary call is
        // the slower of the two, so kicking them off together
        // shaves a round-trip off the total latency.
        let vocab_fut = self
            .client
            .describe_configuration_options()
            .environment_name(env_name)
            .send();
        let settings_fut = self
            .client
            .describe_configuration_settings()
            .application_name(application_name)
            .environment_name(env_name)
            .send();
        let (vocab_resp, settings_resp) = tokio::try_join!(
            async {
                vocab_fut
                    .await
                    .wrap_err("DescribeConfigurationOptions failed")
            },
            async {
                settings_fut
                    .await
                    .wrap_err("DescribeConfigurationSettings(options) failed")
            },
        )?;

        // Index current values by (namespace, name).
        let mut current: std::collections::HashMap<(String, String), String> =
            std::collections::HashMap::new();
        for c in settings_resp.configuration_settings.unwrap_or_default() {
            for o in c.option_settings.unwrap_or_default() {
                if let (Some(ns), Some(name)) = (o.namespace, o.option_name) {
                    if let Some(v) = o.value {
                        if !v.is_empty() {
                            current.insert((ns, name), v);
                        }
                    }
                }
            }
        }

        let mut out: Vec<ConfigOption> = vocab_resp
            .options
            .unwrap_or_default()
            .into_iter()
            .filter_map(|o| {
                let namespace = o.namespace?;
                let name = o.name?;
                let value = current.get(&(namespace.clone(), name.clone())).cloned();
                Some(ConfigOption {
                    namespace,
                    name,
                    value,
                    default_value: o.default_value,
                    value_type: o
                        .value_type
                        .map(|v| v.as_str().to_string())
                        .unwrap_or_default(),
                    value_options: o.value_options.unwrap_or_default(),
                    change_severity: o.change_severity,
                    user_defined: o.user_defined,
                    min_value: o.min_value,
                    max_value: o.max_value,
                    max_length: o.max_length,
                })
            })
            .collect();
        // Sort: namespace asc, user-set first within each namespace,
        // then alpha by name. Puts the operator's mutations at the
        // top of each group where they catch the eye.
        out.sort_by(|a, b| {
            let a_set = a.value.is_some();
            let b_set = b.value.is_some();
            a.namespace
                .cmp(&b.namespace)
                .then_with(|| b_set.cmp(&a_set))
                .then_with(|| a.name.cmp(&b.name))
        });
        Ok(out)
    }

    /// Fetch ALB listener option settings for an env. EB stores
    /// listener config in `aws:elbv2:listener:<PORT>` namespaces (one
    /// per listener; `default` is the port-80 HTTP listener, `443`
    /// is the typical HTTPS one). Returns a Vec of
    /// `(port_or_default, option_name, value)` rows so the renderer
    /// can group by port.
    ///
    /// Result is empty when the env doesn't use an ALB (Classic LB
    /// or worker tier) — caller should distinguish from "no config"
    /// by checking the env's tier first.
    pub async fn fetch_env_listeners(
        &self,
        application_name: &str,
        env_name: &str,
    ) -> Result<Vec<(String, String, String)>> {
        let resp = self
            .client
            .describe_configuration_settings()
            .application_name(application_name)
            .environment_name(env_name)
            .send()
            .await
            .wrap_err("DescribeConfigurationSettings(listeners) failed")?;
        let mut out: Vec<(String, String, String)> = resp
            .configuration_settings
            .unwrap_or_default()
            .into_iter()
            .flat_map(|c| c.option_settings.unwrap_or_default())
            .filter_map(|o| {
                let ns = o.namespace?;
                // Listener namespaces look like
                // `aws:elbv2:listener:default` / `aws:elbv2:listener:443`.
                // Strip the prefix to get the port (or "default").
                let port = ns.strip_prefix("aws:elbv2:listener:")?.to_string();
                let opt = o.option_name?;
                let value = o.value.unwrap_or_default();
                // Skip empty values — EB returns every settable key
                // even when unset, and an empty cert ARN / rule
                // list isn't worth showing.
                if value.is_empty() {
                    return None;
                }
                Some((port, opt, value))
            })
            .collect();
        // Sort: 'default' (port 80) first, then numeric ports asc,
        // then alpha by option name within each listener.
        out.sort_by(|a, b| {
            let rank_a = u8::from(a.0 != "default");
            let rank_b = u8::from(b.0 != "default");
            let port_a = a.0.parse::<u32>().unwrap_or(0);
            let port_b = b.0.parse::<u32>().unwrap_or(0);
            (rank_a, port_a, &a.1).cmp(&(rank_b, port_b, &b.1))
        });
        Ok(out)
    }

    pub async fn fetch_env_vars(
        &self,
        application_name: &str,
        env_name: &str,
    ) -> Result<Vec<(String, String)>> {
        let resp = self
            .client
            .describe_configuration_settings()
            .application_name(application_name)
            .environment_name(env_name)
            .send()
            .await
            .wrap_err("DescribeConfigurationSettings(env) failed")?;
        let mut out: Vec<(String, String)> = resp
            .configuration_settings
            .unwrap_or_default()
            .into_iter()
            .flat_map(|c| c.option_settings.unwrap_or_default())
            .filter(|o| {
                o.namespace.as_deref() == Some("aws:elasticbeanstalk:application:environment")
            })
            .map(|o| {
                (
                    o.option_name.unwrap_or_default(),
                    o.value.unwrap_or_default(),
                )
            })
            .collect();
        out.sort();
        Ok(out)
    }

    /// Update an env's option settings — `to_set` is `(namespace, option_name,
    /// value)` triples to add or overwrite; `to_remove` is `(namespace,
    /// option_name)` pairs to clear back to defaults. EB applies the change
    /// as a rolling update (or instantly for non-disruptive options).
    pub async fn update_env_option_settings(
        &self,
        env_name: &str,
        to_set: &[(String, String, String)],
        to_remove: &[(String, String)],
    ) -> Result<()> {
        use aws_sdk_elasticbeanstalk::types::{ConfigurationOptionSetting, OptionSpecification};
        if to_set.is_empty() && to_remove.is_empty() {
            return Err(eyre!("update_env_option_settings: nothing to do"));
        }
        let mut req = self.client.update_environment().environment_name(env_name);
        for (ns, name, value) in to_set {
            req = req.option_settings(
                ConfigurationOptionSetting::builder()
                    .namespace(ns)
                    .option_name(name)
                    .value(value)
                    .build(),
            );
        }
        for (ns, name) in to_remove {
            req = req.options_to_remove(
                OptionSpecification::builder()
                    .namespace(ns)
                    .option_name(name)
                    .build(),
            );
        }
        req.send()
            .await
            .wrap_err("UpdateEnvironment(option_settings) failed")?;
        Ok(())
    }

    pub async fn list_tags(&self, resource_arn: &str) -> Result<Vec<(String, String)>> {
        let resp = self
            .client
            .list_tags_for_resource()
            .resource_arn(resource_arn)
            .send()
            .await?;
        let tags = resp
            .resource_tags
            .unwrap_or_default()
            .into_iter()
            .filter_map(|t| match (t.key, t.value) {
                (Some(k), Some(v)) => Some((k, v)),
                _ => None,
            })
            .collect();
        Ok(tags)
    }

    /// UpdateTagsForResource — add/update tags listed in `to_add` and remove
    /// keys listed in `to_remove`. Empty lists are allowed but at least one
    /// side must be non-empty (the API rejects no-op calls).
    pub async fn update_tags(
        &self,
        resource_arn: &str,
        to_add: &[(String, String)],
        to_remove: &[String],
    ) -> Result<()> {
        use aws_sdk_elasticbeanstalk::types::Tag;
        let mut req = self
            .client
            .update_tags_for_resource()
            .resource_arn(resource_arn);
        for (k, v) in to_add {
            req = req.tags_to_add(Tag::builder().key(k).value(v).build());
        }
        for k in to_remove {
            req = req.tags_to_remove(k);
        }
        req.send().await?;
        Ok(())
    }

    pub async fn rebuild_env(&self, env_name: &str) -> Result<()> {
        self.client
            .rebuild_environment()
            .environment_name(env_name)
            .send()
            .await?;
        Ok(())
    }

    pub async fn restart_app_server(&self, env_name: &str) -> Result<()> {
        self.client
            .restart_app_server()
            .environment_name(env_name)
            .send()
            .await?;
        Ok(())
    }

    pub async fn swap_cnames(&self, source: &str, dest: &str) -> Result<()> {
        self.client
            .swap_environment_cnames()
            .source_environment_name(source)
            .destination_environment_name(dest)
            .send()
            .await?;
        Ok(())
    }

    /// Snapshot an env's current configuration as a named template under the
    /// same application. Idempotent for the user — if a template with the
    /// same name already exists, the API returns an error which we surface.
    pub async fn create_config_template(
        &self,
        application_name: &str,
        template_name: &str,
        source_env_name: &str,
    ) -> Result<()> {
        self.client
            .create_configuration_template()
            .application_name(application_name)
            .template_name(template_name)
            .environment_id(source_env_name)
            .send()
            .await
            .wrap_err("CreateConfigurationTemplate failed")?;
        Ok(())
    }

    /// Delete a configuration template by name. AWS will refuse if the
    /// template is currently in use; we pass the error back unchanged.
    pub async fn delete_config_template(
        &self,
        application_name: &str,
        template_name: &str,
    ) -> Result<()> {
        self.client
            .delete_configuration_template()
            .application_name(application_name)
            .template_name(template_name)
            .send()
            .await
            .wrap_err("DeleteConfigurationTemplate failed")?;
        Ok(())
    }

    /// List the newer platform versions in the same branch family as the
    /// env's current platform. Filtered server-side to `Ready` platforms;
    /// branch matching is best-effort using the current ARN's branch suffix
    /// (e.g. `Tomcat 9 with Corretto 17`). Sorted newest version first.
    pub async fn list_compatible_platforms(&self, env_name: &str) -> Result<Vec<CustomPlatform>> {
        use aws_sdk_elasticbeanstalk::types::{PlatformFilter, PlatformStatus};
        // Read the env's current platform ARN.
        let desc = self
            .client
            .describe_environments()
            .environment_names(env_name)
            .send()
            .await
            .wrap_err("DescribeEnvironments failed")?;
        let env = desc
            .environments
            .unwrap_or_default()
            .into_iter()
            .next()
            .ok_or_else(|| eyre!("env '{env_name}' not found"))?;
        let current_arn = env.platform_arn.clone().unwrap_or_default();
        let stack_or_arn = env
            .solution_stack_name
            .clone()
            .unwrap_or_else(|| current_arn.clone());
        let branch = platform_branch_from(&stack_or_arn);
        let owner_filter = PlatformFilter::builder()
            .r#type("PlatformStatus")
            .operator("=")
            .values(PlatformStatus::Ready.as_str())
            .build();
        let mut filters = vec![owner_filter];
        if !branch.is_empty() {
            filters.push(
                PlatformFilter::builder()
                    .r#type("PlatformBranchName")
                    // begins_with: `branch` is the bare family when
                    // derived from a solution-stack name, the full
                    // branch when derived from an ARN — both prefix
                    // the real PlatformBranchName.
                    .operator("begins_with")
                    .values(branch.clone())
                    .build(),
            );
        }
        let (this, fs) = (self, &filters);
        let raw = super::paginate("ListPlatformVersions", move |token| async move {
            let mut req = this.client.list_platform_versions();
            for f in fs {
                req = req.filters(f.clone());
            }
            if let Some(t) = token {
                req = req.next_token(t);
            }
            let resp = req.send().await.wrap_err("ListPlatformVersions failed")?;
            Ok((
                resp.platform_summary_list.unwrap_or_default(),
                resp.next_token,
            ))
        })
        .await?
        // Feeds the platform-upgrade picker: a short list reads as
        // "that platform version isn't available for this env".
        .complete("ListPlatformVersions")?;
        let mut out: Vec<CustomPlatform> = raw.into_iter().map(map_platform).collect();
        // Sort newest-first by semver-ish version.
        out.sort_by(|a, b| crate::util::compare_versions(&b.version, &a.version));
        Ok(out)
    }

    /// Migrate the env to a new platform ARN via UpdateEnvironment. EB
    /// performs this as a rolling update; the API returns immediately and
    /// the event log carries progress.
    pub async fn upgrade_platform(&self, env_name: &str, platform_arn: &str) -> Result<()> {
        self.client
            .update_environment()
            .environment_name(env_name)
            .platform_arn(platform_arn)
            .send()
            .await
            .wrap_err("UpdateEnvironment(platform_arn) failed")?;
        Ok(())
    }

    /// Clone an env: snapshot the source's settings into a transient
    /// configuration template, spin up a new env from it, then clean the
    /// template up. The new env starts the usual EB launch process — the
    /// caller can monitor via DescribeEvents.
    pub async fn clone_env(&self, source_env_name: &str, target_env_name: &str) -> Result<()> {
        // Snapshot the source env's application + ID.
        let desc = self
            .client
            .describe_environments()
            .environment_names(source_env_name)
            .send()
            .await
            .wrap_err("DescribeEnvironments failed")?;
        let env = desc
            .environments
            .unwrap_or_default()
            .into_iter()
            .next()
            .ok_or_else(|| eyre!("source env '{source_env_name}' not found"))?;
        let application = env
            .application_name
            .ok_or_else(|| eyre!("source env has no application_name"))?;
        let env_id = env
            .environment_id
            .ok_or_else(|| eyre!("source env has no environment_id"))?;
        // Use a transient template name so we can clean it up even if the
        // create fails partway.
        let template = format!(
            "__ebman-clone-{}-{}",
            target_env_name,
            chrono::Utc::now().timestamp()
        );
        self.client
            .create_configuration_template()
            .application_name(&application)
            .template_name(&template)
            .environment_id(&env_id)
            .send()
            .await
            .wrap_err("CreateConfigurationTemplate failed")?;
        // Best-effort cleanup even if create_environment fails — we don't
        // want to leave debris.
        let create_result = self
            .client
            .create_environment()
            .application_name(&application)
            .environment_name(target_env_name)
            .template_name(&template)
            .send()
            .await;
        let _ = self
            .client
            .delete_configuration_template()
            .application_name(&application)
            .template_name(&template)
            .send()
            .await;
        create_result.wrap_err("CreateEnvironment failed")?;
        Ok(())
    }

    /// Set the env's `aws:autoscaling:asg:{MinSize,MaxSize}` so the ASG
    /// reaches `count` instances. Passing `Some(0)` is the "stop" pattern
    /// (no instances, env keeps its config). The API returns immediately;
    /// EB performs the scale as a rolling change.
    pub async fn scale_env(&self, env_name: &str, min: i32, max: i32) -> Result<()> {
        use aws_sdk_elasticbeanstalk::types::ConfigurationOptionSetting;
        let opts = vec![
            ConfigurationOptionSetting::builder()
                .namespace("aws:autoscaling:asg")
                .option_name("MinSize")
                .value(min.to_string())
                .build(),
            ConfigurationOptionSetting::builder()
                .namespace("aws:autoscaling:asg")
                .option_name("MaxSize")
                .value(max.to_string())
                .build(),
        ];
        self.client
            .update_environment()
            .environment_name(env_name)
            .set_option_settings(Some(opts))
            .send()
            .await
            .wrap_err("UpdateEnvironment(asg) failed")?;
        Ok(())
    }

    /// Stop an in-flight environment update. Useful to bail out of a hung
    /// deploy. No-op if EB sees no operation in progress.
    pub async fn abort_environment_update(&self, env_name: &str) -> Result<()> {
        self.client
            .abort_environment_update()
            .environment_name(env_name)
            .send()
            .await
            .wrap_err("AbortEnvironmentUpdate failed")?;
        Ok(())
    }

    /// List custom EB platforms in this account. Filters server-side via
    /// `PlatformOwner=self` so we only show platforms the caller built, not
    /// the AWS-managed ones. Returns the ARN, platform branch name, and
    /// lifecycle state per entry.
    pub async fn list_custom_platforms(&self) -> Result<Vec<CustomPlatform>> {
        use aws_sdk_elasticbeanstalk::types::PlatformFilter;
        let filter = PlatformFilter::builder()
            .r#type("PlatformOwner")
            .operator("=")
            .values("self")
            .build();
        let (this, f) = (self, &filter);
        let raw = super::paginate("ListPlatformVersions", move |token| async move {
            let mut req = this.client.list_platform_versions().filters(f.clone());
            if let Some(t) = token {
                req = req.next_token(t);
            }
            let resp = req.send().await.wrap_err("ListPlatformVersions failed")?;
            Ok((
                resp.platform_summary_list.unwrap_or_default(),
                resp.next_token,
            ))
        })
        .await?
        // `:custom-platform-delete` takes an ARN the operator copies
        // out of this list, so a short one reads as "not there".
        .complete("ListPlatformVersions")?;
        let out: Vec<CustomPlatform> = raw.into_iter().map(map_platform).collect();
        Ok(out)
    }

    /// The newest version-publish date across a custom platform's
    /// version ARNs, via per-version `DescribePlatformVersion` (the
    /// only API that carries dates — `ListPlatformVersions` doesn't).
    /// `None` when no version reported a date. Feeds EBL015.
    pub async fn latest_platform_version_date(
        &self,
        version_arns: &[String],
    ) -> Result<Option<DateTime<Utc>>> {
        let mut latest: Option<DateTime<Utc>> = None;
        for arn in version_arns {
            let resp = self
                .client
                .describe_platform_version()
                .platform_arn(arn)
                .send()
                .await
                .wrap_err("DescribePlatformVersion failed")?;
            let date = resp
                .platform_description
                .and_then(|d| d.date_created)
                .and_then(|t| DateTime::<Utc>::from_timestamp(t.secs(), t.subsec_nanos()));
            if let Some(d) = date {
                if latest.is_none_or(|l| d > l) {
                    latest = Some(d);
                }
            }
        }
        Ok(latest)
    }

    /// Delete a custom platform by ARN. EB returns success immediately even
    /// though the underlying AMI / EBS cleanup runs async. Will fail if any
    /// envs are still using the platform.
    pub async fn delete_custom_platform(&self, platform_arn: &str) -> Result<()> {
        self.client
            .delete_platform_version()
            .platform_arn(platform_arn)
            .send()
            .await
            .wrap_err("DeletePlatformVersion failed")?;
        Ok(())
    }

    /// List application versions for `application_name`, sorted newest-first
    /// by `date_created`. Each entry carries the version label and the
    /// optional description text shown in the EB console. Pages through
    /// `next_token` so orgs with hundreds of historical versions see
    /// everything in `:versions` and `:rollback` can find labels that
    /// fall past the first page.
    pub async fn list_application_versions(
        &self,
        application_name: &str,
    ) -> Result<Vec<AppVersion>> {
        let (this, app) = (self, application_name);
        let raw = super::paginate("DescribeApplicationVersions", move |token| async move {
            let mut req = this
                .client
                .describe_application_versions()
                .application_name(app);
            if let Some(t) = token {
                req = req.next_token(t);
            }
            let resp = req
                .send()
                .await
                .wrap_err("DescribeApplicationVersions failed")?;
            Ok((
                resp.application_versions.unwrap_or_default(),
                resp.next_token,
            ))
        })
        .await?
        // The MCP `deploy` write gates on `.any(|v| v.label == label)`
        // and otherwise tells the caller the version doesn't exist.
        .complete("DescribeApplicationVersions")?;
        let mut out: Vec<AppVersion> = Vec::new();
        for v in raw {
            out.push(AppVersion {
                label: v.version_label.unwrap_or_default(),
                description: v.description.unwrap_or_default(),
                created: v
                    .date_created
                    .and_then(|d| DateTime::from_timestamp(d.secs(), d.subsec_nanos())),
            });
        }
        out.sort_by_key(|v| std::cmp::Reverse(v.created));
        Ok(out)
    }

    /// Delete an application version by label. `delete_source_bundle = true`
    /// also removes the underlying `.zip` from S3 so the storage cost goes
    /// away. EB rejects the call if the version is currently deployed to any
    /// env — surfaced as `SourceBundleDeletionException` /
    /// `OperationInProgressException` in the error chain.
    pub async fn delete_application_version(
        &self,
        application_name: &str,
        version_label: &str,
        delete_source_bundle: bool,
    ) -> Result<()> {
        self.client
            .delete_application_version()
            .application_name(application_name)
            .version_label(version_label)
            .delete_source_bundle(delete_source_bundle)
            .send()
            .await
            .wrap_err("DeleteApplicationVersion failed")?;
        Ok(())
    }

    /// Deploy a specific application-version label to an existing env via
    /// Ask EB for its managed S3 bucket — same bucket EB uses for its own
    /// uploads. We push application bundles into a known prefix here so
    /// `CreateApplicationVersion` can reference an `S3Location`. EB
    /// auto-creates the bucket on first call; subsequent calls return the
    /// same name.
    pub async fn create_storage_location(&self) -> Result<String> {
        let resp = self
            .client
            .create_storage_location()
            .send()
            .await
            .wrap_err("CreateStorageLocation failed")?;
        resp.s3_bucket
            .ok_or_else(|| eyre!("CreateStorageLocation returned no S3Bucket"))
    }

    /// Register a new application version pointing at an S3 source bundle.
    /// `auto_create_app` is `false` because we only create versions for
    /// existing applications; the env's application is the source of truth.
    pub async fn create_app_version(
        &self,
        application_name: &str,
        version_label: &str,
        description: Option<&str>,
        s3_bucket: &str,
        s3_key: &str,
    ) -> Result<()> {
        use aws_sdk_elasticbeanstalk::types::S3Location;
        let source = S3Location::builder()
            .s3_bucket(s3_bucket)
            .s3_key(s3_key)
            .build();
        let mut req = self
            .client
            .create_application_version()
            .application_name(application_name)
            .version_label(version_label)
            .source_bundle(source)
            .auto_create_application(false);
        if let Some(d) = description {
            req = req.description(d);
        }
        req.send()
            .await
            .wrap_err("CreateApplicationVersion failed")?;
        Ok(())
    }

    /// `UpdateEnvironment(version_label)`. Returns immediately — the env
    /// will mutate in the background.
    pub async fn deploy_version(&self, env_name: &str, version_label: &str) -> Result<()> {
        self.client
            .update_environment()
            .environment_name(env_name)
            .version_label(version_label)
            .send()
            .await
            .wrap_err("UpdateEnvironment(version_label) failed")?;
        Ok(())
    }

    /// Fetch the option settings stored in a saved configuration template.
    /// Returns a sorted `(namespace, option_name, value)` vector — sort makes
    /// the overlay output stable and diffable across runs. Empty values are
    /// preserved (operators sometimes care that a setting is explicitly
    /// empty vs. unset; the call only returns settings the template actually
    /// defines, so "missing" already means "use platform default").
    pub async fn describe_template_settings(
        &self,
        application_name: &str,
        template_name: &str,
    ) -> Result<Vec<(String, String, String)>> {
        let resp = self
            .client
            .describe_configuration_settings()
            .application_name(application_name)
            .template_name(template_name)
            .send()
            .await
            .wrap_err("DescribeConfigurationSettings(template) failed")?;
        let mut out: Vec<(String, String, String)> = resp
            .configuration_settings
            .unwrap_or_default()
            .into_iter()
            .flat_map(|c| c.option_settings.unwrap_or_default())
            .map(|o| {
                (
                    o.namespace.unwrap_or_default(),
                    o.option_name.unwrap_or_default(),
                    o.value.unwrap_or_default(),
                )
            })
            .collect();
        out.sort();
        Ok(out)
    }

    /// Apply a saved configuration template to an existing env via
    /// `UpdateEnvironment(template_name)`. The env will start mutating in
    /// the background; surface the launch via the events panel.
    pub async fn apply_config_template(&self, env_name: &str, template_name: &str) -> Result<()> {
        self.client
            .update_environment()
            .environment_name(env_name)
            .template_name(template_name)
            .send()
            .await
            .wrap_err("UpdateEnvironment(template_name) failed")?;
        Ok(())
    }

    pub async fn terminate_env(&self, env_name: &str) -> Result<()> {
        self.client
            .terminate_environment()
            .environment_name(env_name)
            .send()
            .await?;
        Ok(())
    }

    /// Ask EB to start collecting the tail log for an env. Per-instance log
    /// snapshots become available via `retrieve_env_info` once each instance
    /// has uploaded its sample to S3 (usually 5-15 seconds).
    pub async fn request_env_info_tail(&self, env_name: &str) -> Result<()> {
        use aws_sdk_elasticbeanstalk::types::EnvironmentInfoType;
        self.client
            .request_environment_info()
            .environment_name(env_name)
            .info_type(EnvironmentInfoType::Tail)
            .send()
            .await
            .wrap_err("RequestEnvironmentInfo failed")?;
        Ok(())
    }

    /// Read whatever tail-log samples EB has on file for the env, mapped to
    /// pre-signed S3 URLs. Empty vec means no samples have been uploaded yet —
    /// poll again. Each entry is `(ec2_instance_id, pre_signed_url)`.
    pub async fn retrieve_env_info_tail(&self, env_name: &str) -> Result<Vec<(String, String)>> {
        use aws_sdk_elasticbeanstalk::types::EnvironmentInfoType;
        let resp = self
            .client
            .retrieve_environment_info()
            .environment_name(env_name)
            .info_type(EnvironmentInfoType::Tail)
            .send()
            .await
            .wrap_err("RetrieveEnvironmentInfo failed")?;
        let mut out = Vec::new();
        for info in resp.environment_info.unwrap_or_default() {
            if let (Some(id), Some(url)) = (info.ec2_instance_id, info.message) {
                out.push((id, url));
            }
        }
        Ok(out)
    }

    /// `DescribeEnvironmentHealth` summarised down to a `(healthy, total)`
    /// pair for the INST column on the main table. Lightweight compared to
    /// `DescribeInstancesHealth` (one call returns aggregated counts; no
    /// per-instance attributes). Fanned across every env on each refresh
    /// tick — typical accounts have ≤ 50 envs which is well under the
    /// EB API's per-second budget.
    pub async fn fetch_env_instance_counts(&self, env_name: &str) -> Result<EnvInstanceCounts> {
        let resp = self
            .client
            .describe_environment_health()
            .environment_name(env_name)
            .attribute_names(
                aws_sdk_elasticbeanstalk::types::EnvironmentHealthAttribute::InstancesHealth,
            )
            .send()
            .await
            .wrap_err("DescribeEnvironmentHealth failed")?;
        Ok(summarise_instance_health(resp.instances_health.as_ref()))
    }

    pub async fn list_instances(&self, env_name: &str) -> Result<Vec<Instance>> {
        // Paginated: this list is `:ssm-run`'s target set and
        // `spawn_dry_run`'s blast-radius count, so a truncated one means
        // the shell command silently never reaches the missing
        // instances while the overlay reports N/N success.
        let (this, env) = (self, env_name);
        let raw = super::paginate("DescribeInstancesHealth", move |token| async move {
            let mut req = this
                .client
                .describe_instances_health()
                .environment_name(env)
                .attribute_names(aws_sdk_elasticbeanstalk::types::InstancesHealthAttribute::All);
            if let Some(t) = token {
                req = req.next_token(t);
            }
            let resp = req
                .send()
                .await
                .wrap_err("DescribeInstancesHealth failed")?;
            Ok((
                resp.instance_health_list.unwrap_or_default(),
                resp.next_token,
            ))
        })
        .await?
        // This function's own comment says a truncated list means
        // `:ssm-run` silently misses instances while reporting N/N
        // success — so it must not hand one back.
        .complete("DescribeInstancesHealth")?;
        let instances = raw
            .into_iter()
            .map(|i| Instance {
                id: i.instance_id.unwrap_or_default(),
                health: i.health_status.unwrap_or_default(),
                color: i.color.unwrap_or_default(),
                causes: i.causes.unwrap_or_default(),
                instance_type: i.instance_type.unwrap_or_default(),
                availability_zone: i.availability_zone.unwrap_or_default(),
                launched_at: i
                    .launched_at
                    .and_then(|d| DateTime::from_timestamp(d.secs(), d.subsec_nanos())),
            })
            .collect();
        Ok(instances)
    }

    pub async fn list_applications(&self) -> Result<Vec<Application>> {
        let resp = self.client.describe_applications().send().await?;
        let apps = resp
            .applications
            .unwrap_or_default()
            .into_iter()
            .map(|a| Application {
                name: a.application_name.unwrap_or_default(),
                description: a.description.unwrap_or_default(),
                date_created: a
                    .date_created
                    .and_then(|d| DateTime::from_timestamp(d.secs(), d.subsec_nanos())),
                date_updated: a
                    .date_updated
                    .and_then(|d| DateTime::from_timestamp(d.secs(), d.subsec_nanos())),
                version_count: a.versions.map(|v| v.len()).unwrap_or(0),
                templates: a.configuration_templates.unwrap_or_default(),
                // Filled in by a follow-up `list_application_versions` fan-out.
                latest_version_label: None,
                latest_version_created: None,
            })
            .collect();
        Ok(apps)
    }

    pub async fn list_environments(&self) -> Result<Vec<Environment>> {
        let this = self;
        let raw = super::paginate("DescribeEnvironments", move |token| async move {
            let mut req = this.client.describe_environments().include_deleted(false);
            if let Some(t) = token {
                req = req.next_token(t);
            }
            let resp = req.send().await.wrap_err("DescribeEnvironments failed")?;
            Ok((resp.environments.unwrap_or_default(), resp.next_token))
        })
        .await?
        // Callers `.find()` by name and turn a miss into "env not found
        // in region X" — `spawn_rollout_preflight` halts a rollout on
        // it, the MCP tools refuse a write on it. A short list there is
        // a wrong answer, not a shorter one.
        .complete("DescribeEnvironments")?;
        Ok(raw.into_iter().map(map_env).collect())
    }

    /// Flat list of every solution-stack name available in this region
    /// (`ListAvailableSolutionStacks`). Drives the stale-platform check:
    /// an env whose stack has a lower version than the newest stack in
    /// the same family is flagged in the table.
    pub async fn list_solution_stacks(&self) -> Result<Vec<String>> {
        let resp = self
            .client
            .list_available_solution_stacks()
            .send()
            .await
            .wrap_err("ListAvailableSolutionStacks failed")?;
        Ok(resp.solution_stacks.unwrap_or_default())
    }
}