coralogix-cli 0.1.19

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
use std::io::Read;
use std::sync::Arc;

use anyhow::{bail, Result};
use colored::Colorize;
use rand::RngExt;
use serde::Serialize;
use serde_json::{json, Value};
use toon_format::encode_default as toon_encode;

pub mod api;

use crate::config::OutputFormat;
use crate::execution::{fan_out, report_errors_and_collect_successes, ExecutionTarget};
use crate::render;
use api::{
    DashboardFolderItem, DashboardSearchResult, DashboardsApi, IssueSeverity, QueryByFieldResult,
    QuerySearchResult,
};

use crate::safety::confirm_destructive;

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

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

/// Look up a string value at a JSON pointer path (e.g. `/dashboard/id`).
fn json_str_at(v: &Value, pointer: &str) -> Option<String> {
    v.pointer(pointer)
        .and_then(|v| v.as_str())
        .map(String::from)
}

/// Extract a dashboard ID from a create/replace response, trying the shapes
/// the API has been observed to return: a top-level `dashboardId`, a
/// top-level `id`, or a nested `dashboard.id`. Returns `None` when the
/// response carried no ID so callers can flag that rather than fabricate one.
fn dashboard_id_from_response(resp: &Value) -> Option<String> {
    json_str_at(resp, "/dashboardId")
        .or_else(|| json_str_at(resp, "/id"))
        .or_else(|| json_str_at(resp, "/dashboard/id"))
}

/// Extract a folder ID from a folder-create response, trying `folderId` then
/// `id`. Returns `None` when the response carried no ID.
fn folder_id_from_response(resp: &Value) -> Option<String> {
    json_str_at(resp, "/folderId").or_else(|| json_str_at(resp, "/id"))
}

/// Builds one catalog row as JSON for `json` / `toon` output after fan-out.
///
/// When `include_profile` is true (multiple `--profile`), injects the profile key so merged
/// arrays stay attributable per account; text mode uses a separate table path.
fn catalog_item_to_json(
    item: &api::DashboardCatalogItem,
    include_profile: bool,
    profile: &str,
) -> Value {
    let mut v = json!({
        "id": item.id,
        "name": item.name,
        "description": item.description,
        "slug_name": item.slug_name,
        "create_time": item.create_time,
        "update_time": item.update_time,
        "is_default": item.is_default,
        "is_pinned": item.is_pinned,
        "is_locked": item.is_locked,
        "folder": item.folder.as_ref().map(|f| json!({
            "id": f.id,
            "name": f.name,
            "parent_id": f.parent_id,
        })),
    });
    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 dashboard-folder row as JSON for `json` / `toon` output after fan-out.
///
/// Same contract as `catalog_item_to_json`: folder list responses are merged across
/// profiles, so we normalize each item to a plain object (string ids via `id_str` /
/// `parent_id_str`) and optionally add the profile key when rendering multi-profile results.
fn folder_item_to_json(item: &DashboardFolderItem, include_profile: bool, profile: &str) -> Value {
    let mut v = json!({
        "id": item.id_str(),
        "name": item.name,
        "parent_id": item.parent_id_str(),
    });
    if include_profile {
        if let Value::Object(ref mut m) = v {
            m.insert(
                JSON_KEY_PROFILE.to_string(),
                Value::String(profile.to_string()),
            );
        }
    }
    v
}

/// One merged row for `json` / `toon`: `serde_json::to_value` (field names = JSON keys), then optional `profile`.
pub fn profiled_api_row_to_json<T: Serialize>(
    profile: &str,
    row: &T,
    include_profile: bool,
    row_kind: &str,
) -> Result<Value> {
    let mut v = serde_json::to_value(row)
        .map_err(|e| anyhow::anyhow!("failed to serialize {row_kind} row: {e}"))?;
    if include_profile {
        if let Value::Object(ref mut m) = v {
            m.insert(
                JSON_KEY_PROFILE.to_string(),
                Value::String(profile.to_string()),
            );
        }
    }
    Ok(v)
}

/// Runs `semantic_search` on every target **concurrently**, flattens `(profile, row)` pairs,
/// and errors if **all** profiles fail (so CI/scripts see a non-zero exit when nothing succeeded).
///
/// `fan_out` schedules one async task per profile. Each task clones the query string, builds a
/// [`DashboardsApi`] for that profile's HTTP client, and awaits the same REST call; answers are
/// stitched together so `-p a -p b` produces one combined list.
async fn collect_semantic_search_results(
    targets: &[Arc<ExecutionTarget>],
    query_text: &str,
    limit: u32,
) -> Result<Vec<(String, DashboardSearchResult)>> {
    let query_owned = query_text.to_string();

    let per_profile = fan_out(targets, |target| {
        let query_clone = query_owned.clone();
        async move {
            let api = DashboardsApi::new(&target.client);
            Ok(api.semantic_search(&query_clone, limit).await?)
        }
    })
    .await;

    let mut all_results: Vec<(String, DashboardSearchResult)> = Vec::new();
    for (profile, resp) in report_errors_and_collect_successes(per_profile)? {
        for r in resp.results {
            all_results.push((profile.clone(), r));
        }
    }
    Ok(all_results)
}

fn semantic_search_merged_json_rows(
    rows: &[(String, DashboardSearchResult)],
    include_profile: bool,
) -> Result<Vec<Value>> {
    rows.iter()
        .map(|(profile, r)| {
            profiled_api_row_to_json(profile, r, include_profile, "dashboard semantic search")
        })
        .collect()
}

fn render_semantic_search_text_table(
    rows: &[(String, DashboardSearchResult)],
    include_profile: bool,
) {
    if rows.is_empty() {
        println!("{}", "No matching dashboards found.".yellow());
        return;
    }
    let table_rows: Vec<Vec<String>> = rows
        .iter()
        .map(|(profile, r)| {
            vec![
                profile.clone(),
                r.dashboard_name.clone().unwrap_or_default(),
                r.dashboard_folder.clone().unwrap_or_default(),
                r.widget_count.map(|n| n.to_string()).unwrap_or_default(),
                format!("{:.3}", r.similarity),
                r.semantic_description
                    .as_deref()
                    .or(r.description.as_deref())
                    .unwrap_or_default()
                    .chars()
                    .take(60)
                    .collect(),
            ]
        })
        .collect();
    render::render_table(
        &["Name", "Folder", "Widgets", "Similarity", "Description"],
        table_rows,
        include_profile,
    );
}

async fn collect_query_search_results(
    targets: &[Arc<ExecutionTarget>],
    query_text: &str,
    limit: u32,
) -> Result<Vec<(String, QuerySearchResult)>> {
    let query_owned = query_text.to_string();
    let per_profile = fan_out(targets, |target| {
        let query_clone = query_owned.clone();
        async move {
            let api = DashboardsApi::new(&target.client);
            Ok(api.search_queries(&query_clone, limit).await?)
        }
    })
    .await;

    let mut all_results: Vec<(String, QuerySearchResult)> = Vec::new();
    for (profile, resp) in report_errors_and_collect_successes(per_profile)? {
        for r in resp.results {
            all_results.push((profile.clone(), r));
        }
    }
    Ok(all_results)
}

fn query_search_merged_json_rows(
    rows: &[(String, QuerySearchResult)],
    include_profile: bool,
) -> Result<Vec<Value>> {
    rows.iter()
        .map(|(profile, r)| {
            profiled_api_row_to_json(profile, r, include_profile, "dashboard query search")
        })
        .collect()
}

fn render_query_search_text_table(rows: &[(String, QuerySearchResult)], include_profile: bool) {
    if rows.is_empty() {
        println!("{}", "No matching queries found.".yellow());
        return;
    }
    let table_rows: Vec<Vec<String>> = rows
        .iter()
        .map(|(profile, r)| {
            vec![
                profile.clone(),
                r.query_text.clone(),
                r.dashboard_name.clone().unwrap_or_default(),
                r.widget_title.clone().unwrap_or_default(),
                format!("{:.3}", r.similarity),
            ]
        })
        .collect();
    render::render_table(
        &["Query", "Dashboard", "Widget", "Similarity"],
        table_rows,
        include_profile,
    );
}

async fn collect_queries_by_field_results(
    targets: &[Arc<ExecutionTarget>],
    field_path: &str,
    limit: u32,
) -> Result<Vec<(String, QueryByFieldResult)>> {
    let field_path_owned = field_path.to_string();
    let per_profile = fan_out(targets, |target| {
        let field_path_clone = field_path_owned.clone();
        async move {
            let api = DashboardsApi::new(&target.client);
            Ok(api.queries_by_field(&field_path_clone, limit).await?)
        }
    })
    .await;

    let mut all_results: Vec<(String, QueryByFieldResult)> = Vec::new();
    for (profile, resp) in report_errors_and_collect_successes(per_profile)? {
        for r in resp.queries {
            all_results.push((profile.clone(), r));
        }
    }
    Ok(all_results)
}

fn queries_by_field_merged_json_rows(
    rows: &[(String, QueryByFieldResult)],
    include_profile: bool,
) -> Result<Vec<Value>> {
    rows.iter()
        .map(|(profile, r)| {
            profiled_api_row_to_json(profile, r, include_profile, "dashboard queries-by-field")
        })
        .collect()
}

fn render_queries_by_field_text_table(
    rows: &[(String, QueryByFieldResult)],
    field_path: &str,
    include_profile: bool,
) {
    if rows.is_empty() {
        println!(
            "{}",
            format!("No queries found referencing {field_path:?}.").yellow()
        );
        return;
    }
    let table_rows: Vec<Vec<String>> = rows
        .iter()
        .map(|(profile, r)| {
            vec![
                profile.clone(),
                r.query_text.clone(),
                r.dashboard_name.clone().unwrap_or_default(),
                r.widget_title.clone().unwrap_or_default(),
                r.matched_fields.join(", "),
            ]
        })
        .collect();
    render::render_table(
        &["Query", "Dashboard", "Widget", "Matched Fields"],
        table_rows,
        include_profile,
    );
}

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

pub async fn run_semantic_search(
    targets: &[Arc<ExecutionTarget>],
    query_text: &str,
    limit: u32,
    output: OutputFormat,
) -> Result<()> {
    if query_text.trim().is_empty() {
        bail!("query text cannot be empty");
    }
    eprintln!(
        "{}",
        format!("Searching dashboards for: {query_text:?}…").dimmed()
    );

    let include_profile = targets.len() > 1;
    let all_results = collect_semantic_search_results(targets, query_text, limit).await?;

    match output {
        OutputFormat::Json => {
            let json_rows = semantic_search_merged_json_rows(&all_results, include_profile)?;
            render::render_json(&json_rows)?;
        }
        OutputFormat::Toon => {
            let json_rows = semantic_search_merged_json_rows(&all_results, include_profile)?;
            render::render_toon(&json_rows)?;
        }
        OutputFormat::Text => render_semantic_search_text_table(&all_results, include_profile),
    }

    Ok(())
}

pub async fn run_catalog(targets: &[Arc<ExecutionTarget>], output: OutputFormat) -> Result<()> {
    eprintln!("{}", "Fetching dashboard catalog...".dimmed());

    let include_profile = targets.len() > 1;

    let per_profile = fan_out(targets, |t| async move {
        let api = DashboardsApi::new(&t.client);
        Ok(api.catalog().await?)
    })
    .await;

    let mut all_rows: Vec<Value> = Vec::new();
    let mut all_items: Vec<(String, api::DashboardCatalogItem)> = Vec::new();
    for (profile, resp) in report_errors_and_collect_successes(per_profile)? {
        // Print the dashboards catalog page link to stderr once per
        // profile. Skip when there are no dashboards, since there's
        // nothing to view.
        if !resp.items.is_empty() {
            crate::execution::emit_console_link_for_profile(targets, &profile, |b| {
                crate::console_url::dashboards_url(b)
            })
            .await;
        }
        for item in resp.items {
            all_rows.push(catalog_item_to_json(&item, include_profile, &profile));
            all_items.push((profile.clone(), item));
        }
    }

    match output {
        OutputFormat::Json => render::render_json(&all_rows)?,
        OutputFormat::Toon => {
            let toon =
                toon_encode(&all_rows).map_err(|e| anyhow::anyhow!("TOON encoding failed: {e}"))?;
            println!("{toon}");
        }
        OutputFormat::Text => {
            if all_items.is_empty() {
                render::print_no_results("No dashboards found.");
                return Ok(());
            }
            let rows: Vec<Vec<String>> = all_items
                .iter()
                .map(|(profile, item)| {
                    vec![
                        profile.clone(),
                        item.id.clone().unwrap_or_default(),
                        item.name.clone().unwrap_or_default(),
                        item.folder
                            .as_ref()
                            .and_then(|f| f.name.clone())
                            .unwrap_or_default(),
                        item.update_time.clone().unwrap_or_default(),
                        render::bool_display(item.is_pinned),
                        render::bool_display(item.is_locked),
                    ]
                })
                .collect();
            render::render_table(
                &["ID", "Name", "Folder", "Updated", "Pinned", "Locked"],
                rows,
                include_profile,
            );
        }
    }

    Ok(())
}

pub async fn run_search(
    targets: &[Arc<ExecutionTarget>],
    query_text: &str,
    limit: u32,
    output: OutputFormat,
) -> Result<()> {
    if query_text.trim().is_empty() {
        bail!("query text cannot be empty");
    }
    eprintln!(
        "{}",
        format!("Searching dashboard queries for: {query_text:?}…").dimmed()
    );

    let include_profile = targets.len() > 1;
    let all_results = collect_query_search_results(targets, query_text, limit).await?;

    match output {
        OutputFormat::Json => {
            let json_rows = query_search_merged_json_rows(&all_results, include_profile)?;
            render::render_json(&json_rows)?;
        }
        OutputFormat::Toon => {
            let json_rows = query_search_merged_json_rows(&all_results, include_profile)?;
            render::render_toon(&json_rows)?;
        }
        OutputFormat::Text => render_query_search_text_table(&all_results, include_profile),
    }

    Ok(())
}

pub async fn run_queries_by_field(
    targets: &[Arc<ExecutionTarget>],
    field_path: &str,
    limit: u32,
    output: OutputFormat,
) -> Result<()> {
    if field_path.trim().is_empty() {
        bail!("field path cannot be empty");
    }
    eprintln!(
        "{}",
        format!("Finding queries referencing field {field_path:?}…").dimmed()
    );

    let include_profile = targets.len() > 1;
    let all_results = collect_queries_by_field_results(targets, field_path, limit).await?;

    match output {
        OutputFormat::Json => {
            let json_rows = queries_by_field_merged_json_rows(&all_results, include_profile)?;
            render::render_json(&json_rows)?;
        }
        OutputFormat::Toon => {
            let json_rows = queries_by_field_merged_json_rows(&all_results, include_profile)?;
            render::render_toon(&json_rows)?;
        }
        OutputFormat::Text => {
            render_queries_by_field_text_table(&all_results, field_path, include_profile);
        }
    }

    Ok(())
}

pub async fn run_get(
    targets: &[Arc<ExecutionTarget>],
    dashboard_id: &str,
    output: OutputFormat,
) -> Result<()> {
    if dashboard_id.trim().is_empty() {
        bail!("dashboard id cannot be empty");
    }
    eprintln!(
        "{}",
        format!("Fetching dashboard {dashboard_id}...").dimmed()
    );

    let include_profile = targets.len() > 1;
    let dashboard_id_owned = dashboard_id.to_string();

    let per_profile = fan_out(targets, |target| {
        let dashboard_id_clone = dashboard_id_owned.clone();
        async move {
            let api = DashboardsApi::new(&target.client);
            Ok(api.get(&dashboard_id_clone).await?)
        }
    })
    .await;

    let mut all_results: Vec<Value> = Vec::new();
    for (profile, mut val) in report_errors_and_collect_successes(per_profile)? {
        if include_profile {
            render::tag_get_result(&mut val, &profile);
        }
        crate::execution::emit_console_link_for_profile(targets, &profile, |b| {
            crate::console_url::dashboard_url(b, dashboard_id)
        })
        .await;
        all_results.push(val);
    }

    match output {
        OutputFormat::Json => render::render_json_auto(&all_results)?,
        OutputFormat::Toon => {
            let toon = toon_encode(&all_results)
                .map_err(|e| anyhow::anyhow!("TOON encoding failed: {e}"))?;
            println!("{toon}");
        }
        OutputFormat::Text => {
            render::render_get_text(
                &all_results,
                include_profile,
                "Dashboard not found.",
                Some(&|val| {
                    let name = val
                        .get("name")
                        .or_else(|| val.get("dashboard").and_then(|d| d.get("name")))
                        .and_then(|v| v.as_str())
                        .unwrap_or("-");
                    let id = val
                        .get("id")
                        .or_else(|| val.get("dashboard").and_then(|d| d.get("id")))
                        .and_then(|v| v.as_str())
                        .unwrap_or("-");
                    let desc = val
                        .get("description")
                        .or_else(|| val.get("dashboard").and_then(|d| d.get("description")))
                        .and_then(|v| v.as_str())
                        .unwrap_or("");

                    println!("{}: {}", "Name".bold(), name);
                    println!("{}:   {}", "ID".bold(), id);
                    if !desc.is_empty() {
                        println!("{}: {}", "Desc".bold(), desc);
                    }
                }),
            )?;
        }
    }

    Ok(())
}

// ── Create ────────────────────────────────────────────────────────────────────

/// Generate a random hex string for the `requestId` envelope field.
fn new_request_id() -> String {
    let mut rng = rand::rng();
    (0..16)
        .map(|_| format!("{:02x}", rng.random::<u8>()))
        .collect()
}

/// Read a JSON payload from a file path or stdin (when `from_file == "-"`),
/// and normalize it into the inner `dashboard` object expected by the
/// `CreateDashboard` API. Accepts either the bare dashboard JSON or the
/// `{ "dashboard": {...} }` wrapper form.
fn read_dashboard_body(from_file: &str) -> Result<Value> {
    let raw = if from_file == "-" {
        eprintln!("{}", "Reading dashboard definition from stdin...".dimmed());
        let mut buf = String::new();
        std::io::stdin().read_to_string(&mut buf)?;
        buf
    } else {
        eprintln!(
            "{}",
            format!("Reading dashboard definition from {from_file}...").dimmed()
        );
        std::fs::read_to_string(from_file)?
    };

    let parsed: Value = serde_json::from_str(&raw)?;

    // Allow either a bare dashboard doc or a pre-wrapped request payload.
    let dashboard = if parsed.get("dashboard").is_some() {
        parsed
            .get("dashboard")
            .cloned()
            .unwrap_or_else(|| json!({}))
    } else {
        parsed
    };

    if !dashboard.is_object() {
        bail!("Dashboard JSON must be a JSON object (got {})", dashboard);
    }
    if dashboard.get("layout").is_none() {
        bail!(
            "Dashboard JSON is missing required 'layout' field. See `cx dashboards create --help`."
        );
    }

    Ok(dashboard)
}

pub async fn run_create(
    targets: &[Arc<ExecutionTarget>],
    from_file: &str,
    folder_id: Option<&str>,
    output: OutputFormat,
) -> Result<()> {
    let mut dashboard = read_dashboard_body(from_file)?;

    // Inject folder assignment if the caller provided one.
    if let Some(folder) = folder_id {
        if let Value::Object(ref mut m) = dashboard {
            m.insert(
                "folderId".to_string(),
                json!({ "value": folder.to_string() }),
            );
        }
    }

    let name = dashboard
        .get("name")
        .and_then(|v| v.as_str())
        .unwrap_or("<unnamed>")
        .to_string();

    eprintln!("{}", format!("Creating dashboard '{name}'...").dimmed());

    let include_profile = targets.len() > 1;

    let per_profile = fan_out(targets, |t| {
        let dashboard = dashboard.clone();
        async move {
            let body = json!({
                "requestId": new_request_id(),
                "dashboard": dashboard,
            });
            let api = DashboardsApi::new(&t.client);
            Ok(api.create(&body).await?)
        }
    })
    .await;

    let mut all_results: Vec<Value> = Vec::new();
    for (profile, mut resp) in report_errors_and_collect_successes(per_profile)? {
        let created_id = dashboard_id_from_response(&resp);
        render::print_created(
            "Created",
            "dashboard",
            Some(&name),
            created_id.as_deref(),
            &profile,
        );
        if let Some(id) = &created_id {
            crate::execution::emit_console_link_for_profile(targets, &profile, |b| {
                crate::console_url::dashboard_url(b, id)
            })
            .await;
        }
        if include_profile {
            render::tag_get_result(&mut resp, &profile);
        }
        all_results.push(resp);
    }

    match output {
        OutputFormat::Json => render::render_json_auto(&all_results)?,
        OutputFormat::Toon => {
            let toon = toon_encode(&all_results)
                .map_err(|e| anyhow::anyhow!("TOON encoding failed: {e}"))?;
            println!("{toon}");
        }
        // Status lines already printed to stderr via `print_created`.
        OutputFormat::Text => {}
    }

    Ok(())
}

// ── Replace ──────────────────────────────────────────────────────────────────

pub async fn run_replace(
    targets: &[Arc<ExecutionTarget>],
    from_file: &str,
    output: OutputFormat,
    yes: bool,
    agent_mode: bool,
) -> Result<()> {
    let dashboard = read_dashboard_body(from_file)?;

    let dash_id = dashboard
        .get("id")
        .and_then(|v| v.as_str())
        .ok_or_else(|| {
            anyhow::anyhow!(
                "Dashboard JSON is missing required 'id' field. \
                 Use `cx dashboards get <id> -o json` to fetch the full definition, \
                 then pass the edited JSON to `cx dashboards replace`."
            )
        })?;

    let name = dashboard
        .get("name")
        .and_then(|v| v.as_str())
        .unwrap_or("<unnamed>")
        .to_string();

    confirm_destructive(
        &format!("Replace dashboard '{name}' ({dash_id})?"),
        yes,
        agent_mode,
    )?;

    eprintln!("{}", format!("Replacing dashboard '{name}'...").dimmed());

    let include_profile = targets.len() > 1;

    let per_profile = fan_out(targets, |t| {
        let dashboard = dashboard.clone();
        async move {
            let body = json!({
                "requestId": new_request_id(),
                "dashboard": dashboard,
            });
            let api = DashboardsApi::new(&t.client);
            Ok(api.replace(&body).await?)
        }
    })
    .await;

    let mut all_results: Vec<Value> = Vec::new();
    for (profile, mut resp) in report_errors_and_collect_successes(per_profile)? {
        // The request already carried the dashboard's id (`dash_id`, required above), so
        // fall back to it when the replace response comes back without one — some
        // deployments return an empty body on a successful replace.
        let replaced_id = dashboard_id_from_response(&resp).or_else(|| Some(dash_id.to_string()));
        render::print_created(
            "Replaced",
            "dashboard",
            Some(&name),
            replaced_id.as_deref(),
            &profile,
        );
        if let Some(id) = &replaced_id {
            crate::execution::emit_console_link_for_profile(targets, &profile, |b| {
                crate::console_url::dashboard_url(b, id)
            })
            .await;
        }
        if include_profile {
            render::tag_get_result(&mut resp, &profile);
        }
        all_results.push(resp);
    }

    match output {
        OutputFormat::Json => render::render_json_auto(&all_results)?,
        OutputFormat::Toon => {
            let toon = toon_encode(&all_results)
                .map_err(|e| anyhow::anyhow!("TOON encoding failed: {e}"))?;
            println!("{toon}");
        }
        // Status lines already printed to stderr via `print_created`.
        OutputFormat::Text => {}
    }

    Ok(())
}

// ── Delete ────────────────────────────────────────────────────────────────────

pub async fn run_delete(targets: &[Arc<ExecutionTarget>], id: &str) -> Result<()> {
    eprintln!("{}", format!("Deleting dashboard {id}...").dimmed());
    let dashboard_id_owned = id.to_string();
    let per_profile = fan_out(targets, |target| {
        let dashboard_id_clone = dashboard_id_owned.clone();
        async move {
            let api = DashboardsApi::new(&target.client);
            api.delete(&dashboard_id_clone).await?;
            Ok(())
        }
    })
    .await;
    for (profile, ()) in report_errors_and_collect_successes(per_profile)? {
        eprintln!(
            "{}",
            format!("Dashboard {id} deleted in profile '{profile}'.").green()
        );
    }
    Ok(())
}

// ── Folders ───────────────────────────────────────────────────────────────────

pub async fn run_folders_list(
    targets: &[Arc<ExecutionTarget>],
    output: OutputFormat,
) -> Result<()> {
    eprintln!("{}", "Fetching dashboard folders...".dimmed());

    let include_profile = targets.len() > 1;

    let per_profile = fan_out(targets, |t| async move {
        let api = DashboardsApi::new(&t.client);
        Ok(api.folders().await?)
    })
    .await;

    let mut all_rows: Vec<Value> = Vec::new();
    let mut all_items: Vec<(String, DashboardFolderItem)> = Vec::new();
    for (profile, resp) in report_errors_and_collect_successes(per_profile)? {
        // Folders live in the same catalog UI as the dashboards themselves,
        // so link to the same page. Skip when there are no folders.
        if !resp.folders.is_empty() {
            crate::execution::emit_console_link_for_profile(targets, &profile, |b| {
                crate::console_url::dashboards_url(b)
            })
            .await;
        }
        for item in resp.folders {
            all_rows.push(folder_item_to_json(&item, include_profile, &profile));
            all_items.push((profile.clone(), item));
        }
    }

    match output {
        OutputFormat::Json => render::render_json(&all_rows)?,
        OutputFormat::Toon => {
            let toon =
                toon_encode(&all_rows).map_err(|e| anyhow::anyhow!("TOON encoding failed: {e}"))?;
            println!("{toon}");
        }
        OutputFormat::Text => {
            if all_items.is_empty() {
                render::print_no_results("No dashboard folders found.");
                return Ok(());
            }
            let rows: Vec<Vec<String>> = all_items
                .iter()
                .map(|(profile, item)| {
                    vec![
                        profile.clone(),
                        item.id_str().unwrap_or("").to_string(),
                        item.name.clone().unwrap_or_default(),
                        item.parent_id_str().unwrap_or("").to_string(),
                    ]
                })
                .collect();
            render::render_table(&["ID", "Name", "Parent ID"], rows, include_profile);
        }
    }

    Ok(())
}

pub async fn run_folders_create(
    targets: &[Arc<ExecutionTarget>],
    name: &str,
    parent_id: Option<&str>,
    output: OutputFormat,
) -> Result<()> {
    if name.trim().is_empty() {
        bail!("folder name cannot be empty");
    }
    eprintln!(
        "{}",
        format!("Creating dashboard folder '{name}'...").dimmed()
    );

    let include_profile = targets.len() > 1;
    let name_owned = name.to_string();
    let parent_id_owned = parent_id.map(|s| s.to_string());

    let per_profile = fan_out(targets, |t| {
        let name = name_owned.clone();
        let parent_id = parent_id_owned.clone();
        async move {
            let mut folder = json!({ "name": name });
            if let (Some(p), Value::Object(ref mut m)) = (parent_id.as_ref(), &mut folder) {
                m.insert("parentId".to_string(), Value::String(p.clone()));
            }
            let body = json!({
                "requestId": new_request_id(),
                "folder": folder,
            });
            let api = DashboardsApi::new(&t.client);
            Ok(api.folders_create(&body).await?)
        }
    })
    .await;

    let mut all_results: Vec<Value> = Vec::new();
    for (profile, mut resp) in report_errors_and_collect_successes(per_profile)? {
        let created_id = folder_id_from_response(&resp);
        render::print_created(
            "Created",
            "dashboard folder",
            Some(name),
            created_id.as_deref(),
            &profile,
        );
        if include_profile {
            render::tag_get_result(&mut resp, &profile);
        }
        all_results.push(resp);
    }

    match output {
        OutputFormat::Json => render::render_json_auto(&all_results)?,
        OutputFormat::Toon => {
            let toon = toon_encode(&all_results)
                .map_err(|e| anyhow::anyhow!("TOON encoding failed: {e}"))?;
            println!("{toon}");
        }
        // Status lines already printed to stderr via `print_created`.
        OutputFormat::Text => {}
    }

    Ok(())
}

pub async fn run_folders_delete(targets: &[Arc<ExecutionTarget>], id: &str) -> Result<()> {
    eprintln!("{}", format!("Deleting dashboard folder {id}...").dimmed());
    let folder_id_owned = id.to_string();
    let per_profile = fan_out(targets, |target| {
        let folder_id_clone = folder_id_owned.clone();
        async move {
            let api = DashboardsApi::new(&target.client);
            api.folders_delete(&folder_id_clone).await?;
            Ok(())
        }
    })
    .await;
    for (profile, ()) in report_errors_and_collect_successes(per_profile)? {
        eprintln!(
            "{}",
            format!("Folder {id} deleted in profile '{profile}'.").green()
        );
    }
    Ok(())
}

// ── Check (CheckDashboard) ────────────────────────────────────────────────────

/// Build the `CheckDashboardRequest` JSON body for the `dashboardId` oneof arm.
fn check_body_from_id(dashboard_id: &str) -> Value {
    json!({ "dashboardId": dashboard_id })
}

/// Build the `CheckDashboardRequest` JSON body for the `dashboard` oneof arm,
/// reusing `read_dashboard_body` to normalize a bare doc or a
/// `{ "dashboard": {...} }` wrapper into the inner dashboard object.
fn check_body_from_file(from_file: &str) -> Result<Value> {
    let dashboard = read_dashboard_body(from_file)?;
    Ok(json!({ "dashboard": dashboard }))
}

/// Colorize a severity string for text output.
fn severity_colored(severity: IssueSeverity) -> String {
    let s = match severity {
        IssueSeverity::SeverityError => "SEVERITY_ERROR",
        IssueSeverity::SeverityWarning => "SEVERITY_WARNING",
        IssueSeverity::SeverityUnspecified => "SEVERITY_UNSPECIFIED",
    };
    match severity {
        IssueSeverity::SeverityError => s.red().to_string(),
        IssueSeverity::SeverityWarning => s.yellow().to_string(),
        IssueSeverity::SeverityUnspecified => s.dimmed().to_string(),
    }
}

/// Build one issue row as JSON for `json` / `toon` output.
fn issue_json_row(issue: &api::DashboardCheckIssue, profile: &str, include_profile: bool) -> Value {
    let mut row = serde_json::to_value(issue).unwrap_or_else(|_| json!({}));
    if include_profile {
        if let Value::Object(ref mut m) = row {
            m.insert(
                JSON_KEY_PROFILE.to_string(),
                Value::String(profile.to_string()),
            );
        }
    }
    row
}

/// Validate a dashboard definition without persisting it
/// (`DashboardsService.CheckDashboard`).
///
/// Exactly one of `from_file` or `dashboard_id` must be supplied:
/// - `from_file` — path to a JSON file (or `-` for stdin) holding either a
///   bare dashboard doc or a `{ "dashboard": {...} }` wrapper.
/// - `dashboard_id` — validate a stored dashboard by id.
///
/// Read-only. Exits non-zero if any error-severity issue is found (CI gate).
/// In multi-profile fan-out, any profile returning error-severity issues
/// causes a non-zero exit, even if other profiles are clean — this is a
/// deliberate carve-out from the usual "exit 0 if any profile succeeds" rule,
/// because `check` is a validation gate first.
pub async fn run_check(
    targets: &[Arc<ExecutionTarget>],
    from_file: Option<&str>,
    dashboard_id: Option<&str>,
    output: OutputFormat,
) -> Result<()> {
    // Mutually exclusive sources. clap enforces "both" via `conflicts_with`;
    // we guard "neither" here with a clear message.
    let body = match (from_file, dashboard_id) {
        (Some(path), None) => {
            eprintln!("{}", "Checking dashboard from file...".dimmed());
            check_body_from_file(path)?
        }
        (None, Some(id)) => {
            if id.trim().is_empty() {
                bail!("dashboard id cannot be empty");
            }
            eprintln!("{}", format!("Checking dashboard {id}...").dimmed());
            check_body_from_id(id)
        }
        (Some(_), Some(_)) => {
            bail!("`--from-file` and `<dashboard_id>` are mutually exclusive; specify one")
        }
        (None, None) => {
            bail!("specify either `--from-file <path>` or a `<dashboard_id>` to check")
        }
    };

    let include_profile = targets.len() > 1;

    let per_profile = fan_out(targets, |t| {
        let body = body.clone();
        async move {
            let api = DashboardsApi::new(&t.client);
            Ok(api.check(&body).await?)
        }
    })
    .await;

    let mut all_issues: Vec<(String, Vec<api::DashboardCheckIssue>)> = Vec::new();
    for (profile, resp) in report_errors_and_collect_successes(per_profile)? {
        if let Some(id) = dashboard_id {
            crate::execution::emit_console_link_for_profile(targets, &profile, |b| {
                crate::console_url::dashboard_url(b, id)
            })
            .await;
        }
        all_issues.push((profile, resp.issues));
    }

    // CI-gate semantics: any error-severity issue (in any profile) fails.
    let total_errors = all_issues
        .iter()
        .flat_map(|(_, issues)| issues.iter())
        .filter(|i| i.severity.is_failure())
        .count();
    let total_issues = all_issues.iter().map(|(_, i)| i.len()).sum::<usize>();

    match output {
        OutputFormat::Json => {
            let mut rows: Vec<Value> = Vec::new();
            for (profile, issues) in &all_issues {
                for issue in issues {
                    rows.push(issue_json_row(issue, profile, include_profile));
                }
            }
            render::render_json(&rows)?;
        }
        OutputFormat::Toon => {
            let mut rows: Vec<Value> = Vec::new();
            for (profile, issues) in &all_issues {
                for issue in issues {
                    rows.push(issue_json_row(issue, profile, include_profile));
                }
            }
            render::render_toon(&rows)?;
        }
        OutputFormat::Text => {
            if total_issues == 0 {
                println!("{}", "Dashboard is valid (no issues)".green());
            } else {
                let mut rows: Vec<Vec<String>> = Vec::new();
                for (profile, issues) in &all_issues {
                    for issue in issues {
                        let row = vec![
                            profile.clone(),
                            severity_colored(issue.severity),
                            issue.location.clone().unwrap_or_default(),
                            issue.message.clone().unwrap_or_default(),
                        ];
                        rows.push(row);
                    }
                }
                render::render_table(&["Severity", "Location", "Message"], rows, include_profile);
            }
        }
    }

    if total_errors > 0 {
        bail!(
            "dashboard check found {total_errors} error(s) across profile(s); {} warning(s) ignored",
            total_issues - total_errors
        );
    }
    Ok(())
}

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

    /// Regression guard for the `render_table` profile-column contract.
    ///
    /// `format_table` strips the first cell of every row when
    /// `include_profile` is false (single-profile mode). Callers must
    /// therefore push the profile as the first element unconditionally;
    /// conditional placement causes the severity column to be dropped and
    /// the remaining columns to shift left. This test constructs rows the
    /// same way `run_check` does and asserts the severity text survives
    /// rendering in single-profile mode.
    #[test]
    fn run_check_rows_preserve_severity_in_single_profile_output() {
        let profile = "mock-profile";
        let issue = api::DashboardCheckIssue {
            severity: api::IssueSeverity::SeverityWarning,
            message: Some("Query uses deprecated function 'timeShift'".to_string()),
            location: Some("/sections/1/rows/0/widgets/0/queries/0".to_string()),
        };

        // Mirrors the row construction in `run_check`'s Text branch.
        let row = vec![
            profile.to_string(),
            severity_colored(issue.severity),
            issue.location.clone().unwrap_or_default(),
            issue.message.clone().unwrap_or_default(),
        ];

        let rendered = render::format_table(
            &["Severity", "Location", "Message"],
            vec![row],
            false, // single-profile mode
        );

        // Severity text must be present (the bug dropped it via skip(1)).
        assert!(
            rendered.contains("SEVERITY_WARNING"),
            "severity column dropped in single-profile output: {rendered}"
        );
        assert!(
            rendered.contains("/sections/1/rows/0/widgets/0/queries/0"),
            "location column missing in single-profile output: {rendered}"
        );
        assert!(
            rendered.contains("Query uses deprecated function 'timeShift'"),
            "message column missing in single-profile output: {rendered}"
        );
    }
}