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
// Smart API Exploration - Help users find operations quickly
// Searches across operation names, descriptions, paths, and tags

use crate::cli::{ExploreCommand, ExploreFormat};
use crate::core::output::is_json_mode;
use crate::core::parser::{parse_spec, UnifiedOperation, UnifiedSpec};
use anyhow::Result;
use colored::*;
use std::collections::HashMap;
use std::path::{Path, PathBuf};

pub fn explore_command(cmd: ExploreCommand) -> 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")
        }
    });

    // Explore operations
    let results = explore_operations(&spec_path, &cmd.keyword)?;

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

    // Display results based on format
    match format {
        ExploreFormat::Pretty => {
            display_explore_results(&results, &cmd.keyword, cmd.limit);
        }
        ExploreFormat::Simple => {
            display_simple_results(&results, &cmd.keyword);
        }
        ExploreFormat::Json => {
            display_json_results(&results)?;
        }
    }

    Ok(())
}

pub struct ExploreResult {
    pub operation: UnifiedOperation,
    pub relevance_score: f32,
    pub matched_fields: Vec<String>,
}

pub fn explore_operations(
    spec_path: &std::path::Path,
    keyword: &str,
) -> Result<Vec<ExploreResult>> {
    // Load and parse the spec
    let spec_content = std::fs::read_to_string(spec_path)?;
    let spec = parse_spec(&spec_content)?;

    // Search operations
    let results = search_operations(&spec, keyword);

    Ok(results)
}

fn search_operations(spec: &UnifiedSpec, keyword: &str) -> Vec<ExploreResult> {
    let keyword_lower = keyword.to_lowercase();
    let mut results = Vec::new();

    for operation in &spec.operations {
        let mut score = 0.0;
        let mut matched_fields = Vec::new();

        // Check operation ID (highest weight)
        if operation
            .operation_id
            .to_lowercase()
            .contains(&keyword_lower)
        {
            score += 3.0;
            matched_fields.push("operation_id".to_string());
        }

        // Check path (high weight)
        if operation.path.to_lowercase().contains(&keyword_lower) {
            score += 2.5;
            matched_fields.push("path".to_string());
        }

        // Check method
        if operation.method.to_lowercase().contains(&keyword_lower) {
            score += 1.5;
            matched_fields.push("method".to_string());
        }

        // Check summary
        if let Some(summary) = &operation.summary {
            if summary.to_lowercase().contains(&keyword_lower) {
                score += 2.0;
                matched_fields.push("summary".to_string());
            }
        }

        // Check description
        if let Some(desc) = &operation.description {
            if desc.to_lowercase().contains(&keyword_lower) {
                score += 1.0;
                matched_fields.push("description".to_string());
            }
        }

        // Check parameters
        for param in &operation.parameters {
            if param.name.to_lowercase().contains(&keyword_lower) {
                score += 0.5;
                matched_fields.push(format!("parameter:{}", param.name));
            }
        }

        // If we have any matches, add to results
        if score > 0.0 {
            results.push(ExploreResult {
                operation: operation.clone(),
                relevance_score: score,
                matched_fields,
            });
        }
    }

    // Sort by relevance score (highest first)
    results.sort_by(|a, b| b.relevance_score.partial_cmp(&a.relevance_score).unwrap());

    results
}

pub fn display_explore_results(results: &[ExploreResult], keyword: &str, limit: usize) {
    if results.is_empty() {
        println!("❌ No operations found matching '{}'", keyword.red());
        return;
    }

    println!(
        "\n🔍 Found {} operations matching '{}':\n",
        results.len().to_string().green(),
        keyword.cyan()
    );

    // Group by similarity/category if possible
    let grouped = group_by_category(results);

    for (category, ops) in grouped {
        if !category.is_empty() {
            println!("{}", format!("📁 {}", category).bright_blue().bold());
        }

        for (idx, result) in ops.iter().take(limit).enumerate() {
            display_single_result(idx + 1, result, keyword);
        }

        if ops.len() > limit {
            println!("   ... and {} more in this category", ops.len() - limit);
        }
        println!();
    }

    // Show usage hint
    println!(
        "{}",
        "💡 Use 'mrapids show <operation>' to see details".dimmed()
    );
}

fn display_single_result(num: usize, result: &ExploreResult, keyword: &str) {
    let op = &result.operation;

    // Highlight the keyword in the output
    let highlighted_id = highlight_keyword(&op.operation_id, keyword);
    let highlighted_path = highlight_keyword(&op.path, keyword);

    println!(
        "  {} {} {}",
        format!("{}.", num).dimmed(),
        format!("{} {}", op.method.bright_green(), highlighted_path).bold(),
        format!("[{}]", highlighted_id).bright_cyan()
    );

    // Show summary if it contains the keyword
    if let Some(summary) = &op.summary {
        if summary.to_lowercase().contains(&keyword.to_lowercase()) {
            let highlighted_summary = highlight_keyword(summary, keyword);
            println!("     {}", highlighted_summary.dimmed());
        } else {
            // Show truncated summary
            let truncated = if summary.len() > 60 {
                format!("{}...", &summary[..60])
            } else {
                summary.clone()
            };
            println!("     {}", truncated.dimmed());
        }
    }

    // Show what matched
    println!(
        "     {} {}",
        "Matched:".bright_black(),
        result.matched_fields.join(", ").bright_black()
    );
}

fn highlight_keyword(text: &str, keyword: &str) -> String {
    // Case-insensitive highlighting
    let lower_text = text.to_lowercase();
    let lower_keyword = keyword.to_lowercase();

    if let Some(pos) = lower_text.find(&lower_keyword) {
        let (before, rest) = text.split_at(pos);
        let (matched, after) = rest.split_at(keyword.len());
        format!("{}{}{}", before, matched.bright_yellow().bold(), after)
    } else {
        text.to_string()
    }
}

fn group_by_category(results: &[ExploreResult]) -> Vec<(String, Vec<&ExploreResult>)> {
    let mut groups: HashMap<String, Vec<&ExploreResult>> = HashMap::new();

    for result in results {
        let category = extract_category(&result.operation);
        groups.entry(category).or_insert_with(Vec::new).push(result);
    }

    // Sort groups by total relevance
    let mut sorted_groups: Vec<_> = groups.into_iter().collect();
    sorted_groups.sort_by(|a, b| {
        let a_score: f32 = a.1.iter().map(|r| r.relevance_score).sum();
        let b_score: f32 = b.1.iter().map(|r| r.relevance_score).sum();
        b_score.partial_cmp(&a_score).unwrap()
    });

    sorted_groups
}

fn extract_category(operation: &UnifiedOperation) -> String {
    // Extract category from path or operation ID
    // Examples: /users/{id} -> Users, /products/{id}/reviews -> Products

    let path_parts: Vec<&str> = operation
        .path
        .split('/')
        .filter(|s| !s.is_empty())
        .collect();

    if let Some(first_part) = path_parts.first() {
        // Skip if it's a parameter
        if !first_part.starts_with('{') {
            return capitalize_first(first_part);
        }
    }

    // Try to extract from operation ID
    // getPetById -> Pet, createUser -> User
    let op_id_lower = operation.operation_id.to_lowercase();

    let categories = [
        "user", "pet", "order", "product", "payment", "customer", "account",
    ];
    for cat in &categories {
        if op_id_lower.contains(cat) {
            return capitalize_first(cat);
        }
    }

    "General".to_string()
}

fn capitalize_first(s: &str) -> String {
    let mut chars = s.chars();
    match chars.next() {
        None => String::new(),
        Some(first) => first.to_uppercase().chain(chars).collect(),
    }
}

fn display_simple_results(results: &[ExploreResult], keyword: &str) {
    if results.is_empty() {
        println!("No operations found matching '{}'", keyword);
        return;
    }

    for result in results {
        let op = &result.operation;
        println!("{} {} [{}]", op.method, op.path, op.operation_id);
    }
}

fn display_json_results(results: &[ExploreResult]) -> Result<()> {
    let json_results: Vec<_> = results
        .iter()
        .map(|r| {
            serde_json::json!({
                "operation_id": r.operation.operation_id,
                "method": r.operation.method,
                "path": r.operation.path,
                "summary": r.operation.summary,
                "relevance_score": r.relevance_score,
                "matched_fields": r.matched_fields,
            })
        })
        .collect();

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::parser::{
        ApiInfo, ParameterLocation, SchemaType, UnifiedParameter, UnifiedSchema,
    };

    // Helper function to create a test operation
    fn create_test_operation(
        id: &str,
        method: &str,
        path: &str,
        summary: Option<&str>,
    ) -> UnifiedOperation {
        UnifiedOperation {
            operation_id: id.to_string(),
            method: method.to_string(),
            path: path.to_string(),
            summary: summary.map(|s| s.to_string()),
            description: None,
            tags: vec![],
            parameters: vec![],
            request_body: None,
            responses: HashMap::new(),
            security: None,
        }
    }

    fn create_test_spec(operations: Vec<UnifiedOperation>) -> UnifiedSpec {
        UnifiedSpec {
            info: ApiInfo {
                title: "Test API".to_string(),
                version: "1.0.0".to_string(),
                description: None,
            },
            base_url: "https://api.test.com".to_string(),
            operations,
            security_schemes: HashMap::new(),
        }
    }

    // ============================================================================
    // capitalize_first tests
    // ============================================================================

    #[test]
    fn test_capitalize_first_simple() {
        assert_eq!(capitalize_first("hello"), "Hello");
        assert_eq!(capitalize_first("world"), "World");
    }

    #[test]
    fn test_capitalize_first_empty() {
        assert_eq!(capitalize_first(""), "");
    }

    #[test]
    fn test_capitalize_first_already_uppercase() {
        assert_eq!(capitalize_first("Hello"), "Hello");
    }

    #[test]
    fn test_capitalize_first_single_char() {
        assert_eq!(capitalize_first("a"), "A");
    }

    // ============================================================================
    // highlight_keyword tests
    // ============================================================================

    #[test]
    fn test_highlight_keyword_found() {
        let result = highlight_keyword("getUserById", "user");
        // Should contain the keyword (highlighting adds ANSI codes)
        assert!(result.contains("User") || result.contains("user"));
    }

    #[test]
    fn test_highlight_keyword_not_found() {
        let result = highlight_keyword("getUserById", "pet");
        assert_eq!(result, "getUserById");
    }

    #[test]
    fn test_highlight_keyword_case_insensitive() {
        let result = highlight_keyword("getUserById", "USER");
        // Should find "User" even with uppercase keyword
        assert!(result.len() > "getUserById".len() || result.contains("User"));
    }

    // ============================================================================
    // extract_category tests
    // ============================================================================

    #[test]
    fn test_extract_category_from_path() {
        let op = create_test_operation("getUser", "GET", "/users/{id}", None);
        assert_eq!(extract_category(&op), "Users");
    }

    #[test]
    fn test_extract_category_from_operation_id() {
        let op = create_test_operation("getPetById", "GET", "/{id}", None);
        assert_eq!(extract_category(&op), "Pet");
    }

    #[test]
    fn test_extract_category_general() {
        let op = create_test_operation("healthCheck", "GET", "/health", None);
        // "health" is not in the known categories, so should return "Health" from path
        assert_eq!(extract_category(&op), "Health");
    }

    #[test]
    fn test_extract_category_products() {
        let op = create_test_operation("listProducts", "GET", "/products", None);
        assert_eq!(extract_category(&op), "Products");
    }

    // ============================================================================
    // search_operations tests
    // ============================================================================

    #[test]
    fn test_search_operations_by_operation_id() {
        let ops = vec![
            create_test_operation("getUser", "GET", "/users/{id}", None),
            create_test_operation("listPets", "GET", "/pets", None),
        ];
        let spec = create_test_spec(ops);

        let results = search_operations(&spec, "user");
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].operation.operation_id, "getUser");
        assert!(results[0]
            .matched_fields
            .contains(&"operation_id".to_string()));
    }

    #[test]
    fn test_search_operations_by_path() {
        let ops = vec![
            create_test_operation("getItem", "GET", "/users/{id}", None),
            create_test_operation("getPet", "GET", "/pets/{id}", None),
        ];
        let spec = create_test_spec(ops);

        let results = search_operations(&spec, "user");
        assert_eq!(results.len(), 1);
        assert!(results[0].matched_fields.contains(&"path".to_string()));
    }

    #[test]
    fn test_search_operations_by_method() {
        let ops = vec![
            create_test_operation("createUser", "POST", "/users", None),
            create_test_operation("getUser", "GET", "/users/{id}", None),
        ];
        let spec = create_test_spec(ops);

        let results = search_operations(&spec, "post");
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].operation.method, "POST");
    }

    #[test]
    fn test_search_operations_by_summary() {
        let ops = vec![
            create_test_operation("op1", "GET", "/a", Some("Create a new user")),
            create_test_operation("op2", "GET", "/b", Some("List pets")),
        ];
        let spec = create_test_spec(ops);

        let results = search_operations(&spec, "user");
        assert_eq!(results.len(), 1);
        assert!(results[0].matched_fields.contains(&"summary".to_string()));
    }

    #[test]
    fn test_search_operations_multiple_matches() {
        let ops = vec![
            create_test_operation("getUser", "GET", "/users/{id}", Some("Get a user")),
            create_test_operation("createUser", "POST", "/users", Some("Create user")),
            create_test_operation("listPets", "GET", "/pets", None),
        ];
        let spec = create_test_spec(ops);

        let results = search_operations(&spec, "user");
        assert_eq!(results.len(), 2);
    }

    #[test]
    fn test_search_operations_no_matches() {
        let ops = vec![create_test_operation("listPets", "GET", "/pets", None)];
        let spec = create_test_spec(ops);

        let results = search_operations(&spec, "user");
        assert!(results.is_empty());
    }

    #[test]
    fn test_search_operations_sorted_by_relevance() {
        let ops = vec![
            // Lower score - only path match
            create_test_operation("op1", "GET", "/users", None),
            // Higher score - operation_id match
            create_test_operation("getUser", "GET", "/other", None),
        ];
        let spec = create_test_spec(ops);

        let results = search_operations(&spec, "user");
        assert_eq!(results.len(), 2);
        // getUser should be first (higher score for operation_id match)
        assert_eq!(results[0].operation.operation_id, "getUser");
    }

    #[test]
    fn test_search_operations_case_insensitive() {
        let ops = vec![create_test_operation(
            "GetUserById",
            "GET",
            "/Users/{id}",
            None,
        )];
        let spec = create_test_spec(ops);

        let results = search_operations(&spec, "USER");
        assert_eq!(results.len(), 1);
    }

    #[test]
    fn test_search_operations_with_parameters() {
        let mut op = create_test_operation("getItem", "GET", "/items/{id}", None);
        op.parameters = vec![UnifiedParameter {
            name: "userId".to_string(),
            location: ParameterLocation::Query,
            required: false,
            schema: UnifiedSchema {
                schema_type: SchemaType::String,
                ..Default::default()
            },
            description: None,
            example: None,
        }];
        let spec = create_test_spec(vec![op]);

        let results = search_operations(&spec, "user");
        assert_eq!(results.len(), 1);
        assert!(results[0]
            .matched_fields
            .iter()
            .any(|f| f.contains("parameter")));
    }

    // ============================================================================
    // group_by_category tests
    // ============================================================================

    #[test]
    fn test_group_by_category_groups_correctly() {
        let ops = vec![
            create_test_operation("getUser", "GET", "/users/{id}", None),
            create_test_operation("listUsers", "GET", "/users", None),
            create_test_operation("getPet", "GET", "/pets/{id}", None),
        ];
        let spec = create_test_spec(ops);

        let results = search_operations(&spec, "get");
        let groups = group_by_category(&results);

        // Should have 2 categories: Users and Pets
        assert_eq!(groups.len(), 2);
    }

    // ============================================================================
    // ExploreResult tests
    // ============================================================================

    #[test]
    fn test_explore_result_structure() {
        let op = create_test_operation("test", "GET", "/test", Some("Test summary"));
        let result = ExploreResult {
            operation: op,
            relevance_score: 2.5,
            matched_fields: vec!["operation_id".to_string(), "path".to_string()],
        };

        assert_eq!(result.relevance_score, 2.5);
        assert_eq!(result.matched_fields.len(), 2);
    }
}