coralogix-cli 0.1.25

Coralogix CLI - the observability backbone for AI agents and engineering teams.
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
use std::sync::Arc;

use anyhow::{anyhow, bail, Context, Result};
use colored::Colorize;
use serde_json::{json, Value};
use toon_format::encode_default as toon_encode;

pub mod api;
mod legacy;

use api::{
    BoolFilter, CategoryType, FieldMatch, Filter, FilterDescriptor, GetResourcesResponse,
    HealthHistoryEntry, InfraApi, ListResourcesParams, Op, ResourceData, ResourceTypeMapping,
};

use crate::config::OutputFormat;
use crate::execution::{fan_out, report_errors_and_collect_successes, ExecutionTarget};
use crate::render;

/// JSON key for the source profile when merging multi-profile infra REST rows.
const JSON_KEY_PROFILE: &str = "profile";

#[derive(Debug, Clone, Copy)]
pub struct PageWindow {
    pub start_row: Option<i64>,
    pub end_row: Option<i64>,
}

// ── Subcommand runners ────────────────────────────────────────────────────────

/// `cx infra resources types` - list the available resource type mappings.
pub async fn run_types(targets: &[Arc<ExecutionTarget>], output: OutputFormat) -> Result<()> {
    eprintln!("{}", "Fetching available resource types...".dimmed());

    let include_profile = targets.len() > 1;

    let per_profile = fan_out(targets, |target| async move {
        let api = InfraApi::new(&target.client);
        Ok(api.available_types().await?)
    })
    .await;

    let mut merged: Vec<(String, ResourceTypeMapping)> = Vec::new();
    for (profile, resp) in report_errors_and_collect_successes(per_profile)? {
        for mapping in resp.resource_types {
            merged.push((profile.clone(), mapping));
        }
    }

    match output {
        OutputFormat::Json | OutputFormat::Toon => {
            let rows: Vec<Value> = merged
                .iter()
                .map(|(profile, m)| type_mapping_to_json(m, include_profile, profile))
                .collect();
            render_machine_rows(output, &rows)?;
        }
        OutputFormat::Text => {
            if merged.is_empty() {
                render::print_no_results("No resource types found.");
                return Ok(());
            }
            let rows: Vec<Vec<String>> = merged
                .iter()
                .map(|(profile, m)| {
                    vec![
                        profile.clone(),
                        display_or_dash(
                            m.category_type.as_ref().and_then(|c| c.category.as_deref()),
                        ),
                        display_or_dash(
                            m.category_type
                                .as_ref()
                                .and_then(|c| c.type_name.as_deref()),
                        ),
                        display_or_dash(m.label.as_deref()),
                    ]
                })
                .collect();
            render::render_table(&["Category", "Type", "Label"], rows, include_profile);
        }
    }

    Ok(())
}

pub async fn run_filters(
    targets: &[Arc<ExecutionTarget>],
    category: Option<&str>,
    resource_type: Option<&str>,
    output: OutputFormat,
) -> Result<()> {
    let category = category
        .map(|c| require_non_empty(c, "--category"))
        .transpose()?;
    let resource_type = resource_type
        .map(|t| require_non_empty(t, "--type"))
        .transpose()?;

    eprintln!("{}", "Fetching filterable attributes...".dimmed());

    let include_profile = targets.len() > 1;

    let per_profile = fan_out(targets, |target| async move {
        let api = InfraApi::new(&target.client);
        Ok(api.filters(category, resource_type).await?)
    })
    .await;

    let mut merged: Vec<(String, FilterDescriptor)> = Vec::new();
    for (profile, resp) in report_errors_and_collect_successes(per_profile)? {
        for descriptor in resp.filters {
            merged.push((profile.clone(), descriptor));
        }
    }

    match output {
        OutputFormat::Json | OutputFormat::Toon => {
            let rows: Vec<Value> = merged
                .iter()
                .map(|(profile, f)| filter_to_json(f, include_profile, profile))
                .collect();
            render_machine_rows(output, &rows)?;
        }
        OutputFormat::Text => {
            if merged.is_empty() {
                render::print_no_results("No filterable attributes found.");
                return Ok(());
            }
            let rows: Vec<Vec<String>> = merged
                .iter()
                .map(|(profile, f)| {
                    vec![
                        profile.clone(),
                        display_or_dash(f.name.as_deref()),
                        display_or_dash(f.kind.as_deref()),
                        if f.wildcard { "yes" } else { "no" }.to_string(),
                        join_or_dash(&f.values),
                        join_or_dash(&format_type_pairs(&f.types)),
                    ]
                })
                .collect();
            render::render_table(
                &["Attribute", "Kind", "Wildcard", "Values", "Types"],
                rows,
                include_profile,
            );
        }
    }

    Ok(())
}

/// `cx infra resources list` - list resources, narrowed by category, type or attribute.
pub async fn run_list(
    targets: &[Arc<ExecutionTarget>],
    category: Option<&str>,
    resource_type: Option<&str>,
    match_all: &[String],
    match_any: &[String],
    window: PageWindow,
    output: OutputFormat,
) -> Result<()> {
    let category = category
        .map(|c| require_non_empty(c, "--category"))
        .transpose()?;
    let resource_type = resource_type
        .map(|t| require_non_empty(t, "--type"))
        .transpose()?;
    let filter = build_filter(match_all, match_any)?;
    if category.is_none() && resource_type.is_none() && filter.is_none() {
        bail!(
            "nothing to narrow by; pass at least one of --category, --type, \
             --match-all or --match-any - `cx infra resources filters` lists \
             the attributes this tenant can filter on"
        );
    }
    window.validate()?;

    eprintln!("{}", "Fetching resources...".dimmed());

    let per_profile = fan_out(targets, |target| {
        let category = category.map(String::from);
        let resource_type = resource_type.map(String::from);
        let filter = &filter;
        async move {
            let api = InfraApi::new(&target.client);
            let params = ListResourcesParams {
                category: category.as_deref(),
                resource_type: resource_type.as_deref(),
                filter: filter.as_ref(),
                start_row: window.start_row,
                end_row: window.end_row,
            };
            Ok(api.list(&params).await?)
        }
    })
    .await;

    render_resources(
        per_profile,
        targets.len() > 1,
        resource_type.is_some(),
        output,
    )
}

/// `cx infra resources list` - the deprecated name and scope filters, which
/// still require a category and a type.
pub async fn run_list_legacy(
    targets: &[Arc<ExecutionTarget>],
    category: Option<&str>,
    resource_type: Option<&str>,
    name_filter: Option<&str>,
    scope: &[String],
    window: PageWindow,
    output: OutputFormat,
) -> Result<()> {
    let (Some(category), Some(resource_type)) = (category, resource_type) else {
        bail!("--name-filter and --scope require both --category and --type");
    };
    let category = require_non_empty(category, "--category")?;
    let resource_type = require_non_empty(resource_type, "--type")?;
    let name_filter = name_filter.map(str::trim).filter(|s| !s.is_empty());
    let scope_filters = legacy::parse_scope_filters(scope)?;
    window.validate()?;

    eprintln!("{}", "Fetching resources...".dimmed());

    let per_profile = fan_out(targets, |target| {
        let category = category.to_string();
        let resource_type = resource_type.to_string();
        let name_filter = name_filter.map(String::from);
        let scope_filters = scope_filters.clone();
        async move {
            let params = legacy::LegacyListParams {
                category: &category,
                resource_type: &resource_type,
                name_filter: name_filter.as_deref(),
                scope_filters: &scope_filters,
                start_row: window.start_row,
                end_row: window.end_row,
            };
            Ok(legacy::list(&target.client, &params).await?)
        }
    })
    .await;

    render_resources(per_profile, targets.len() > 1, true, output)
}

fn render_resources(
    per_profile: Vec<(String, Result<GetResourcesResponse>)>,
    include_profile: bool,
    type_pinned: bool,
    output: OutputFormat,
) -> Result<()> {
    let mut counts: Vec<ProfileCounts> = Vec::new();
    let mut merged: Vec<(String, ResourceData)> = Vec::new();
    for (profile, resp) in report_errors_and_collect_successes(per_profile)? {
        counts.push(ProfileCounts {
            profile: profile.clone(),
            total_count: resp.total_count,
            returned_count: resp.resources.len(),
        });
        for resource in resp.resources {
            merged.push((profile.clone(), resource));
        }
    }
    let total_count = aggregate_total(&counts);

    match output {
        OutputFormat::Json | OutputFormat::Toon => {
            let rows: Vec<Value> = merged
                .iter()
                .map(|(profile, r)| resource_to_json(r, include_profile, profile))
                .collect();
            let envelope = build_list_envelope(total_count, rows, &counts, include_profile);
            render_machine_envelope(output, &envelope)?;
        }
        OutputFormat::Text => {
            if merged.is_empty() {
                render::print_no_results("No resources found.");
                return Ok(());
            }
            let (headers, rows) = list_table(&merged);
            let header_refs: Vec<&str> = headers.iter().map(String::as_str).collect();
            render::render_table(&header_refs, rows, include_profile);
            eprintln!(
                "{}",
                format_count_summary(merged.len(), total_count, &counts, include_profile).dimmed()
            );
            if !type_pinned {
                eprintln!(
                    "{}",
                    "Columns are the union of the matched types; a blank cell means the resource \
                     does not carry that column. Narrow with --type for one type's set."
                        .dimmed()
                );
            }
        }
    }

    Ok(())
}

/// `cx infra resources health-history <resource-id>` - daily health status samples,
/// oldest first.
///
/// Single-profile by construction (see [`single_target`]), so this issues one
/// request and renders the response directly - no fan-out, no merge, and no
/// profile tagging.
pub async fn run_health_history(
    targets: &[Arc<ExecutionTarget>],
    resource_id: &str,
    output: OutputFormat,
) -> Result<()> {
    let resource_id = require_non_empty(resource_id, "resource id")?;
    let target = single_target(targets, "health-history")?;

    eprintln!(
        "{}",
        format!("Fetching health history for '{resource_id}'...").dimmed()
    );

    let resp = InfraApi::new(&target.client)
        .health_history(resource_id)
        .await
        .with_context(|| format!("profile '{}' failed", target.profile_name))?;
    let history = resp.health_history;

    match output {
        OutputFormat::Json | OutputFormat::Toon => {
            let rows: Vec<Value> = history.iter().map(health_entry_to_json).collect();
            render_machine_rows(output, &rows)?;
        }
        OutputFormat::Text => {
            if history.is_empty() {
                render::print_no_results("No health history found.");
                return Ok(());
            }
            let rows: Vec<Vec<String>> = history
                .iter()
                .map(|entry| {
                    vec![
                        target.profile_name.clone(),
                        display_or_dash(entry.timestamp.as_deref()),
                        display_or_dash(entry.status.as_deref()),
                    ]
                })
                .collect();
            render::render_table(&["Timestamp", "Status"], rows, false);
        }
    }

    Ok(())
}

/// `cx infra resources raw-data <resource-id>` - the raw resource document.
///
/// Single-profile by construction (see [`single_target`]), so this issues one
/// request and renders the response directly - no fan-out, no merge, and no
/// profile tagging.
pub async fn run_raw_data(
    targets: &[Arc<ExecutionTarget>],
    resource_id: &str,
    output: OutputFormat,
) -> Result<()> {
    let resource_id = require_non_empty(resource_id, "resource id")?;
    let target = single_target(targets, "raw-data")?;

    eprintln!(
        "{}",
        format!("Fetching raw resource data for '{resource_id}'...").dimmed()
    );

    let resp = InfraApi::new(&target.client)
        .raw_data(resource_id)
        .await
        .with_context(|| format!("profile '{}' failed", target.profile_name))?;

    // A 200 with null raw data means the document is cleanly missing, so note it
    // on stderr and render an empty result rather than failing.
    let results: Vec<Value> = match resp.raw_data {
        Some(doc) => vec![doc],
        None => {
            eprintln!("{}", "no raw data for this resource".yellow());
            Vec::new()
        }
    };

    match output {
        OutputFormat::Json => render::render_json_auto(&results)?,
        OutputFormat::Toon => render::render_toon(&results)?,
        OutputFormat::Text => {
            render::render_get_text(&results, false, "No raw data found.", None)?;
        }
    }

    Ok(())
}

// ── Helpers ───────────────────────────────────────────────────────────────────

/// Renders merged JSON rows for the two machine formats.
///
/// Every caller peels `OutputFormat::Text` off first and renders its own table,
/// so reaching here with `Text` is a bug in this module rather than bad input.
fn render_machine_rows(output: OutputFormat, rows: &[Value]) -> Result<()> {
    match output {
        OutputFormat::Json => render::render_json(rows),
        OutputFormat::Toon => render::render_toon(rows),
        OutputFormat::Text => {
            unreachable!("callers render text themselves; only Json/Toon reach here")
        }
    }
}

/// Per-profile row counts for one `list` invocation. `total_count` is the
/// profile's fleet-wide match count, independent of the page window.
struct ProfileCounts {
    profile: String,
    total_count: i64,
    returned_count: usize,
}

/// Sums the per-profile totals. Saturating: a fan-out across profiles whose
/// totals sum past `i64::MAX` should clamp rather than wrap into a negative.
fn aggregate_total(counts: &[ProfileCounts]) -> i64 {
    counts
        .iter()
        .fold(0i64, |acc, c| acc.saturating_add(c.total_count))
}

/// Builds the `list` result envelope.
///
/// `list` is the only infra subcommand that wraps its rows instead of emitting a
/// bare array, because `--start-row`/`--end-row` make the caller responsible for
/// paging and `total_count` is the only stop condition available to them. Fleets
/// can run to hundreds of thousands of resources, so the CLI deliberately does
/// not page on the caller's behalf - it just reports the total.
///
/// `total_count` counts every resource matching the query, not just the rows in
/// this window, so it is normally larger than `returned_count`.
///
/// Key order is meaningful: the counts precede `resources` so a consumer reading
/// a truncated stream still sees the stop condition before the row payload.
fn build_list_envelope(
    total_count: i64,
    rows: Vec<Value>,
    counts: &[ProfileCounts],
    include_profile: bool,
) -> Value {
    let mut envelope = serde_json::Map::new();
    envelope.insert("total_count".to_string(), json!(total_count));
    envelope.insert("returned_count".to_string(), json!(rows.len()));

    if include_profile {
        let per_profile: Vec<Value> = counts
            .iter()
            .map(|c| {
                json!({
                    JSON_KEY_PROFILE: c.profile,
                    "total_count": c.total_count,
                    "returned_count": c.returned_count,
                })
            })
            .collect();
        envelope.insert("counts_by_profile".to_string(), Value::Array(per_profile));
    }

    envelope.insert("resources".to_string(), Value::Array(rows));
    Value::Object(envelope)
}

/// Renders the `list` envelope for the two machine formats. `Text` is unreachable
/// for the same reason as in [`render_machine_rows`].
fn render_machine_envelope(output: OutputFormat, envelope: &Value) -> Result<()> {
    match output {
        OutputFormat::Json => render::render_json_auto(std::slice::from_ref(envelope)),
        OutputFormat::Toon => {
            let encoded =
                toon_encode(envelope).map_err(|e| anyhow!("TOON encoding failed: {e}"))?;
            println!("{encoded}");
            Ok(())
        }
        OutputFormat::Text => {
            unreachable!("callers render text themselves; only Json/Toon reach here")
        }
    }
}

/// Formats the dimmed stderr summary line under the text-mode table. When fanning
/// out, the per-profile lines show each profile's own returned-vs-total figures -
/// the window applies per profile, so each is paged against its own total, not
/// the sum.
fn format_count_summary(
    returned: usize,
    total: i64,
    counts: &[ProfileCounts],
    include_profile: bool,
) -> String {
    let mut out = format!("Showing {returned} of {total} total resources");

    if include_profile {
        for c in counts {
            out.push_str(&format!(
                "\n  {}: {} of {}",
                c.profile, c.returned_count, c.total_count
            ));
        }
    }

    out
}

/// Trims a required string input and rejects it when nothing remains, so an
/// empty `--category ""` fails fast instead of sending an empty query
/// parameter to the API.
fn require_non_empty<'v>(value: &'v str, field_name: &str) -> Result<&'v str> {
    let trimmed = value.trim();
    if trimmed.is_empty() {
        bail!("{field_name} must not be empty");
    }
    Ok(trimmed)
}

/// Resolves the single target the `resource_id` subcommands operate on.
///
/// Resource ids are scoped to a single team, so an id
/// resolved in one profile cannot exist in another.
/// Fanning out would query every profile with an id that only one of
/// them can answer, so refuse it outright.
fn single_target<'t>(
    targets: &'t [Arc<ExecutionTarget>],
    subcommand: &str,
) -> Result<&'t ExecutionTarget> {
    match targets {
        [target] => Ok(target),
        [] => bail!("no profile resolved for `cx infra resources {subcommand}`"),
        _ => bail!(
            "`cx infra resources {subcommand}` accepts a single profile, but {} were given; \
             a resource id is scoped to one team and cannot resolve in another profile. \
             Re-run once per profile with a single -p.",
            targets.len()
        ),
    }
}

/// Validates the `--start-row` / `--end-row` page window.
///
/// The API coerces a bad window rather than rejecting it: a negative `startRow`
/// is clamped to `0`, and a window whose end is at or before its start yields a
/// row count of `0`.
///
/// Deliberately not checked here: the service's ceiling on `startRow + rows`.
/// That is a server-side policy constant which the CLI should not mirror, and its
/// 400 already names the limit and how to get under it.
impl PageWindow {
    fn validate(self) -> Result<()> {
        let Self { start_row, end_row } = self;
        if let Some(start) = start_row {
            if start < 0 {
                bail!("--start-row must not be negative (got {start}); rows are 0-based");
            }
        }

        if let Some(end) = end_row {
            if end < 0 {
                bail!("--end-row must not be negative (got {end})");
            }
        }

        if let (Some(start), Some(end)) = (start_row, end_row) {
            if end <= start {
                bail!(
                    "--end-row ({end}) must be greater than --start-row ({start}); \
                     --end-row is exclusive, so this window selects no rows"
                );
            }
        }

        Ok(())
    }
}

fn build_filter(match_all: &[String], match_any: &[String]) -> Result<Option<Filter>> {
    let all = parse_matches(match_all, "--match-all")?;
    let any_matches = parse_matches(match_any, "--match-any")?;

    if let Some(field) = all.iter().map(|m| &m.field).find(|field| {
        any_matches
            .iter()
            .any(|m| m.field.eq_ignore_ascii_case(field))
    }) {
        bail!(
            "attribute '{field}' appears in both --match-all and --match-any; \
             an attribute belongs to one of them - require it with --match-all, \
             or make it one alternative with --match-any"
        );
    }

    let mut operands: Vec<Filter> = all
        .into_iter()
        .flat_map(|m| {
            let field = m.field;
            m.values.into_iter().map(move |value| {
                Filter::Match(FieldMatch {
                    field: field.clone(),
                    values: vec![value],
                })
            })
        })
        .collect();

    let any: Vec<Filter> = any_matches.into_iter().map(Filter::Match).collect();
    if any.len() == 1 {
        operands.extend(any);
    } else if !any.is_empty() {
        operands.push(Filter::Bool(BoolFilter {
            op: Op::Or,
            operands: any,
        }));
    }

    if operands.len() == 1 {
        return Ok(operands.pop());
    }
    Ok((!operands.is_empty()).then_some(Filter::Bool(BoolFilter {
        op: Op::And,
        operands,
    })))
}

fn parse_matches(raw: &[String], flag: &str) -> Result<Vec<FieldMatch>> {
    let mut matches: Vec<FieldMatch> = Vec::new();

    for entry in raw {
        let Some((field, values_raw)) = entry.split_once('=') else {
            bail!("invalid {flag} '{entry}': expected NAME=VALUE");
        };
        let field = field.trim();
        if field.is_empty() {
            bail!("invalid {flag} '{entry}': attribute name must not be empty");
        }
        let mut values: Vec<String> = Vec::new();
        for value in values_raw.split(',').map(str::trim) {
            if !value.is_empty() && !values.iter().any(|seen| seen == value) {
                values.push(value.to_string());
            }
        }
        if values.is_empty() {
            bail!("invalid {flag} '{entry}': value must not be empty");
        }
        if matches.iter().any(|m| m.field.eq_ignore_ascii_case(field)) {
            bail!(
                "{flag} attribute '{field}' given more than once; \
                 list its values on one flag instead - {flag} {field}=a,b"
            );
        }
        matches.push(FieldMatch {
            field: field.to_string(),
            values,
        });
    }

    Ok(matches)
}

fn filter_to_json(item: &FilterDescriptor, include_profile: bool, profile: &str) -> Value {
    let v = json!({
        "name": item.name,
        "kind": item.kind,
        "wildcard": item.wildcard,
        "values": item.values,
        "types": item
            .types
            .iter()
            .map(|t| json!({ "category": t.category, "type": t.type_name }))
            .collect::<Vec<Value>>(),
    });
    tag_profile(v, include_profile, profile)
}

fn format_type_pairs(types: &[CategoryType]) -> Vec<String> {
    types
        .iter()
        .map(|t| {
            format!(
                "{}/{}",
                display_or_dash(t.category.as_deref()),
                display_or_dash(t.type_name.as_deref())
            )
        })
        .collect()
}

fn join_or_dash(values: &[String]) -> String {
    if values.is_empty() {
        "-".to_string()
    } else {
        values.join(", ")
    }
}

/// Builds one resource row as JSON for `json` / `toon` output after fan-out.
fn resource_to_json(item: &ResourceData, include_profile: bool, profile: &str) -> Value {
    let v = json!({
        "resource_id": item.resource_id,
        "name": item.name,
        "category": item.category,
        "type": item.type_name,
        "columns": item.columns,
    });
    tag_profile(v, include_profile, profile)
}

/// Injects the profile key into a JSON row when `include_profile` is true
/// (multiple `--profile`), so merged arrays stay attributable per account;
/// text mode uses a separate table path.
fn tag_profile(mut v: Value, include_profile: bool, profile: &str) -> Value {
    if include_profile {
        if let Value::Object(ref mut m) = v {
            m.insert(
                JSON_KEY_PROFILE.to_string(),
                Value::String(profile.to_string()),
            );
        }
    }
    v
}

/// Builds one health-history row as JSON for `json` / `toon` output.
///
/// No profile tagging: `health-history` runs against a single profile, so there
/// is nothing to disambiguate.
fn health_entry_to_json(item: &HealthHistoryEntry) -> Value {
    json!({
        "timestamp": item.timestamp,
        "status": item.status,
    })
}

/// Builds one resource-type row as JSON for `json` / `toon` output after fan-out.
fn type_mapping_to_json(item: &ResourceTypeMapping, include_profile: bool, profile: &str) -> Value {
    let v = json!({
        "category": item.category_type.as_ref().and_then(|c| c.category.clone()),
        "type": item.category_type.as_ref().and_then(|c| c.type_name.clone()),
        "label": item.label,
    });
    tag_profile(v, include_profile, profile)
}

fn display_or_dash(value: Option<&str>) -> String {
    value.filter(|s| !s.is_empty()).unwrap_or("-").to_string()
}

fn list_table(merged: &[(String, ResourceData)]) -> (Vec<String>, Vec<Vec<String>>) {
    let resources: Vec<&ResourceData> = merged.iter().map(|(_, r)| r).collect();
    let columns = union_of_columns(&resources);

    let headers: Vec<String> = ["Resource ID", "Name", "Category", "Type"]
        .into_iter()
        .map(String::from)
        .chain(columns.iter().cloned())
        .collect();

    let rows: Vec<Vec<String>> = merged
        .iter()
        .map(|(profile, r)| {
            let mut row = vec![
                profile.clone(),
                display_or_dash(r.resource_id.as_deref()),
                display_or_dash(display_name(r)),
                display_or_dash(r.category.as_deref()),
                display_or_dash(r.type_name.as_deref()),
            ];
            row.extend(
                columns
                    .iter()
                    .map(|column| r.columns.get(column).cloned().unwrap_or_default()),
            );
            row
        })
        .collect();

    (headers, rows)
}

fn union_of_columns(resources: &[&ResourceData]) -> Vec<String> {
    let mut columns: Vec<String> = Vec::new();
    for resource in resources {
        for name in resource.columns.keys() {
            if !name.eq_ignore_ascii_case("name") && !columns.contains(name) {
                columns.push(name.clone());
            }
        }
    }
    columns
}

/// The name the API matches `--name-filter` against.
///
/// The `name` field is an internal identifier, while the `Name` column holds the display name
/// that `nameFilter` actually searches. Falls back to `name` when the column is absent.
fn display_name(item: &ResourceData) -> Option<&str> {
    item.columns
        .iter()
        .find(|(key, _)| key.eq_ignore_ascii_case("name"))
        .map(|(_, value)| value.as_str())
        .filter(|s| !s.is_empty())
        .or(item.name.as_deref())
}

// ── Tests ──────────────────────────────────────────────────────────────────────

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

    #[test]
    fn require_non_empty_trims_and_accepts_values() {
        assert_eq!(require_non_empty(" Hosts ", "--category").unwrap(), "Hosts");
    }

    #[test]
    fn require_non_empty_rejects_empty_and_whitespace() {
        let err = require_non_empty("", "--category").unwrap_err();
        assert!(err.to_string().contains("--category must not be empty"));

        let err = require_non_empty("   ", "resource id").unwrap_err();
        assert!(err.to_string().contains("resource id must not be empty"));
    }

    #[test]
    fn parse_matches_reads_one_attribute_and_one_value() {
        let matches = parse_matches(&["Region=eu-west-1".to_string()], "--match-all").unwrap();
        assert_eq!(
            matches,
            vec![FieldMatch {
                field: "Region".to_string(),
                values: vec!["eu-west-1".to_string()],
            }]
        );
    }

    #[test]
    fn parse_matches_splits_values_on_commas() {
        let matches =
            parse_matches(&["Region=eu-west-1,us-east-1".to_string()], "--match-all").unwrap();
        assert_eq!(matches[0].values, vec!["eu-west-1", "us-east-1"]);
    }

    #[test]
    fn parse_matches_dedupes_repeated_values_in_one_list() {
        let matches = parse_matches(
            &["Region=eu-west-1,us-east-1,eu-west-1".to_string()],
            "--match-all",
        )
        .unwrap();
        assert_eq!(matches[0].values, vec!["eu-west-1", "us-east-1"]);
    }

    #[test]
    fn parse_matches_trims_whitespace_around_both_sides() {
        let matches = parse_matches(
            &[" Region = eu-west-1 , us-east-1 ".to_string()],
            "--match-all",
        )
        .unwrap();
        assert_eq!(matches[0].field, "Region");
        assert_eq!(matches[0].values, vec!["eu-west-1", "us-east-1"]);
    }

    #[test]
    fn parse_matches_keeps_a_value_containing_an_equals() {
        let matches = parse_matches(&["Tag=env=prod".to_string()], "--match-all").unwrap();
        assert_eq!(matches[0].values, vec!["env=prod"]);
    }

    #[test]
    fn parse_matches_rejects_a_missing_equals() {
        let err = parse_matches(&["Region".to_string()], "--match-all").unwrap_err();
        assert!(err.to_string().contains("expected NAME=VALUE"));
    }

    #[test]
    fn parse_matches_rejects_an_empty_attribute_name() {
        let err = parse_matches(&["=eu-west-1".to_string()], "--match-all").unwrap_err();
        assert!(err.to_string().contains("must not be empty"));
    }

    #[test]
    fn parse_matches_rejects_an_empty_value() {
        for entry in ["Region=", "Region=,", "Region= , "] {
            let err = parse_matches(&[entry.to_string()], "--match-all").unwrap_err();
            assert!(
                err.to_string().contains("value must not be empty"),
                "{entry} should be refused"
            );
        }
    }

    #[test]
    fn parse_matches_rejects_a_repeated_attribute() {
        let err = parse_matches(
            &[
                "Region=eu-west-1".to_string(),
                "Region=us-east-1".to_string(),
            ],
            "--match-all",
        )
        .unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("'Region' given more than once"), "got: {msg}");
        assert!(msg.contains("--match-all Region=a,b"), "got: {msg}");
    }

    #[test]
    fn parse_matches_detects_a_repeat_whatever_its_case() {
        let err = parse_matches(
            &[
                "Region=eu-west-1".to_string(),
                "region=us-east-1".to_string(),
            ],
            "--match-any",
        )
        .unwrap_err();
        assert!(err.to_string().contains("given more than once"));
    }

    #[test]
    fn parse_matches_names_the_flag_it_was_given() {
        let err = parse_matches(&["Region".to_string()], "--match-any").unwrap_err();
        assert!(err.to_string().contains("--match-any"));
    }

    #[test]
    fn parse_matches_empty_input_yields_no_matches() {
        assert!(parse_matches(&[], "--match-all").unwrap().is_empty());
    }

    #[test]
    fn build_filter_is_absent_without_either_flag() {
        assert_eq!(build_filter(&[], &[]).unwrap(), None);
    }

    #[test]
    fn build_filter_collapses_a_single_attribute() {
        let filter = build_filter(&["Health=critical".to_string()], &[])
            .unwrap()
            .unwrap();
        assert_eq!(
            filter,
            Filter::Match(FieldMatch {
                field: "Health".to_string(),
                values: vec!["critical".to_string()],
            })
        );
    }

    #[test]
    fn build_filter_collapses_a_single_match_any() {
        let filter = build_filter(&[], &["Health=critical".to_string()])
            .unwrap()
            .unwrap();
        assert!(matches!(filter, Filter::Match(_)), "{filter:?}");
    }

    #[test]
    fn build_filter_ands_every_match_all() {
        let filter = build_filter(
            &[
                "Region=eu-west-1".to_string(),
                "Health=critical".to_string(),
            ],
            &[],
        )
        .unwrap()
        .unwrap();
        let Filter::Bool(BoolFilter { op, operands }) = filter else {
            panic!("expected a bool");
        };
        assert_eq!(op, Op::And);
        assert_eq!(operands.len(), 2);
        assert!(operands.iter().all(|o| matches!(o, Filter::Match(_))));
    }

    #[test]
    fn build_filter_ors_every_match_any() {
        let filter = build_filter(
            &[],
            &[
                "Name=coredns".to_string(),
                "Namespace=kube-system".to_string(),
            ],
        )
        .unwrap()
        .unwrap();
        let Filter::Bool(BoolFilter { op, operands }) = filter else {
            panic!("expected a bool");
        };
        assert_eq!(op, Op::Or);
        assert_eq!(operands.len(), 2);
    }

    #[test]
    fn build_filter_nests_the_or_group_inside_the_and() {
        let filter = build_filter(
            &["OS=Linux".to_string()],
            &[
                "Health=critical".to_string(),
                "Region=eu-west-1".to_string(),
            ],
        )
        .unwrap()
        .unwrap();

        let Filter::Bool(BoolFilter { op, operands }) = filter else {
            panic!("expected a bool");
        };
        assert_eq!(op, Op::And);
        assert_eq!(operands.len(), 2);

        assert_eq!(
            operands[0],
            Filter::Match(FieldMatch {
                field: "OS".to_string(),
                values: vec!["Linux".to_string()],
            })
        );
        let Filter::Bool(BoolFilter {
            op: inner_op,
            operands: inner,
        }) = &operands[1]
        else {
            panic!("expected the second operand to be the OR group");
        };
        assert_eq!(*inner_op, Op::Or);
        assert_eq!(inner.len(), 2);
    }

    /// Across the groups this ANDs two nodes on one field, which either matches
    /// nothing or quietly collapses to the `--match-all` value alone.
    #[test]
    fn build_filter_refuses_one_attribute_in_both_groups() {
        let err = build_filter(
            &["Region=eu-west-1".to_string()],
            &["Region=us-east-1".to_string()],
        )
        .unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("'Region' appears in both"), "got: {msg}");
        assert!(
            msg.contains("--match-all") && msg.contains("--match-any"),
            "got: {msg}"
        );
    }

    #[test]
    fn build_filter_detects_a_cross_group_repeat_whatever_its_case() {
        let err = build_filter(
            &["Region=eu-west-1".to_string()],
            &["region=us-east-1".to_string()],
        )
        .unwrap_err();
        assert!(err.to_string().contains("appears in both"));
    }

    #[test]
    fn build_filter_ands_the_values_of_one_match_all() {
        let filter = build_filter(&["Tag=a,b".to_string()], &[])
            .unwrap()
            .unwrap();
        let Filter::Bool(BoolFilter { op, operands }) = filter else {
            panic!("expected a bool");
        };
        assert_eq!(op, Op::And);
        assert_eq!(
            operands,
            vec![
                Filter::Match(FieldMatch {
                    field: "Tag".to_string(),
                    values: vec!["a".to_string()],
                }),
                Filter::Match(FieldMatch {
                    field: "Tag".to_string(),
                    values: vec!["b".to_string()],
                }),
            ]
        );
    }

    #[test]
    fn build_filter_ors_the_values_of_one_match_any() {
        let filter = build_filter(&[], &["Tag=a,b".to_string()])
            .unwrap()
            .unwrap();
        assert_eq!(
            filter,
            Filter::Match(FieldMatch {
                field: "Tag".to_string(),
                values: vec!["a".to_string(), "b".to_string()],
            })
        );
    }

    #[test]
    fn build_filter_expands_each_match_all_attribute_independently() {
        let filter = build_filter(&["Tag=a,b".to_string(), "OS=linux".to_string()], &[])
            .unwrap()
            .unwrap();
        let Filter::Bool(BoolFilter { op, operands }) = filter else {
            panic!("expected a bool");
        };
        assert_eq!(op, Op::And);
        assert_eq!(operands.len(), 3);
        assert!(operands.iter().all(|o| matches!(o, Filter::Match(_))));
    }

    #[test]
    fn build_filter_keeps_the_groups_distinct() {
        let filter = build_filter(&["Tag=a,b".to_string()], &["Region=eu,us".to_string()])
            .unwrap()
            .unwrap();
        let Filter::Bool(BoolFilter { op, operands }) = filter else {
            panic!("expected a bool");
        };
        assert_eq!(op, Op::And);
        assert_eq!(
            operands,
            vec![
                Filter::Match(FieldMatch {
                    field: "Tag".to_string(),
                    values: vec!["a".to_string()],
                }),
                Filter::Match(FieldMatch {
                    field: "Tag".to_string(),
                    values: vec!["b".to_string()],
                }),
                Filter::Match(FieldMatch {
                    field: "Region".to_string(),
                    values: vec!["eu".to_string(), "us".to_string()],
                }),
            ]
        );
    }

    #[test]
    fn build_filter_propagates_a_parse_error() {
        assert!(build_filter(&["Region".to_string()], &[]).is_err());
        assert!(build_filter(&[], &["Region".to_string()]).is_err());
    }

    // ── validate_page_window ─────────────────────────────────────────────────

    #[test]
    fn page_window_accepts_an_ascending_window_and_open_ends() {
        assert!(PageWindow {
            start_row: None,
            end_row: None
        }
        .validate()
        .is_ok());
        assert!(PageWindow {
            start_row: Some(0),
            end_row: Some(100)
        }
        .validate()
        .is_ok());
        assert!(PageWindow {
            start_row: Some(100),
            end_row: Some(200)
        }
        .validate()
        .is_ok());
        assert!(PageWindow {
            start_row: Some(100),
            end_row: None
        }
        .validate()
        .is_ok());
        assert!(PageWindow {
            start_row: None,
            end_row: Some(50)
        }
        .validate()
        .is_ok());
        assert!(PageWindow {
            start_row: Some(0),
            end_row: Some(1)
        }
        .validate()
        .is_ok());
    }

    /// The API clamps a negative `startRow` to 0 and returns 200, so without this
    /// check the caller silently gets the first window instead of an error.
    #[test]
    fn page_window_rejects_a_negative_start_row() {
        let err = PageWindow {
            start_row: Some(-5),
            end_row: None,
        }
        .validate()
        .unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("--start-row must not be negative"),
            "got: {msg}"
        );
        assert!(msg.contains("-5"), "got: {msg}");
    }

    #[test]
    fn page_window_rejects_a_negative_end_row() {
        let err = PageWindow {
            start_row: None,
            end_row: Some(-1),
        }
        .validate()
        .unwrap_err();
        assert!(err.to_string().contains("--end-row must not be negative"));
    }

    /// An inverted window yields a row count of 0 server-side, so the caller sees
    /// an empty result set and can easily read it as "no such resources".
    #[test]
    fn page_window_rejects_an_inverted_window() {
        let err = PageWindow {
            start_row: Some(200),
            end_row: Some(100),
        }
        .validate()
        .unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("must be greater than"), "got: {msg}");
        assert!(msg.contains("100") && msg.contains("200"), "got: {msg}");
    }

    /// `--end-row` is exclusive, so an equal start and end can only ever return
    /// nothing - always a mistake rather than a meaningful request.
    #[test]
    fn page_window_rejects_an_empty_window() {
        let err = PageWindow {
            start_row: Some(100),
            end_row: Some(100),
        }
        .validate()
        .unwrap_err();
        assert!(err.to_string().contains("selects no rows"));
    }

    /// The repeat check must not reject distinct keys that share a value.
    #[test]
    fn tag_profile_inserts_key_only_when_multi_profile() {
        let tagged = tag_profile(json!({"a": 1}), true, "prod");
        assert_eq!(tagged["profile"], "prod");

        let untagged = tag_profile(json!({"a": 1}), false, "prod");
        assert!(untagged.get("profile").is_none());
    }

    // ── aggregate_total ──────────────────────────────────────────────────────

    #[test]
    fn aggregate_total_sums_profile_totals() {
        let counts = counts(&[("prod", 150, 100), ("staging", 90, 90)]);
        assert_eq!(aggregate_total(&counts), 240);
    }

    #[test]
    fn aggregate_total_of_no_profiles_is_zero() {
        assert_eq!(aggregate_total(&[]), 0);
    }

    /// Saturating rather than wrapping: a fan-out whose totals exceed `i64::MAX`
    /// must clamp, not flip to a negative "total".
    #[test]
    fn aggregate_total_saturates_instead_of_overflowing() {
        let counts = counts(&[("a", i64::MAX, 1), ("b", 1, 1)]);
        assert_eq!(aggregate_total(&counts), i64::MAX);
    }

    // ── build_list_envelope ──────────────────────────────────────────────────

    #[test]
    fn envelope_reports_total_and_returned_counts() {
        let counts = counts(&[("prod", 512_000, 100)]);
        let envelope = build_list_envelope(512_000, rows(100), &counts, false);

        assert_eq!(envelope["total_count"], 512_000);
        assert_eq!(envelope["returned_count"], 100);
        assert_eq!(envelope["resources"].as_array().unwrap().len(), 100);
    }

    /// The counts must precede `resources` so a consumer reading a truncated
    /// stream still sees its stop condition before the row payload.
    #[test]
    fn envelope_orders_counts_before_resources() {
        let counts = counts(&[("prod", 5, 5)]);
        let envelope = build_list_envelope(5, rows(5), &counts, false);
        let keys: Vec<&str> = envelope
            .as_object()
            .unwrap()
            .keys()
            .map(String::as_str)
            .collect();
        assert_eq!(keys, vec!["total_count", "returned_count", "resources"]);
    }

    /// `returned_count` tracks the rows actually emitted, so a caller can tell a
    /// partial window from a complete one by comparing it against `total_count`.
    #[test]
    fn envelope_distinguishes_a_partial_window_from_the_fleet_total() {
        let counts = counts(&[("prod", 512_000, 100)]);
        let envelope = build_list_envelope(512_000, rows(100), &counts, false);

        assert_ne!(envelope["total_count"], envelope["returned_count"]);
        assert_eq!(envelope["total_count"], 512_000);
        assert_eq!(envelope["returned_count"], 100);
    }

    /// `returned_count` must reflect the rows actually emitted, not a per-profile
    /// figure - under fan-out it is the merged row count across all profiles.
    #[test]
    fn envelope_returned_count_matches_the_emitted_row_count() {
        let counts = counts(&[("prod", 150, 100), ("staging", 90, 90)]);
        let envelope = build_list_envelope(240, rows(190), &counts, true);

        assert_eq!(envelope["returned_count"], 190);
        assert_eq!(
            envelope["returned_count"].as_u64().unwrap() as usize,
            envelope["resources"].as_array().unwrap().len()
        );
    }

    #[test]
    fn envelope_omits_per_profile_counts_for_a_single_profile() {
        let counts = counts(&[("prod", 150, 100)]);
        let envelope = build_list_envelope(150, rows(100), &counts, false);
        assert!(envelope.get("counts_by_profile").is_none());
    }

    /// The page window applies per profile, so a summed total alone cannot tell
    /// a caller which profile still has rows pending.
    #[test]
    fn envelope_breaks_counts_down_per_profile_when_fanning_out() {
        let counts = counts(&[("prod", 150, 100), ("staging", 90, 90)]);
        let envelope = build_list_envelope(240, rows(190), &counts, true);

        let per_profile = envelope["counts_by_profile"].as_array().unwrap();
        assert_eq!(per_profile.len(), 2);
        assert_eq!(per_profile[0]["profile"], "prod");
        assert_eq!(per_profile[0]["total_count"], 150);
        assert_eq!(per_profile[0]["returned_count"], 100);
        assert_eq!(per_profile[1]["profile"], "staging");
        assert_eq!(per_profile[1]["total_count"], 90);
        assert_eq!(per_profile[1]["returned_count"], 90);
    }

    #[test]
    fn envelope_for_no_results_still_reports_counts() {
        let envelope = build_list_envelope(0, rows(0), &counts(&[("prod", 0, 0)]), false);
        assert_eq!(envelope["total_count"], 0);
        assert_eq!(envelope["returned_count"], 0);
        assert!(envelope["resources"].as_array().unwrap().is_empty());
    }

    // ── format_count_summary ─────────────────────────────────────────────────

    #[test]
    fn count_summary_reports_the_total() {
        let counts = counts(&[("prod", 512_000, 100)]);
        assert_eq!(
            format_count_summary(100, 512_000, &counts, false),
            "Showing 100 of 512000 total resources"
        );
    }

    #[test]
    fn count_summary_breaks_down_per_profile_when_fanning_out() {
        let counts = counts(&[("prod", 150, 100), ("staging", 90, 90)]);
        assert_eq!(
            format_count_summary(190, 240, &counts, true),
            "Showing 190 of 240 total resources\n  prod: 100 of 150\n  staging: 90 of 90"
        );
    }

    #[test]
    fn display_or_dash_falls_back_on_none_and_empty() {
        assert_eq!(display_or_dash(Some("value")), "value");
        assert_eq!(display_or_dash(Some("")), "-");
        assert_eq!(display_or_dash(None), "-");
    }

    fn resource(name: Option<&str>, columns: &[(&str, &str)]) -> ResourceData {
        ResourceData {
            resource_id: Some("4013226:host_id=i-077a1626590913a16".to_string()),
            name: name.map(String::from),
            columns: columns
                .iter()
                .map(|(k, v)| (k.to_string(), v.to_string()))
                .collect(),
            category: Some("Hosts".to_string()),
            type_name: Some("EC2_Instances".to_string()),
        }
    }

    #[test]
    fn display_name_prefers_the_name_column() {
        let r = resource(
            Some("i-077a1626590913a16"),
            &[("Name", "ip-10-109-46-236.eu-west-1.compute.internal")],
        );
        assert_eq!(
            display_name(&r),
            Some("ip-10-109-46-236.eu-west-1.compute.internal")
        );
    }

    #[test]
    fn display_name_matches_the_column_key_case_insensitively() {
        let r = resource(Some("i-abc123"), &[("name", "web-server-1")]);
        assert_eq!(display_name(&r), Some("web-server-1"));
    }

    #[test]
    fn display_name_falls_back_to_the_name_field() {
        let missing = resource(Some("i-abc123"), &[("region", "eu-west-1")]);
        assert_eq!(display_name(&missing), Some("i-abc123"));

        let empty = resource(Some("i-abc123"), &[("Name", "")]);
        assert_eq!(display_name(&empty), Some("i-abc123"));

        let neither = resource(None, &[]);
        assert_eq!(display_name(&neither), None);
    }

    fn typed_resource(category: &str, type_name: &str, columns: &[(&str, &str)]) -> ResourceData {
        let mut r = resource(Some("name"), columns);
        r.category = Some(category.to_string());
        r.type_name = Some(type_name.to_string());
        r
    }

    #[test]
    fn union_of_columns_sorts_each_row_then_appends_new_names() {
        let a = typed_resource(
            "Hosts",
            "EC2_Instances",
            &[("Region", "eu"), ("OS", "Linux")],
        );
        let b = typed_resource("Kubernetes", "Pods", &[("Namespace", "kube-system")]);
        assert_eq!(
            union_of_columns(&[&a, &b]),
            vec![
                "OS".to_string(),
                "Region".to_string(),
                "Namespace".to_string()
            ]
        );
    }

    #[test]
    fn union_of_columns_leaves_name_to_its_own_column() {
        let r = typed_resource(
            "Hosts",
            "EC2_Instances",
            &[("Name", "web-01"), ("Region", "eu")],
        );
        assert_eq!(union_of_columns(&[&r]), vec!["Region".to_string()]);
    }

    #[test]
    fn union_of_columns_does_not_repeat_a_shared_column() {
        let a = typed_resource("Hosts", "EC2_Instances", &[("Region", "eu")]);
        let b = typed_resource("Hosts", "Azure_VMs", &[("Region", "westeu")]);
        assert_eq!(union_of_columns(&[&a, &b]), vec!["Region".to_string()]);
    }

    #[test]
    fn union_of_columns_is_empty_without_rows() {
        assert!(union_of_columns(&[]).is_empty());
    }

    fn merged_row(
        category: &str,
        type_name: &str,
        columns: &[(&str, &str)],
    ) -> (String, ResourceData) {
        (
            "p".to_string(),
            typed_resource(category, type_name, columns),
        )
    }

    #[test]
    fn list_table_always_carries_the_classification_columns() {
        let (headers, rows) = list_table(&[merged_row(
            "Hosts",
            "EC2_Instances",
            &[("Region", "eu-west-1")],
        )]);
        assert_eq!(headers[..4], ["Resource ID", "Name", "Category", "Type"]);
        assert_eq!(rows[0][3], "Hosts");
        assert_eq!(rows[0][4], "EC2_Instances");
    }

    #[test]
    fn list_table_has_one_shape_whatever_the_row_mix() {
        let one_type = list_table(&[merged_row("Hosts", "EC2_Instances", &[("Region", "eu")])]).0;
        let mixed = list_table(&[
            merged_row("Hosts", "EC2_Instances", &[("Region", "eu")]),
            merged_row("Hosts", "Azure_VMs", &[("Region", "westeu")]),
        ])
        .0;
        assert_eq!(one_type, mixed);
    }

    #[test]
    fn list_table_leaves_a_missing_column_blank() {
        let (headers, rows) = list_table(&[
            merged_row("Hosts", "EC2_Instances", &[("Region", "eu-west-1")]),
            merged_row("Kubernetes", "Pods", &[("Namespace", "kube-system")]),
        ]);
        assert_eq!(headers[4..], ["Region", "Namespace"]);
        assert_eq!(rows[0][5], "eu-west-1");
        assert_eq!(rows[0][6], "");
        assert_eq!(rows[1][5], "");
        assert_eq!(rows[1][6], "kube-system");
    }

    #[test]
    fn list_table_dashes_a_missing_fixed_column() {
        let mut row = typed_resource("Hosts", "EC2_Instances", &[("Region", "eu")]);
        row.category = None;
        let (_, rows) = list_table(&[("p".to_string(), row)]);
        assert_eq!(rows[0][3], "-");
        assert_eq!(rows[0][5], "eu");
    }

    #[test]
    fn a_json_row_carries_the_scope_and_the_columns() {
        let item = ResourceData {
            resource_id: Some("4013226:host_id=i-077a".to_string()),
            name: Some("prod-api-01".to_string()),
            columns: BTreeMap::from([
                ("Name".to_string(), "prod-api-01".to_string()),
                ("Region".to_string(), "eu-west-1".to_string()),
            ]),
            category: Some("Hosts".to_string()),
            type_name: Some("EC2_Instances".to_string()),
        };

        assert_eq!(
            resource_to_json(&item, false, "prod"),
            json!({
                "resource_id": "4013226:host_id=i-077a",
                "name": "prod-api-01",
                "category": "Hosts",
                "type": "EC2_Instances",
                "columns": { "Name": "prod-api-01", "Region": "eu-west-1" },
            })
        );
    }

    #[test]
    fn a_json_row_is_tagged_with_its_profile_only_when_asked() {
        let item = ResourceData {
            resource_id: Some("id".to_string()),
            name: Some("n".to_string()),
            columns: BTreeMap::new(),
            category: Some("Hosts".to_string()),
            type_name: Some("EC2_Instances".to_string()),
        };

        assert_eq!(resource_to_json(&item, true, "prod")["profile"], "prod");
        assert!(resource_to_json(&item, false, "prod")
            .get("profile")
            .is_none());
    }

    fn counts(entries: &[(&str, i64, usize)]) -> Vec<ProfileCounts> {
        entries
            .iter()
            .map(|(profile, total_count, returned_count)| ProfileCounts {
                profile: profile.to_string(),
                total_count: *total_count,
                returned_count: *returned_count,
            })
            .collect()
    }

    fn rows(n: usize) -> Vec<Value> {
        (0..n)
            .map(|i| json!({ "resource_id": format!("id-{i}") }))
            .collect()
    }
}