orbit-tui 1.1.1

Terminal UI for AWS - navigate, observe, and manage AWS resources
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
//! AWS API Dispatcher
//!
//! This module handles all AWS API dispatching:
//! - List operations via JSON config
//! - Actions (write operations like start/stop/delete)
//! - Describe (single resource details)
//!
//! API operations are configured in JSON files under src/resources/.
//! Special cases (S3 objects, STS) have dedicated handlers.

use super::field_mapper::build_response;
use super::handlers::get_protocol_handler;
use super::protocol::ApiProtocol;
use super::registry::get_resource;
use crate::aws::client::AwsClients;
use crate::aws::http::xml_to_json;
use anyhow::{anyhow, Result};
use serde_json::{json, Value};
use tracing::debug;

// =============================================================================
// Helper Functions
// =============================================================================

/// Extract a single string parameter from Value
fn extract_param(params: &Value, key: &str) -> String {
    params
        .get(key)
        .and_then(|v| {
            v.as_str().map(|s| s.to_string()).or_else(|| {
                v.as_array()
                    .and_then(|a| a.first())
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_string())
            })
        })
        .unwrap_or_default()
}

/// Format bytes into human-readable format
fn format_bytes(bytes: u64) -> String {
    const KB: u64 = 1024;
    const MB: u64 = KB * 1024;
    const GB: u64 = MB * 1024;
    const TB: u64 = GB * 1024;

    if bytes >= TB {
        format!("{:.1} TB", bytes as f64 / TB as f64)
    } else if bytes >= GB {
        format!("{:.1} GB", bytes as f64 / GB as f64)
    } else if bytes >= MB {
        format!("{:.1} MB", bytes as f64 / MB as f64)
    } else if bytes >= KB {
        format!("{:.1} KB", bytes as f64 / KB as f64)
    } else {
        format!("{} B", bytes)
    }
}

/// Format epoch milliseconds to human-readable date string
fn format_epoch_millis(millis: i64) -> String {
    use chrono::{TimeZone, Utc};

    if millis <= 0 {
        return "-".to_string();
    }

    Utc.timestamp_millis_opt(millis)
        .single()
        .map(|dt| dt.format("%Y-%m-%d %H:%M:%S").to_string())
        .unwrap_or_else(|| "-".to_string())
}

/// Resolve template variables in static param values: {resource_id}, {timestamp}
fn resolve_static_param_template(template: &str, resource_id: &str, timestamp: &str) -> String {
    template
        .replace("{resource_id}", resource_id)
        .replace("{timestamp}", timestamp)
}

/// Format epoch milliseconds to human-readable date string (public for log tail UI)
pub fn format_log_timestamp(millis: i64) -> String {
    format_epoch_millis(millis)
}

// =============================================================================
// Data-Driven List Operations
// =============================================================================

/// Invoke an AWS list API using JSON configuration
///
/// This function reads the API configuration from the resource definition
/// and uses the appropriate protocol handler to execute the request.
pub async fn invoke_list(
    resource_key: &str,
    clients: &AwsClients,
    params: &Value,
) -> Result<Value> {
    let resource_def =
        get_resource(resource_key).ok_or_else(|| anyhow!("Unknown resource: {}", resource_key))?;

    let api_config = resource_def
        .api_config
        .as_ref()
        .ok_or_else(|| anyhow!("Resource {} does not have api_config", resource_key))?;

    let handler = get_protocol_handler(api_config.protocol);

    let service = api_config
        .service_name
        .as_deref()
        .unwrap_or(&resource_def.service);

    let parsed = handler
        .invoke(
            clients,
            service,
            api_config,
            params,
            &resource_def.field_mappings,
        )
        .await?;

    Ok(build_response(
        parsed.items,
        &resource_def.response_path,
        parsed.next_token,
    ))
}

// =============================================================================
// Legacy List Operations (special cases)
// =============================================================================

/// Invoke an AWS API method for special cases (S3 objects, STS, CloudWatch logs).
/// Most list operations should use invoke_list instead.
pub async fn invoke_sdk(
    service: &str,
    method: &str,
    clients: &AwsClients,
    params: &Value,
) -> Result<Value> {
    match (service, method) {
        // S3 list_objects_v2 - requires bucket region resolution and complex folder handling
        ("s3", "list_objects_v2") => {
            let bucket = extract_param(params, "bucket_names");
            if bucket.is_empty() {
                return Err(anyhow!("Bucket name required"));
            }

            let prefix = params
                .get("prefix")
                .map(|v| {
                    if let Some(s) = v.as_str() {
                        s.to_string()
                    } else if let Some(arr) = v.as_array() {
                        arr.first()
                            .and_then(|v| v.as_str())
                            .unwrap_or("")
                            .to_string()
                    } else {
                        String::new()
                    }
                })
                .unwrap_or_default();

            let bucket_region = clients.http.get_bucket_region(&bucket).await?;
            debug!("Bucket {} is in region {}", bucket, bucket_region);

            let path = if prefix.is_empty() {
                "?list-type=2&delimiter=/".to_string()
            } else {
                format!(
                    "?list-type=2&delimiter=/&prefix={}",
                    urlencoding::encode(&prefix)
                )
            };

            let xml = clients
                .http
                .rest_xml_request_s3_bucket("GET", &bucket, &path, None, &bucket_region)
                .await?;
            let json = xml_to_json(&xml)?;

            let mut objects: Vec<Value> = vec![];

            // Add common prefixes (folders)
            if let Some(prefixes) = json.pointer("/ListBucketResult/CommonPrefixes") {
                let prefix_list = match prefixes {
                    Value::Array(arr) => arr.clone(),
                    obj @ Value::Object(_) => vec![obj.clone()],
                    _ => vec![],
                };
                for p in prefix_list {
                    let prefix_val = p.pointer("/Prefix").and_then(|v| v.as_str()).unwrap_or("-");
                    let display_name = prefix_val
                        .trim_end_matches('/')
                        .rsplit('/')
                        .next()
                        .unwrap_or(prefix_val);
                    objects.push(json!({
                        "Key": prefix_val,
                        "DisplayName": format!("{}/", display_name),
                        "Size": "-",
                        "LastModified": "-",
                        "StorageClass": "FOLDER",
                        "IsFolder": true
                    }));
                }
            }

            // Add objects (files)
            if let Some(contents) = json.pointer("/ListBucketResult/Contents") {
                let content_list = match contents {
                    Value::Array(arr) => arr.clone(),
                    obj @ Value::Object(_) => vec![obj.clone()],
                    _ => vec![],
                };
                for obj in content_list {
                    let key = obj.pointer("/Key").and_then(|v| v.as_str()).unwrap_or("-");
                    if key == prefix {
                        continue;
                    }
                    let display_name = key.rsplit('/').next().unwrap_or(key);
                    let size = obj.pointer("/Size").and_then(|v| v.as_str()).unwrap_or("0");
                    let size_bytes = size.parse::<u64>().unwrap_or(0);
                    let size_formatted = format_bytes(size_bytes);
                    objects.push(json!({
                        "Key": key,
                        "DisplayName": display_name,
                        "Size": size_formatted,
                        // Raw byte count kept alongside the display string so the
                        // download size guard doesn't have to parse "1.2 KB" back
                        "SizeBytes": size_bytes,
                        "LastModified": obj.pointer("/LastModified").and_then(|v| v.as_str()).unwrap_or("-"),
                        "StorageClass": obj.pointer("/StorageClass").and_then(|v| v.as_str()).unwrap_or("STANDARD"),
                        "IsFolder": false
                    }));
                }
            }

            Ok(json!({ "objects": objects }))
        }

        // STS get_caller_identity - returns single item, not a list
        ("sts", "get_caller_identity") => {
            let xml = clients
                .http
                .query_request("sts", "GetCallerIdentity", &[])
                .await?;
            let json = xml_to_json(&xml)?;

            let result_path = json.pointer("/GetCallerIdentityResponse/GetCallerIdentityResult");
            let identity = json!({
                "Account": result_path.and_then(|r| r.pointer("/Account")).and_then(|v| v.as_str()).unwrap_or("-"),
                "UserId": result_path.and_then(|r| r.pointer("/UserId")).and_then(|v| v.as_str()).unwrap_or("-"),
                "Arn": result_path.and_then(|r| r.pointer("/Arn")).and_then(|v| v.as_str()).unwrap_or("-"),
            });

            Ok(json!({ "identity": [identity] }))
        }

        // CloudWatch Logs - tail_logs (streaming operation)
        ("cloudwatchlogs", "tail_logs") => {
            let log_group = extract_param(params, "log_group_name");
            let log_stream = extract_param(params, "log_stream_name");

            if log_group.is_empty() || log_stream.is_empty() {
                return Err(anyhow!("Log group and stream names required"));
            }

            let request_body = json!({
                "logGroupName": log_group,
                "logStreamName": log_stream,
                "startFromHead": false,
                "limit": 100
            })
            .to_string();

            let response = clients
                .http
                .json_request("logs", "GetLogEvents", &request_body)
                .await?;
            let json: Value = serde_json::from_str(&response)?;

            let events = json
                .get("events")
                .and_then(|v| v.as_array())
                .cloned()
                .unwrap_or_default();
            let result: Vec<Value> = events
                .iter()
                .map(|e| {
                    let timestamp = e.get("timestamp").and_then(|v| v.as_i64()).unwrap_or(0);
                    json!({
                        "timestamp": format_epoch_millis(timestamp),
                        "message": e.get("message").and_then(|v| v.as_str()).unwrap_or("-"),
                    })
                })
                .collect();

            Ok(json!({ "events": result }))
        }

        // CloudWatch Logs - get_log_events (for log tailing UI)
        ("cloudwatchlogs", "get_log_events") => {
            let log_group = extract_param(params, "log_group_name");
            let log_stream = extract_param(params, "log_stream_name");

            if log_group.is_empty() || log_stream.is_empty() {
                return Err(anyhow!("Log group and stream names required"));
            }

            let mut request = json!({
                "logGroupName": log_group,
                "logStreamName": log_stream,
                "startFromHead": false,
                "limit": 100
            });

            // Add next token if provided
            if let Some(token) = params.get("next_forward_token").and_then(|v| v.as_str()) {
                request["nextToken"] = json!(token);
            }

            let response = clients
                .http
                .json_request("logs", "GetLogEvents", &request.to_string())
                .await?;
            let json: Value = serde_json::from_str(&response)?;

            Ok(json)
        }

        _ => Err(anyhow!(
            "Operation not handled: service='{}', method='{}'. Configure it in the resource JSON.",
            service,
            method
        )),
    }
}

// =============================================================================
// Data-Driven Action Execution
// =============================================================================

/// Execute an action using JSON configuration
async fn invoke_action(
    resource_key: &str,
    action_id: &str,
    clients: &AwsClients,
    resource_id: &str,
) -> Result<()> {
    let resource_def =
        get_resource(resource_key).ok_or_else(|| anyhow!("Unknown resource: {}", resource_key))?;

    let action_config = resource_def
        .action_configs
        .get(action_id)
        .ok_or_else(|| anyhow!("Action '{}' not configured for {}", action_id, resource_key))?;

    let service = action_config
        .service_name
        .as_deref()
        .unwrap_or(&resource_def.service);

    debug!(
        "Executing action: {} on {} (service: {}, protocol: {:?})",
        action_id, resource_key, service, action_config.protocol
    );

    match action_config.protocol {
        ApiProtocol::Query => {
            let action_name = action_config
                .action
                .as_ref()
                .ok_or_else(|| anyhow!("Query action requires 'action' field"))?;

            let mut params_owned: Vec<(String, String)> = Vec::new();

            // Handle special formats
            if action_config.special_handling.as_deref() == Some("parse_pipe_format_tg_target") {
                // Format: target_group_arn|target_id
                let parts: Vec<&str> = resource_id.split('|').collect();
                if parts.len() != 2 {
                    return Err(anyhow!(
                        "Invalid target format, expected target_group_arn|target_id"
                    ));
                }
                params_owned.push(("TargetGroupArn".to_string(), parts[0].to_string()));
                params_owned.push(("Targets.member.1.Id".to_string(), parts[1].to_string()));
            } else {
                // Add resource ID parameter
                if let Some(ref id_param) = action_config.id_param {
                    params_owned.push((id_param.clone(), resource_id.to_string()));
                }
            }

            // Add static parameters
            // Resolve template variables in static params: {resource_id}, {timestamp}
            let current_timestamp = chrono::Utc::now().format("%Y%m%dT%H%M%S").to_string();

            for (key, value) in &action_config.static_params {
                if let Some(template) = value.as_str() {
                    let resolved =
                        resolve_static_param_template(template, resource_id, &current_timestamp);
                    params_owned.push((key.clone(), resolved));
                }
            }

            let params_ref: Vec<(&str, &str)> = params_owned
                .iter()
                .map(|(k, v)| (k.as_str(), v.as_str()))
                .collect();

            clients
                .http
                .query_request(service, action_name, &params_ref)
                .await?;
            Ok(())
        }

        ApiProtocol::Json => {
            let action_name = action_config
                .action
                .as_ref()
                .ok_or_else(|| anyhow!("JSON action requires 'action' field"))?;

            let body = if let Some(ref template) = action_config.body_template {
                // Handle special ARN parsing if needed
                let actual_id =
                    if action_config.special_handling.as_deref() == Some("parse_arn_for_cluster") {
                        // Extract cluster from ARN like arn:aws:ecs:region:account:service/cluster/service-name
                        let parts: Vec<&str> = resource_id.split('/').collect();
                        if parts.len() >= 2 {
                            parts[parts.len() - 2].to_string()
                        } else {
                            resource_id.to_string()
                        }
                    } else {
                        resource_id.to_string()
                    };

                template
                    .replace("{resource_id}", &actual_id)
                    .replace("{cluster}", {
                        let parts: Vec<&str> = resource_id.split('/').collect();
                        if parts.len() >= 2 {
                            parts[parts.len() - 2]
                        } else {
                            resource_id
                        }
                    })
            } else {
                // Build body from id_param
                let id_param = action_config.id_param.as_deref().unwrap_or("id");
                json!({ id_param: resource_id }).to_string()
            };

            clients
                .http
                .json_request(service, action_name, &body)
                .await?;
            Ok(())
        }

        ApiProtocol::RestJson => {
            let method = action_config.method.as_deref().unwrap_or("DELETE");
            let path_template = action_config
                .path
                .as_ref()
                .ok_or_else(|| anyhow!("REST-JSON action requires 'path' field"))?;

            let path = path_template.replace("{resource_id}", resource_id);
            let body = action_config.body_template.as_deref();

            clients
                .http
                .rest_json_request(service, method, &path, body)
                .await?;
            Ok(())
        }

        ApiProtocol::RestXml => {
            let method = action_config.method.as_deref().unwrap_or("DELETE");
            let path_template = action_config
                .path
                .as_ref()
                .ok_or_else(|| anyhow!("REST-XML action requires 'path' field"))?;

            let path = path_template.replace("{resource_id}", resource_id);

            clients
                .http
                .rest_xml_request(service, method, &path, None)
                .await?;
            Ok(())
        }
    }
}

// =============================================================================
// Data-Driven Describe
// =============================================================================

/// Fill a describe `body_template`.
///
/// `{resource_id}` is the row's id field. `{arn_name}` and `{arn_id}` are the last
/// two segments of an ARN, which is how to reach an API that wants a name and an id
/// together: WAFv2's GetWebACL takes Name, Id and Scope, and the list call hands back
/// only an ARN carrying both.
fn render_describe_body(template: &str, resource_id: &str) -> Result<String> {
    let mut body = template.replace("{resource_id}", resource_id);

    if body.contains("{arn_name}") || body.contains("{arn_id}") {
        let (name, id) = arn_name_and_id(resource_id)?;
        body = body.replace("{arn_name}", name).replace("{arn_id}", id);
    }

    Ok(body)
}

/// Name and id out of an ARN shaped like
/// `arn:aws:wafv2:eu-west-1:123456789012:regional/webacl/<name>/<id>`.
///
/// Checks the whole shape rather than just counting back two segments, so a bare id
/// or a truncated ARN is refused instead of yielding two nonsense values.
fn arn_name_and_id(arn: &str) -> Result<(&str, &str)> {
    let segments: Vec<&str> = arn.split('/').collect();

    if !arn.starts_with("arn:") || segments.len() < 4 || segments.iter().any(|s| s.is_empty()) {
        return Err(anyhow!(
            "cannot read a name and id out of {:?}: expected an ARN ending in /<name>/<id>",
            arn
        ));
    }

    Ok((segments[segments.len() - 2], segments[segments.len() - 1]))
}

/// Describe a single resource using JSON configuration
async fn invoke_describe(
    resource_key: &str,
    clients: &AwsClients,
    resource_id: &str,
) -> Result<Value> {
    let resource_def =
        get_resource(resource_key).ok_or_else(|| anyhow!("Unknown resource: {}", resource_key))?;

    let describe_config = resource_def
        .describe_config
        .as_ref()
        .ok_or_else(|| anyhow!("Describe not configured for {}", resource_key))?;

    let service = describe_config
        .service_name
        .as_deref()
        .unwrap_or(&resource_def.service);

    debug!(
        "Describing resource: {} with id: {} (service: {}, protocol: {:?})",
        resource_key, resource_id, service, describe_config.protocol
    );

    let mut result = match describe_config.protocol {
        ApiProtocol::Query => {
            let action_name = describe_config
                .action
                .as_ref()
                .ok_or_else(|| anyhow!("Query describe requires 'action' field"))?;

            let id_param = describe_config.id_param.as_deref().unwrap_or("Id");
            let xml = clients
                .http
                .query_request(service, action_name, &[(id_param, resource_id)])
                .await?;
            let json = xml_to_json(&xml)?;

            // Extract from response path
            if let Some(ref path) = describe_config.response_path {
                extract_single_item(&json, path)?
            } else {
                json
            }
        }

        ApiProtocol::Json => {
            let action_name = describe_config
                .action
                .as_ref()
                .ok_or_else(|| anyhow!("JSON describe requires 'action' field"))?;

            let body = if let Some(ref template) = describe_config.body_template {
                render_describe_body(template, resource_id)?
            } else {
                let id_param = describe_config.id_param.as_deref().unwrap_or("id");
                json!({ id_param: resource_id }).to_string()
            };

            let response = clients
                .http
                .json_request(service, action_name, &body)
                .await?;
            let json: Value = serde_json::from_str(&response)?;

            if let Some(ref path) = describe_config.response_path {
                json.pointer(path).cloned().unwrap_or(json)
            } else {
                json
            }
        }

        ApiProtocol::RestJson => {
            let method = describe_config.method.as_deref().unwrap_or("GET");
            let path_template = describe_config
                .path
                .as_ref()
                .ok_or_else(|| anyhow!("REST-JSON describe requires 'path' field"))?;

            let path = path_template.replace("{resource_id}", resource_id);
            let response = clients
                .http
                .rest_json_request(service, method, &path, None)
                .await?;
            let json: Value = serde_json::from_str(&response)?;

            if let Some(ref resp_path) = describe_config.response_path {
                json.pointer(resp_path).cloned().unwrap_or(json)
            } else {
                json
            }
        }

        ApiProtocol::RestXml => {
            let method = describe_config.method.as_deref().unwrap_or("GET");
            let path_template = describe_config
                .path
                .as_ref()
                .ok_or_else(|| anyhow!("REST-XML describe requires 'path' field"))?;

            let path = path_template.replace("{resource_id}", resource_id);
            let xml = clients
                .http
                .rest_xml_request(service, method, &path, None)
                .await?;
            let json = xml_to_json(&xml)?;

            if let Some(ref resp_path) = describe_config.response_path {
                json.pointer(resp_path).cloned().unwrap_or(json)
            } else {
                json
            }
        }
    };

    // Handle enrich calls (additional API calls to add more data)
    for enrich in &describe_config.enrich_calls {
        let enrich_result = execute_enrich_call(
            clients,
            service,
            resource_id,
            enrich,
            &describe_config.protocol,
        )
        .await;
        match enrich_result {
            Ok(value) => {
                if let Value::Object(ref mut map) = result {
                    map.insert(enrich.result_field.clone(), value);
                }
            }
            Err(_) => {
                if let Some(ref default) = enrich.default_value {
                    if let Value::Object(ref mut map) = result {
                        map.insert(enrich.result_field.clone(), json!(default));
                    }
                }
            }
        }
    }

    Ok(result)
}

/// Execute an enrichment call for describe
async fn execute_enrich_call(
    clients: &AwsClients,
    service: &str,
    resource_id: &str,
    enrich: &super::protocol::EnrichCall,
    _protocol: &ApiProtocol,
) -> Result<Value> {
    // For now, support REST-XML S3 style enrich calls
    if let Some(ref path) = enrich.path {
        let path = path.replace("{resource_id}", resource_id);
        let method = enrich.method.as_deref().unwrap_or("GET");

        let xml = clients
            .http
            .rest_xml_request(service, method, &path, None)
            .await?;
        let json = xml_to_json(&xml)?;

        if let Some(ref extract) = enrich.extract_path {
            Ok(json.pointer(extract).cloned().unwrap_or(Value::Null))
        } else {
            Ok(json)
        }
    } else {
        Err(anyhow!("Enrich call requires path"))
    }
}

/// Extract a single item from a response that may be array or object
fn extract_single_item(json: &Value, path: &str) -> Result<Value> {
    let value = json
        .pointer(path)
        .ok_or_else(|| anyhow!("Response path not found: {}", path))?;

    match value {
        Value::Array(arr) => arr
            .first()
            .cloned()
            .ok_or_else(|| anyhow!("Empty response")),
        obj @ Value::Object(_) => Ok(obj.clone()),
        _ => Ok(value.clone()),
    }
}

// =============================================================================
// Unified Action Execution
// =============================================================================

/// Execute an action on a resource (start, stop, terminate, etc.)
/// Uses JSON config to execute the action.
pub async fn execute_action(
    service: &str,
    action: &str,
    clients: &AwsClients,
    resource_id: &str,
) -> Result<()> {
    let (resource_key, _) = find_resource_with_action(service, action).ok_or_else(|| {
        anyhow!(
            "Action '{}' not configured for service '{}'. Add action_configs to the resource JSON.",
            action,
            service
        )
    })?;

    invoke_action(&resource_key, action, clients, resource_id).await
}

/// Execute an action that returns data to display (e.g., get_secret_value)
/// These are read-only operations that retrieve and display data.
pub async fn execute_action_with_result(
    service: &str,
    action: &str,
    clients: &AwsClients,
    resource_id: &str,
) -> Result<Value> {
    match (service, action) {
        // Secrets Manager - Get Secret Value
        ("secretsmanager", "get_secret_value") => {
            let response = clients
                .http
                .json_request(
                    "secretsmanager",
                    "GetSecretValue",
                    &json!({
                        "SecretId": resource_id
                    })
                    .to_string(),
                )
                .await?;
            let json: Value = serde_json::from_str(&response)?;
            Ok(json)
        }

        // SSM - Get Parameter Value (with decryption for SecureString)
        ("ssm", "get_parameter") => {
            let response = clients
                .http
                .json_request(
                    "ssm",
                    "GetParameter",
                    &json!({
                        "Name": resource_id,
                        "WithDecryption": true
                    })
                    .to_string(),
                )
                .await?;
            let json: Value = serde_json::from_str(&response)?;
            Ok(json)
        }

        _ => Err(anyhow!(
            "Unknown action with result: {}.{}",
            service,
            action
        )),
    }
}

/// Find a resource that has the given action configured
fn find_resource_with_action(
    service: &str,
    action_id: &str,
) -> Option<(String, &'static super::registry::ResourceDef)> {
    use super::registry::get_registry;

    for (key, resource) in &get_registry().resources {
        if resource.service == service && resource.action_configs.contains_key(action_id) {
            return Some((key.clone(), resource));
        }
    }
    None
}

// =============================================================================
// Describe Function
// =============================================================================

/// Fetch full details for a single resource by ID
/// Uses JSON config, with special handling for S3 buckets.
pub async fn describe_resource(
    resource_key: &str,
    clients: &AwsClients,
    resource_id: &str,
) -> Result<Value> {
    // S3 buckets need special handling for region resolution
    if resource_key == "s3-buckets" {
        return describe_s3_bucket(clients, resource_id).await;
    }

    let resource =
        get_resource(resource_key).ok_or_else(|| anyhow!("Unknown resource: {}", resource_key))?;

    if resource.describe_config.is_none() {
        return Err(anyhow!(
            "Describe not configured for '{}'. Add describe_config to the resource JSON.",
            resource_key
        ));
    }

    invoke_describe(resource_key, clients, resource_id).await
}

/// Special handler for S3 bucket describe (needs region resolution)
async fn describe_s3_bucket(clients: &AwsClients, bucket_name: &str) -> Result<Value> {
    let mut result = json!({
        "BucketName": bucket_name,
    });

    // Get bucket location first (this determines the region for other calls)
    let bucket_region = clients
        .http
        .get_bucket_region(bucket_name)
        .await
        .unwrap_or_else(|_| "us-east-1".to_string());
    result["Region"] = json!(&bucket_region);

    // Get bucket versioning
    if let Ok(xml) = clients
        .http
        .rest_xml_request_s3_bucket("GET", bucket_name, "?versioning", None, &bucket_region)
        .await
    {
        if let Ok(json) = xml_to_json(&xml) {
            let status = json
                .pointer("/VersioningConfiguration/Status")
                .and_then(|v| v.as_str())
                .unwrap_or("Disabled");
            result["Versioning"] = json!(status);
        }
    }

    // Get bucket encryption
    if let Ok(xml) = clients
        .http
        .rest_xml_request_s3_bucket("GET", bucket_name, "?encryption", None, &bucket_region)
        .await
    {
        if let Ok(json) = xml_to_json(&xml) {
            if let Some(rules) = json.pointer("/ServerSideEncryptionConfiguration/Rule") {
                result["Encryption"] = rules.clone();
            }
        }
    } else {
        result["Encryption"] = json!("None");
    }

    Ok(result)
}

// =============================================================================
// Tests
// =============================================================================

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

    #[test]
    fn test_unknown_resource_has_no_api_config() {
        assert!(get_resource("nonexistent-resource").is_none());
    }

    #[test]
    fn test_dynamodb_tables_has_api_config() {
        let resource = get_resource("dynamodb-tables").unwrap();
        assert!(resource.has_api_config());
    }

    #[test]
    fn test_ec2_instances_has_api_config() {
        let resource = get_resource("ec2-instances").unwrap();
        assert!(resource.has_api_config());
    }

    #[test]
    fn test_lambda_functions_has_api_config() {
        let resource = get_resource("lambda-functions").unwrap();
        assert!(resource.has_api_config());
    }

    #[test]
    fn test_iam_users_has_api_config() {
        let resource = get_resource("iam-users").unwrap();
        assert!(resource.has_api_config());
    }

    #[test]
    fn test_redshift_clusters_has_api_config() {
        let resource = get_resource("redshift-clusters").unwrap();
        assert!(resource.has_api_config());
    }

    #[test]
    fn test_resolve_static_param_template_replaces_all_placeholders() {
        let out = resolve_static_param_template(
            "orbit-{resource_id}-{timestamp}",
            "test-cluster",
            "20260309T143000",
        );
        assert_eq!(out, "orbit-test-cluster-20260309T143000");
    }

    #[test]
    fn test_resolve_static_param_template_keeps_plain_text() {
        let out = resolve_static_param_template("fixed-value", "x", "y");
        assert_eq!(out, "fixed-value");
    }

    #[test]
    fn describe_body_fills_the_resource_id() {
        let body = render_describe_body("{\"TableName\": \"{resource_id}\"}", "orders").unwrap();
        assert_eq!(body, "{\"TableName\": \"orders\"}");
    }

    /// WAFv2's GetWebACL wants Name, Id and Scope together, and the list call only
    /// hands back an ARN holding both.
    #[test]
    fn describe_body_splits_a_wafv2_arn_into_name_and_id() {
        let arn = "arn:aws:wafv2:eu-west-1:123456789012:regional/webacl/prod-edge/0f1e2d3c-4b5a-6978-8796-a5b4c3d2e1f0";
        let body = render_describe_body(
            "{\"Name\": \"{arn_name}\", \"Id\": \"{arn_id}\", \"Scope\": \"REGIONAL\"}",
            arn,
        )
        .unwrap();
        assert_eq!(
            body,
            "{\"Name\": \"prod-edge\", \"Id\": \"0f1e2d3c-4b5a-6978-8796-a5b4c3d2e1f0\", \"Scope\": \"REGIONAL\"}"
        );
    }

    /// Substituting nothing would send a literal "{arn_name}" to AWS and report its
    /// confusing rejection as the resource's problem. Fail here instead, naming the
    /// id we could not split.
    #[test]
    fn describe_body_rejects_an_id_that_is_not_an_arn_with_a_name_and_id() {
        for id in [
            "prod-edge",
            "arn:aws:wafv2:eu-west-1:123456789012:regional/webacl",
            "",
        ] {
            let err = render_describe_body("{\"Name\": \"{arn_name}\"}", id)
                .expect_err("should refuse to guess a name");
            assert!(
                err.to_string().contains(id) || id.is_empty(),
                "error {:?} should name the id {:?}",
                err.to_string(),
                id
            );
        }
    }

    #[test]
    fn test_extract_param_variants() {
        use serde_json::json;

        // Test single string value
        let params_str = json!({ "bucket": "my-bucket" });
        assert_eq!(extract_param(&params_str, "bucket"), "my-bucket");

        // Test array with single string
        let params_single_arr = json!({ "bucket": ["only-bucket"] });
        assert_eq!(extract_param(&params_single_arr, "bucket"), "only-bucket");

        // Test array of strings (takes first)
        let params_arr = json!({ "bucket": ["first-bucket", "second-bucket"] });
        assert_eq!(extract_param(&params_arr, "bucket"), "first-bucket");

        // Test missing key
        assert_eq!(extract_param(&params_str, "nonexistent"), "");
    }
}