mrapids 0.1.31

Your OpenAPI, but executable
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
use crate::cli::{ShowCommand, ShowFormat};
use crate::core::api::ApiError;
use crate::core::examples::generate_smart_example;
use crate::core::output::is_json_mode;
use crate::core::parser::{
    parse_spec, ParameterLocation, SchemaType, UnifiedOperation as Operation,
    UnifiedParameter as Parameter, UnifiedSchema as Schema, UnifiedSpec,
};
use crate::utils::security::validate_file_path;
use anyhow::{Context, Result};
use colored::*;
use std::path::{Path, PathBuf};

pub fn show_command(cmd: ShowCommand) -> Result<()> {
    // Determine spec file path
    let spec_path = cmd.spec.unwrap_or_else(|| {
        // Try common locations
        if Path::new("specs/api.yaml").exists() {
            PathBuf::from("specs/api.yaml")
        } else if Path::new("specs/api.yml").exists() {
            PathBuf::from("specs/api.yml")
        } else if Path::new("specs/api.json").exists() {
            PathBuf::from("specs/api.json")
        } else if Path::new("api.yaml").exists() {
            PathBuf::from("api.yaml")
        } else {
            PathBuf::from("openapi.yaml")
        }
    });

    // Validate spec file path
    validate_file_path(&spec_path)?;

    // Load and parse the spec
    let spec_content = std::fs::read_to_string(&spec_path)
        .with_context(|| format!("Failed to read spec file: {}", spec_path.display()))?;

    let spec = parse_spec(&spec_content)?;

    // Find the operation
    let operation_id = normalize_operation_id(&cmd.operation);
    let operation = find_operation(&spec, &operation_id)?;

    // Check if template generation is requested
    if cmd.template {
        return display_template(operation, &spec);
    }

    // Global --json flag overrides per-command format
    let format = if is_json_mode() {
        ShowFormat::Json
    } else {
        cmd.format
    };

    // Display based on format
    match format {
        ShowFormat::Pretty => {
            display_pretty(operation, &spec, cmd.examples);
            Ok(())
        }
        ShowFormat::Json => display_json(operation),
        ShowFormat::Yaml => display_yaml(operation),
    }
}

/// Find an operation by partial name match - public for use by run command
pub fn find_operation_with_spec<'a>(
    spec: &'a UnifiedSpec,
    operation_id: &str,
) -> Result<&'a Operation> {
    find_operation(spec, operation_id)
}

fn normalize_operation_id(id: &str) -> String {
    // Don't transform IDs with slashes - they're already valid operation IDs
    if id.contains('/') {
        return id.to_string();
    }

    // Convert kebab-case to camelCase if needed
    if id.contains('-') {
        id.split('-')
            .enumerate()
            .map(|(i, part)| {
                if i == 0 {
                    part.to_string()
                } else {
                    let mut chars = part.chars();
                    match chars.next() {
                        None => String::new(),
                        Some(first) => first.to_uppercase().chain(chars).collect(),
                    }
                }
            })
            .collect()
    } else {
        id.to_string()
    }
}

fn find_operation<'a>(
    spec: &'a crate::core::parser::UnifiedSpec,
    operation_id: &str,
) -> Result<&'a Operation> {
    let search_term = operation_id.to_lowercase();

    // Try exact match first (case-insensitive)
    if let Some(op) = spec
        .operations
        .iter()
        .find(|op| op.operation_id.to_lowercase() == search_term)
    {
        return Ok(op);
    }

    // Try converting kebab-case to camelCase
    let camel_case = normalize_operation_id(operation_id).to_lowercase();
    if let Some(op) = spec
        .operations
        .iter()
        .find(|op| op.operation_id.to_lowercase() == camel_case)
    {
        return Ok(op);
    }

    // Find all operations that contain the search term
    let matches: Vec<&Operation> = spec
        .operations
        .iter()
        .filter(|op| op.operation_id.to_lowercase().contains(&search_term))
        .collect();

    match matches.len() {
        0 => {
            // No matches - show available operations
            let available = spec
                .operations
                .iter()
                .map(|op| &op.operation_id)
                .take(10)
                .cloned()
                .collect::<Vec<_>>()
                .join(", ");

            Err(ApiError::OperationNotFound(format!(
                "No operation matching '{}' found. Available operations: {} {}",
                operation_id,
                available,
                if spec.operations.len() > 10 {
                    "..."
                } else {
                    ""
                }
            ))
            .into())
        }
        1 => {
            // Single match - use it
            if !is_json_mode() {
                println!(
                    "{} Found operation: {}",
                    "".green(),
                    matches[0].operation_id.bright_cyan()
                );
            }
            Ok(matches[0])
        }
        _ => {
            // Multiple matches - show them
            if !is_json_mode() {
                println!(
                    "{} Multiple operations match '{}':",
                    "?".yellow(),
                    operation_id
                );
                for (i, op) in matches.iter().enumerate() {
                    println!(
                        "  {} {}",
                        format!("{}.", i + 1).dimmed(),
                        op.operation_id.bright_cyan()
                    );
                }
            }
            Err(ApiError::ValidationError(format!(
                "Please be more specific. Found {} operations matching '{}'",
                matches.len(),
                operation_id
            ))
            .into())
        }
    }
}

fn display_pretty(operation: &Operation, spec: &UnifiedSpec, show_examples: bool) {
    // Header
    println!(
        "\n{} {}",
        operation.method.to_uppercase().bright_green().bold(),
        operation.path.bright_cyan()
    );

    // Summary
    if let Some(summary) = &operation.summary {
        println!("{}", summary.dimmed());
    }

    println!("{}", "".repeat(60).dimmed());

    // Authentication requirements
    if let Some(security_reqs) = &operation.security {
        if !security_reqs.is_empty() {
            println!("\n{}", "AUTHENTICATION:".bright_red().bold());
            for req in security_reqs {
                if let Some(scheme) = spec.security_schemes.get(&req.scheme_name) {
                    match scheme.scheme_type.as_str() {
                        "apiKey" => {
                            let location_str = match scheme.location.as_deref() {
                                Some("header") => "header",
                                Some("query") => "query parameter",
                                Some("cookie") => "cookie",
                                _ => "header",
                            };
                            println!(
                                "  {} API Key required: {} in {}",
                                "".bright_red(),
                                scheme.name.as_deref().unwrap_or("api_key").bright_yellow(),
                                location_str
                            );
                        }
                        "http" => match scheme.scheme.as_deref() {
                            Some("bearer") => {
                                println!(
                                    "  {} Bearer token required (Authorization: Bearer <token>)",
                                    "".bright_red()
                                );
                            }
                            Some("basic") => {
                                println!(
                                    "  {} Basic auth required (Authorization: Basic <base64>)",
                                    "".bright_red()
                                );
                            }
                            _ => {
                                println!(
                                    "  {} HTTP {} authentication required",
                                    "".bright_red(),
                                    scheme.scheme.as_deref().unwrap_or("unknown")
                                );
                            }
                        },
                        "oauth2" => {
                            println!("  {} OAuth2 authentication required", "".bright_red());
                            if !req.scopes.is_empty() {
                                println!("    Scopes: {}", req.scopes.join(", ").bright_black());
                            }
                        }
                        _ => {
                            println!(
                                "  {} {} authentication required",
                                "".bright_red(),
                                req.scheme_name.bright_yellow()
                            );
                        }
                    }
                } else {
                    println!(
                        "  {} {} authentication required",
                        "".bright_red(),
                        req.scheme_name.bright_yellow()
                    );
                }
            }
        }
    }

    // Path parameters (always required)
    let path_params: Vec<_> = operation
        .parameters
        .iter()
        .filter(|p| p.location == ParameterLocation::Path)
        .collect();

    if !path_params.is_empty() {
        println!("\n{}", "PATH PARAMETERS:".bright_yellow().bold());
        for param in &path_params {
            display_parameter(param, true);
        }
    }

    // Query parameters
    let query_params: Vec<_> = operation
        .parameters
        .iter()
        .filter(|p| p.location == ParameterLocation::Query)
        .collect();

    if !query_params.is_empty() {
        println!("\n{}", "QUERY PARAMETERS:".bright_blue().bold());
        for param in query_params {
            display_parameter_with_usage(param, false);
        }
    }

    // Header parameters (excluding auth headers)
    let header_params: Vec<_> = operation
        .parameters
        .iter()
        .filter(|p| p.location == ParameterLocation::Header)
        .filter(|p| {
            !p.name.eq_ignore_ascii_case("authorization")
                && !p.name.eq_ignore_ascii_case("x-api-key")
        })
        .collect();

    if !header_params.is_empty() {
        println!("\n{}", "HEADER PARAMETERS:".bright_cyan().bold());
        for param in header_params {
            display_parameter(param, param.required);
        }
    }

    // Request body
    if let Some(body) = &operation.request_body {
        println!("\n{}", "REQUEST BODY:".bright_yellow().bold());
        if let Some((content_type, schema)) = body.content.iter().next() {
            println!("  Content-Type: {}", content_type.dimmed());
            display_schema(&schema.schema, "", body.required);
        }
    }

    // Example command
    println!("\n{}", "EXAMPLE:".bright_green().bold());
    let example = generate_example_command(operation);
    println!("  {}", example.cyan());

    // Show response example
    if show_examples {
        println!("\n{}", "EXPECTED RESPONSE:".bright_green().bold());
        for (status, response) in &operation.responses {
            if status.starts_with('2') {
                println!(
                    "  Status: {} {}",
                    status.bright_green(),
                    response.description.dimmed()
                );
                if let Some((content_type, schema)) = response.content.iter().next() {
                    println!("  Content-Type: {}", content_type.dimmed());
                    // Show simplified response schema
                    if let Ok(example) = generate_response_example(&schema.schema) {
                        println!(
                            "  {}",
                            serde_json::to_string_pretty(&example)
                                .unwrap_or_default()
                                .bright_black()
                        );
                    }
                }
                break;
            }
        }
    }
}

fn display_parameter(param: &Parameter, required: bool) {
    let req_indicator = if required { "*" } else { " " };
    let type_str = schema_type_string(&param.schema);
    let description = param.description.as_deref().unwrap_or("");
    let example = generate_example_value(&param.name, &param.schema);

    println!(
        "  {} {:<15} {:<10} {} {}",
        req_indicator.bright_red(),
        param.name.bright_white(),
        type_str.dimmed(),
        description.dimmed(),
        format!("(e.g. {})", example).bright_black()
    );
}

fn display_parameter_with_usage(param: &Parameter, required: bool) {
    let req_indicator = if required { "*" } else { " " };
    let type_str = schema_type_string(&param.schema);
    let description = param.description.as_deref().unwrap_or("");
    let example = generate_example_value(&param.name, &param.schema);

    // Determine the purpose based on parameter name
    let purpose = match param.name.to_lowercase().as_str() {
        "limit" | "per_page" | "page_size" => "Pagination",
        "offset" | "page" | "skip" => "Pagination",
        "sort" | "order_by" | "sort_by" => "Sorting",
        "order" | "sort_order" | "direction" => "Sort direction",
        "filter" | "status" | "state" | "type" => "Filtering",
        "search" | "q" | "query" => "Search",
        "fields" | "select" | "include" => "Field selection",
        _ => "",
    };

    // First line: parameter name and type, clearly visible
    print!(
        "  {} {:<20}",
        req_indicator.bright_red(),
        param.name.bright_white().bold()
    );

    // Add type
    print!("{:<15}", type_str.bright_cyan());

    // Add purpose tag if identified
    if !purpose.is_empty() {
        print!("[{}]", purpose.bright_green());
    }
    println!();

    // Second line: usage example (more prominent)
    println!(
        "{}",
        format!("?{}={}", param.name, example).bright_yellow()
    );

    // Third line: description (if present, less prominent)
    if !description.is_empty() {
        // Wrap long descriptions
        let desc_lines = wrap_text(description, 70);
        for (i, line) in desc_lines.iter().enumerate() {
            if i == 0 {
                println!("      {}", line.dimmed());
            } else {
                println!("        {}", line.dimmed());
            }
        }
    }

    // Add spacing between parameters
    println!();
}

fn display_schema(schema: &Schema, indent: &str, _required: bool) {
    match &schema.schema_type {
        SchemaType::Object => {
            if let Some(props) = &schema.properties {
                for (name, prop_schema) in props {
                    let is_required = schema
                        .required
                        .as_ref()
                        .map(|r| r.contains(name))
                        .unwrap_or(false);

                    let type_str = schema_type_string(prop_schema);
                    let req_indicator = if is_required { "*" } else { " " };
                    let example = generate_example_value(name, prop_schema);

                    println!(
                        "  {}{} {:<15} {:<10} {}",
                        indent,
                        req_indicator.bright_red(),
                        name.bright_white(),
                        type_str.dimmed(),
                        format!("(e.g. {})", example).bright_black()
                    );

                    // Nested objects
                    if matches!(&prop_schema.schema_type, SchemaType::Object) {
                        display_schema(prop_schema, &format!("{}  ", indent), is_required);
                    }
                }
            }
        }
        _ => {}
    }
}

fn schema_type_string(schema: &Schema) -> String {
    match &schema.schema_type {
        SchemaType::String => {
            if let Some(format) = &schema.format {
                format!("string({})", format)
            } else if let Some(enums) = &schema.enum_values {
                format!(
                    "enum[{}]",
                    enums
                        .iter()
                        .map(|v| v.to_string())
                        .collect::<Vec<_>>()
                        .join("|")
                )
            } else {
                "string".to_string()
            }
        }
        SchemaType::Number => "number".to_string(),
        SchemaType::Integer => "integer".to_string(),
        SchemaType::Boolean => "boolean".to_string(),
        SchemaType::Array => {
            if let Some(items) = &schema.items {
                format!("{}[]", schema_type_string(items))
            } else {
                "array".to_string()
            }
        }
        SchemaType::Object => "object".to_string(),
        SchemaType::Unknown => "unknown".to_string(),
    }
}

fn generate_example_value(field_name: &str, schema: &Schema) -> String {
    // Use our smart example generation
    let value = generate_smart_example(field_name, schema);

    // Convert JSON value to string representation
    match value {
        serde_json::Value::String(s) => s,
        serde_json::Value::Number(n) => n.to_string(),
        serde_json::Value::Bool(b) => b.to_string(),
        serde_json::Value::Null => "null".to_string(),
        serde_json::Value::Array(_) => value.to_string(),
        serde_json::Value::Object(_) => value.to_string(),
    }
}

fn generate_example_command(operation: &Operation) -> String {
    let mut cmd = format!("mrapids run {}", operation.operation_id);

    // Add required parameters using --param syntax
    for param in &operation.parameters {
        if param.required && param.location == ParameterLocation::Path {
            let example = generate_example_value(&param.name, &param.schema);
            cmd.push_str(&format!(" --param {}={}", param.name, example));
        }
    }

    // Add example body parameters if POST/PUT/PATCH
    if matches!(operation.method.as_str(), "post" | "put" | "patch") {
        if let Some(body) = &operation.request_body {
            if body.required {
                // Show a couple of required fields as examples
                if let Some((_, schema)) = body.content.iter().next() {
                    if let Some(props) = &schema.schema.properties {
                        let required_fields: Vec<_> = schema
                            .schema
                            .required
                            .as_ref()
                            .map(|r| r.iter().take(2).collect())
                            .unwrap_or_default();

                        for field in required_fields {
                            if let Some(field_schema) = props.get(field) {
                                let example = generate_example_value(field, field_schema);
                                cmd.push_str(&format!(" --{} {}", field, example));
                            }
                        }
                    }
                }
            }
        }
    }

    cmd
}

fn generate_response_example(schema: &Schema) -> Result<serde_json::Value> {
    use serde_json::json;

    match &schema.schema_type {
        SchemaType::Object => {
            let mut obj = serde_json::Map::new();
            if let Some(props) = &schema.properties {
                for (name, prop_schema) in props.iter().take(5) {
                    // Limit to first 5 properties
                    let value = generate_response_example(prop_schema)?;
                    obj.insert(name.clone(), value);
                }
            }
            Ok(json!(obj))
        }
        SchemaType::Array => {
            if let Some(items) = &schema.items {
                let item = generate_response_example(items)?;
                Ok(json!([item]))
            } else {
                Ok(json!([]))
            }
        }
        SchemaType::String => Ok(json!(generate_example_value("field", schema))),
        SchemaType::Integer => Ok(json!(123)),
        SchemaType::Number => Ok(json!(123.45)),
        SchemaType::Boolean => Ok(json!(true)),
        SchemaType::Unknown => Ok(json!(null)),
    }
}

fn display_json(operation: &Operation) -> Result<()> {
    use serde_json::json;

    // Build a JSON representation manually
    let mut params_json = vec![];
    for param in &operation.parameters {
        params_json.push(json!({
            "name": param.name,
            "location": match param.location {
                ParameterLocation::Path => "path",
                ParameterLocation::Query => "query",
                ParameterLocation::Header => "header",
                ParameterLocation::Cookie => "cookie",
            },
            "required": param.required,
            "type": param.schema.schema_type.to_string(),
            "description": param.description,
            "example": generate_example_value(&param.name, &param.schema),
        }));
    }

    // Build request body JSON if present
    let request_body_json = if let Some(rb) = &operation.request_body {
        let mut content_json = serde_json::Map::new();
        for (content_type, media_type) in &rb.content {
            let schema_json = schema_to_json(&media_type.schema);
            content_json.insert(
                content_type.clone(),
                json!({
                    "schema": schema_json,
                    "example": media_type.example.clone(),
                }),
            );
        }
        Some(json!({
            "required": rb.required,
            "content": content_json,
        }))
    } else {
        None
    };

    // Build security requirements
    let security_json = if let Some(sec_reqs) = &operation.security {
        let reqs: Vec<_> = sec_reqs
            .iter()
            .map(|req| {
                json!({
                    "scheme": req.scheme_name,
                    "scopes": req.scopes,
                })
            })
            .collect();
        Some(reqs)
    } else {
        None
    };

    // Build final JSON
    let output = json!({
        "operation_id": operation.operation_id,
        "method": operation.method,
        "path": operation.path,
        "summary": operation.summary,
        "description": operation.description,
        "parameters": params_json,
        "request_body": request_body_json,
        "security": security_json,
    });

    println!("{}", serde_json::to_string_pretty(&output)?);
    Ok(())
}

fn schema_to_json(schema: &Schema) -> serde_json::Value {
    use serde_json::json;

    let mut json_schema = json!({
        "type": schema.schema_type.to_string(),
    });

    if let Some(obj) = json_schema.as_object_mut() {
        if let Some(desc) = &schema.description {
            obj.insert("description".to_string(), json!(desc));
        }

        if let Some(format) = &schema.format {
            obj.insert("format".to_string(), json!(format));
        }

        if let Some(example) = &schema.example {
            obj.insert("example".to_string(), example.clone());
        }

        if let Some(default) = &schema.default {
            obj.insert("default".to_string(), default.clone());
        }

        if let Some(min) = schema.minimum {
            obj.insert("minimum".to_string(), json!(min));
        }

        if let Some(max) = schema.maximum {
            obj.insert("maximum".to_string(), json!(max));
        }

        if let Some(props) = &schema.properties {
            let mut props_json = serde_json::Map::new();
            for (name, prop_schema) in props {
                props_json.insert(name.clone(), schema_to_json(prop_schema));
            }
            obj.insert("properties".to_string(), json!(props_json));
        }

        if let Some(required) = &schema.required {
            obj.insert("required".to_string(), json!(required));
        }

        if let Some(items) = &schema.items {
            obj.insert("items".to_string(), schema_to_json(items));
        }
    }

    json_schema
}

fn display_yaml(operation: &Operation) -> Result<()> {
    // Convert to JSON first, then to YAML
    use serde_json::json;

    // Build the same structure as JSON
    let mut params_json = vec![];
    for param in &operation.parameters {
        params_json.push(json!({
            "name": param.name,
            "location": match param.location {
                ParameterLocation::Path => "path",
                ParameterLocation::Query => "query",
                ParameterLocation::Header => "header",
                ParameterLocation::Cookie => "cookie",
            },
            "required": param.required,
            "type": param.schema.schema_type.to_string(),
            "description": param.description,
            "example": generate_example_value(&param.name, &param.schema),
        }));
    }

    let request_body_json = if let Some(rb) = &operation.request_body {
        let mut content_json = serde_json::Map::new();
        for (content_type, media_type) in &rb.content {
            let schema_json = schema_to_json(&media_type.schema);
            content_json.insert(
                content_type.clone(),
                json!({
                    "schema": schema_json,
                    "example": media_type.example.clone(),
                }),
            );
        }
        Some(json!({
            "required": rb.required,
            "content": content_json,
        }))
    } else {
        None
    };

    let security_json = if let Some(sec_reqs) = &operation.security {
        let reqs: Vec<_> = sec_reqs
            .iter()
            .map(|req| {
                json!({
                    "scheme": req.scheme_name,
                    "scopes": req.scopes,
                })
            })
            .collect();
        Some(reqs)
    } else {
        None
    };

    let output = json!({
        "operation_id": operation.operation_id,
        "method": operation.method,
        "path": operation.path,
        "summary": operation.summary,
        "description": operation.description,
        "parameters": params_json,
        "request_body": request_body_json,
        "security": security_json,
    });

    println!("{}", serde_yaml::to_string(&output)?);
    Ok(())
}

fn wrap_text(text: &str, max_width: usize) -> Vec<String> {
    let words: Vec<&str> = text.split_whitespace().collect();
    let mut lines = Vec::new();
    let mut current_line = String::new();

    for word in words {
        if current_line.is_empty() {
            current_line.push_str(word);
        } else if current_line.len() + word.len() + 1 <= max_width {
            current_line.push(' ');
            current_line.push_str(word);
        } else {
            lines.push(current_line);
            current_line = word.to_string();
        }
    }

    if !current_line.is_empty() {
        lines.push(current_line);
    }

    lines
}

/// Display a JSON template for the operation
fn display_template(operation: &Operation, _spec: &UnifiedSpec) -> Result<()> {
    println!(
        "\n{} {} - Template Generation",
        operation.method.to_uppercase().bright_green().bold(),
        operation.path.bright_cyan()
    );

    if let Some(summary) = &operation.summary {
        println!("{}", summary.dimmed());
    }

    println!("{}", "".repeat(60).dimmed());

    // Generate the template
    let template = if let Some(request_body) = &operation.request_body {
        // Get the first content type's schema (usually application/json)
        if let Some(media_type) = request_body.content.values().next() {
            generate_template_from_schema(&media_type.schema, "body", false)?
        } else {
            serde_json::json!({})
        }
    } else {
        // No request body - generate from parameters
        let mut template_obj = serde_json::Map::new();

        // Add path parameters
        let path_params: Vec<_> = operation
            .parameters
            .iter()
            .filter(|p| p.location == ParameterLocation::Path)
            .collect();

        if !path_params.is_empty() {
            println!("\n{}", "PATH PARAMETERS (required):".bright_yellow());
            for param in &path_params {
                let example = generate_smart_example(&param.name, &param.schema);
                template_obj.insert(param.name.clone(), example);
                println!(
                    "{}: {}",
                    param.name.bright_white(),
                    param.description.as_deref().unwrap_or("")
                );
            }
        }

        // Add query parameters
        let query_params: Vec<_> = operation
            .parameters
            .iter()
            .filter(|p| p.location == ParameterLocation::Query)
            .collect();

        if !query_params.is_empty() {
            println!("\n{}", "QUERY PARAMETERS:".bright_cyan());
            for param in &query_params {
                let required_mark = if param.required { " (required)" } else { "" };
                let example = generate_smart_example(&param.name, &param.schema);
                template_obj.insert(param.name.clone(), example);
                println!(
                    "{}{}: {}",
                    param.name.bright_white(),
                    required_mark.bright_yellow(),
                    param.description.as_deref().unwrap_or("")
                );
            }
        }

        serde_json::Value::Object(template_obj)
    };

    // Display the template
    println!("\n{}", "JSON TEMPLATE:".bright_green().bold());
    let pretty_json = serde_json::to_string_pretty(&template)?;
    println!("{}", pretty_json.bright_white());

    // Show usage hint
    println!("\n{}", "USAGE:".bright_cyan().bold());
    println!("Save this template to a file and edit it:");
    println!("  1. Copy the JSON above to a file (e.g., request.json)");
    println!("  2. Edit the values as needed");
    println!(
        "  3. Run: mrapids run {} --data @request.json",
        operation.operation_id
    );

    Ok(())
}

/// Generate a template from a schema (reused from run.rs)
fn generate_template_from_schema(
    schema: &Schema,
    field_name: &str,
    minimal: bool,
) -> Result<serde_json::Value> {
    match &schema.schema_type {
        SchemaType::Object => {
            let mut obj = serde_json::Map::new();

            if let Some(properties) = &schema.properties {
                for (prop_name, prop_schema) in properties {
                    // Skip optional fields if minimal mode
                    let required_fields = schema
                        .required
                        .as_ref()
                        .map(|r| r.clone())
                        .unwrap_or_default();
                    if minimal && !required_fields.contains(prop_name) {
                        continue;
                    }

                    let value = generate_template_from_schema(prop_schema, prop_name, minimal)?;
                    obj.insert(prop_name.clone(), value);
                }
            }

            Ok(serde_json::Value::Object(obj))
        }
        SchemaType::Array => {
            // Generate a single example item
            let item = if let Some(items) = &schema.items {
                generate_template_from_schema(items, field_name, minimal)?
            } else {
                serde_json::json!("example")
            };
            Ok(serde_json::json!([item]))
        }
        _ => {
            // Use the existing smart example generator
            Ok(generate_smart_example(field_name, schema))
        }
    }
}