mockforge-plugin-core 0.3.116

Core plugin interfaces and types for MockForge extensible architecture
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
//! Client Generator Plugin Interface
//!
//! This module defines the traits and types for plugins that generate
//! framework-specific mock clients from OpenAPI specifications.

use crate::types::{PluginMetadata, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Client generator plugin trait for generating framework-specific mock clients
#[async_trait::async_trait]
pub trait ClientGeneratorPlugin {
    /// Get the framework name this plugin supports
    fn framework_name(&self) -> &str;

    /// Get the supported file extensions for this framework
    fn supported_extensions(&self) -> Vec<&str>;

    /// Generate mock client code from OpenAPI specification
    async fn generate_client(
        &self,
        spec: &OpenApiSpec,
        config: &ClientGeneratorConfig,
    ) -> Result<ClientGenerationResult>;

    /// Get plugin metadata
    async fn get_metadata(&self) -> PluginMetadata;

    /// Validate the plugin configuration
    async fn validate_config(&self, _config: &ClientGeneratorConfig) -> Result<()> {
        // Default implementation - plugins can override for custom validation
        Ok(())
    }
}

/// OpenAPI specification data structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OpenApiSpec {
    /// OpenAPI version (e.g., "3.0.0")
    pub openapi: String,
    /// API information
    pub info: ApiInfo,
    /// Server URLs
    pub servers: Option<Vec<Server>>,
    /// API paths and operations
    pub paths: HashMap<String, PathItem>,
    /// Component schemas
    pub components: Option<Components>,
}

/// API information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApiInfo {
    /// API title
    pub title: String,
    /// API version
    pub version: String,
    /// API description
    pub description: Option<String>,
}

/// Server information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Server {
    /// Server URL
    pub url: String,
    /// Server description
    pub description: Option<String>,
}

/// Path item containing operations
/// Note: We use #[serde(flatten)] for operations to handle HTTP methods (get, post, etc.)
/// as dynamic keys, while explicitly handling other OpenAPI PathItem fields
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct PathItem {
    /// HTTP operations (get, post, put, delete, patch, head, options, trace)
    /// These are flattened from the OpenAPI spec where HTTP methods appear as top-level keys
    #[serde(flatten)]
    pub operations: HashMap<String, Operation>,
    /// Optional summary for the path (OpenAPI PathItem field)
    /// This field is rarely used but must be handled to avoid deserialization errors
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub summary: Option<String>,
    /// Optional description for the path (OpenAPI PathItem field)
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub description: Option<String>,
    /// Optional parameters shared across all operations (OpenAPI PathItem field)
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub parameters: Option<Vec<serde_json::Value>>,
    /// Optional servers override (OpenAPI PathItem field)
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub servers: Option<Vec<serde_json::Value>>,
    /// Optional $ref (OpenAPI PathItem field) - when present, the path item is a reference
    #[serde(rename = "$ref", skip_serializing_if = "Option::is_none", default)]
    pub ref_path: Option<String>,
}

/// API operation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Operation {
    /// Operation summary
    pub summary: Option<String>,
    /// Operation description
    pub description: Option<String>,
    /// Operation ID
    #[serde(rename = "operationId")]
    pub operation_id: Option<String>,
    /// Request parameters
    pub parameters: Option<Vec<Parameter>>,
    /// Request body
    #[serde(rename = "requestBody")]
    pub request_body: Option<RequestBody>,
    /// Responses
    pub responses: HashMap<String, Response>,
    /// Operation tags
    pub tags: Option<Vec<String>>,
}

/// Request parameter
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Parameter {
    /// Parameter name
    pub name: String,
    /// Parameter location (query, path, header, cookie)
    pub r#in: String,
    /// Parameter description
    pub description: Option<String>,
    /// Whether parameter is required
    pub required: Option<bool>,
    /// Parameter schema
    pub schema: Option<Schema>,
}

/// Request body
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RequestBody {
    /// Request body description
    pub description: Option<String>,
    /// Request body content
    pub content: HashMap<String, MediaType>,
    /// Whether request body is required
    pub required: Option<bool>,
}

/// Media type
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MediaType {
    /// Media type schema
    pub schema: Option<Schema>,
}

/// API response
/// Can be either a full Response object or a $ref to a component
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Response {
    /// Response description (required in OpenAPI but we make it optional for leniency)
    /// This is None when the response is a $ref
    #[serde(
        default = "default_response_description",
        skip_serializing_if = "Option::is_none"
    )]
    pub description: Option<String>,
    /// Response content
    pub content: Option<HashMap<String, MediaType>>,
    /// Response headers
    pub headers: Option<HashMap<String, Header>>,
    /// Reference to another response component (when present, other fields may be None)
    #[serde(rename = "$ref", skip_serializing_if = "Option::is_none")]
    pub ref_path: Option<String>,
}

/// Default description for responses that don't have one
fn default_response_description() -> Option<String> {
    Some("Response".to_string())
}

/// Response header
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Header {
    /// Header description
    pub description: Option<String>,
    /// Header schema
    pub schema: Option<Schema>,
}

/// Components (schemas, responses, etc.)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Components {
    /// Schema definitions
    pub schemas: Option<HashMap<String, Schema>>,
    /// Response definitions
    pub responses: Option<HashMap<String, Response>>,
    /// Parameter definitions
    pub parameters: Option<HashMap<String, Parameter>>,
}

/// JSON Schema
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Schema {
    /// Schema type
    pub r#type: Option<String>,
    /// Schema format
    pub format: Option<String>,
    /// Schema properties
    pub properties: Option<HashMap<String, Schema>>,
    /// Required properties
    pub required: Option<Vec<String>>,
    /// Schema items (for arrays)
    pub items: Option<Box<Schema>>,
    /// Schema description
    pub description: Option<String>,
    /// Schema example
    pub example: Option<serde_json::Value>,
    /// Schema enum values
    pub r#enum: Option<Vec<serde_json::Value>>,
    /// Reference to another schema
    #[serde(rename = "$ref")]
    pub ref_path: Option<String>,
}

/// Client generator configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClientGeneratorConfig {
    /// Output directory for generated files
    pub output_dir: String,
    /// Base URL for the API
    pub base_url: Option<String>,
    /// Whether to include TypeScript types
    pub include_types: bool,
    /// Whether to include mock data generation
    pub include_mocks: bool,
    /// Custom template directory
    pub template_dir: Option<String>,
    /// Additional configuration options
    pub options: HashMap<String, serde_json::Value>,
}

/// Result of client generation
#[derive(Debug, Clone)]
pub struct ClientGenerationResult {
    /// Generated files with their content
    pub files: Vec<GeneratedFile>,
    /// Generation warnings
    pub warnings: Vec<String>,
    /// Generation metadata
    pub metadata: GenerationMetadata,
}

/// Generated file
#[derive(Debug, Clone)]
pub struct GeneratedFile {
    /// File path relative to output directory
    pub path: String,
    /// File content
    pub content: String,
    /// File type (e.g., "typescript", "javascript", "vue", "react")
    pub file_type: String,
}

/// Generation metadata
#[derive(Debug, Clone)]
pub struct GenerationMetadata {
    /// Framework name
    pub framework: String,
    /// Generated client name
    pub client_name: String,
    /// API title from spec
    pub api_title: String,
    /// API version from spec
    pub api_version: String,
    /// Number of operations generated
    pub operation_count: usize,
    /// Number of schemas generated
    pub schema_count: usize,
}

/// Client generator plugin configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClientGeneratorPluginConfig {
    /// Plugin name
    pub name: String,
    /// Framework name
    pub framework: String,
    /// Plugin-specific options
    pub options: HashMap<String, serde_json::Value>,
}

/// Helper functions for client generation
pub mod helpers {
    use super::*;

    /// Capitalize the first letter of a string
    fn capitalize_first(s: &str) -> String {
        let mut chars = s.chars();
        match chars.next() {
            None => String::new(),
            Some(first) => {
                let mut result = first.to_uppercase().collect::<String>();
                result.push_str(&chars.as_str().to_lowercase());
                result
            }
        }
    }

    /// Check if a path segment is a version number (e.g., "v1", "v10", "version1")
    ///
    /// Supports both "v1", "v10", "v123" and "version1", "version10" patterns
    #[cfg_attr(test, allow(dead_code))]
    fn is_version_number(segment: &str) -> bool {
        // Match patterns like "v1", "v10", "v123", etc.
        if segment.starts_with('v') && segment.len() > 1 {
            segment[1..].chars().all(|c| c.is_ascii_digit())
        } else if segment.starts_with("version") && segment.len() > 7 {
            // Match patterns like "version1", "version10", etc.
            segment[7..].chars().all(|c| c.is_ascii_digit())
        } else {
            false
        }
    }

    /// Sanitize an identifier to be a valid TypeScript/JavaScript identifier
    ///
    /// Removes or replaces invalid characters:
    /// - Preserves content inside parentheses and converts to camelCase: "(csv)" -> "Csv"
    /// - Replaces slashes with "Or": "/" -> "Or"
    /// - Removes other invalid characters: spaces, special chars
    /// - Ensures it starts with a letter or underscore
    ///
    /// Examples:
    /// - "getDownloadExport(csv)" -> "getDownloadExportCsv"
    /// - "getUser/organizationSettings" -> "getUserOrOrganizationSettings"
    /// - "postSolveRoutes(aliasOf/routes/plan)" -> "postSolveRoutesAliasOfOrRoutesOrPlan"
    pub fn sanitize_identifier(id: &str) -> String {
        let mut result = String::new();
        let mut chars = id.chars().peekable();

        while let Some(ch) = chars.next() {
            match ch {
                // Preserve content inside parentheses as camelCase
                '(' => {
                    // Extract content and convert to camelCase
                    let mut paren_content = String::new();
                    let mut depth = 1;
                    for next_ch in chars.by_ref() {
                        match next_ch {
                            '(' => {
                                depth += 1;
                                paren_content.push(' ');
                            }
                            ')' => {
                                depth -= 1;
                                if depth == 0 {
                                    break;
                                }
                                paren_content.push(' ');
                            }
                            '/' => paren_content.push(' '), // Convert slashes to spaces for word separation
                            '-' => paren_content.push(' '), // Convert hyphens to spaces
                            c => paren_content.push(c),
                        }
                    }

                    // Convert paren content to camelCase and append
                    // Split on whitespace and process each word, preserving camelCase structure
                    if !paren_content.is_empty() {
                        let words: Vec<&str> = paren_content.split_whitespace().collect();
                        for word in words {
                            if word.is_empty() {
                                continue;
                            }
                            // If word already looks like camelCase (has uppercase in middle), preserve it
                            // Otherwise, capitalize first letter and lowercase rest
                            let mut chars_iter = word.chars();
                            if let Some(first) = chars_iter.next() {
                                result.push(first.to_uppercase().next().unwrap());
                                // Check if rest has uppercase - if so, preserve it
                                let rest: String = chars_iter.collect();
                                if rest.chars().any(|c| c.is_uppercase()) {
                                    // Preserve camelCase structure
                                    result.push_str(&rest);
                                } else {
                                    // Lowercase the rest
                                    result.push_str(&rest.to_lowercase());
                                }
                            }
                        }
                    }
                }
                ')' => {
                    // Shouldn't happen if we handle opening parens correctly, but skip if it does
                    continue;
                }
                // Replace slashes with "Or" (capitalize next char)
                '/' => {
                    if let Some(&next_ch) = chars.peek() {
                        if next_ch.is_alphanumeric() {
                            result.push_str("Or");
                            // Capitalize the next character
                            let next = chars.next().unwrap();
                            result.push(next.to_uppercase().next().unwrap());
                        } else {
                            result.push_str("Or");
                        }
                    } else {
                        result.push_str("Or");
                    }
                }
                // Keep valid identifier characters
                c if c.is_alphanumeric() || c == '_' => {
                    result.push(c);
                }
                // Convert hyphens and spaces to word boundaries (capitalize next)
                '-' | ' ' => {
                    if let Some(&next_ch) = chars.peek() {
                        if next_ch.is_alphanumeric() {
                            // Capitalize next char (effectively creates camelCase boundary)
                            let next = chars.next().unwrap();
                            result.push(next.to_uppercase().next().unwrap());
                        }
                    }
                }
                // Skip other invalid characters
                _ => {}
            }
        }

        // Ensure result starts with a letter (not a number)
        if let Some(first_char) = result.chars().next() {
            if first_char.is_ascii_digit() {
                // Prepend underscore if starts with digit
                result = format!("_{}", result);
            }
        } else {
            // Empty result - provide fallback
            result = "operation".to_string();
        }

        result
    }

    /// Convert a string to camelCase by splitting on hyphens/underscores and capitalizing
    ///
    /// Examples:
    /// - "disease-detection" -> "DiseaseDetection"
    /// - "api_v1_users" -> "ApiV1Users"
    /// - "simple" -> "Simple"
    fn to_camel_case(s: &str) -> String {
        s.split(['-', '_']).filter(|s| !s.is_empty()).map(capitalize_first).collect()
    }

    /// Generate a camelCase operation ID from method, path, and optional summary
    ///
    /// Examples:
    /// - POST /api/v1/ai/disease-detection -> postAiDiseaseDetection
    /// - GET /api/v1/hives/{hiveId}/inspections -> getHiveInspections
    /// - POST /api/v1/users with summary "Create User" -> postCreateUser
    pub fn generate_camel_case_operation_id(
        method: &str,
        path: &str,
        summary: &Option<String>,
    ) -> String {
        // Try to use summary if available and meaningful
        // Use first 2-3 words, or all words if summary is short (<= 50 chars)
        if let Some(s) = summary {
            let words: Vec<&str> = s.split_whitespace().collect();
            let words_to_use = if s.len() <= 50 {
                // Use all words if summary is short
                words
            } else {
                // Otherwise limit to first 3 words
                words.into_iter().take(3).collect()
            };

            if words_to_use.len() >= 2 {
                // Check if the first word is already the HTTP method verb
                // (case-insensitive check to avoid redundant prefixes like "getGet...")
                let method_lower = method.to_lowercase();
                let first_word_lower = words_to_use[0].to_lowercase();

                // Common HTTP method verbs that might appear in summaries
                let method_verbs = ["get", "post", "put", "patch", "delete", "head", "options"];

                // If first word matches the method verb, skip it to avoid redundancy
                let words_to_capitalize = if method_verbs.contains(&first_word_lower.as_str())
                    && first_word_lower == method_lower
                {
                    // Skip the first word if it matches the method
                    &words_to_use[1..]
                } else {
                    // Use all words
                    &words_to_use
                };

                // Only proceed if we have words left after potentially skipping the verb
                if !words_to_capitalize.is_empty() {
                    // Capitalize each word and join
                    let camel_case: String =
                        words_to_capitalize.iter().map(|w| capitalize_first(w)).collect();
                    return format!("{}{}", method.to_lowercase(), camel_case);
                }
            }
        }

        // Generate from path segments
        // Extract meaningful path parts (skip empty, skip path params, skip version numbers)
        let path_parts: Vec<&str> = path
            .split('/')
            .filter(|p| !p.is_empty() && !p.starts_with('{') && !is_version_number(p))
            .collect();

        // Build operation name from last 1-2 meaningful parts (prefer the last part, include second-to-last if it adds context)
        let operation_name = if path_parts.is_empty() {
            "Operation".to_string()
        } else if path_parts.len() == 1 {
            // Single part: just convert to camelCase
            to_camel_case(path_parts[0])
        } else {
            // Multiple parts: use last part, optionally include second-to-last for context
            // For paths like /api/v1/hives/{hiveId}/inspections, use "Inspections"
            // For paths like /api/v1/ai/disease-detection, use "DiseaseDetection"
            let last_part = path_parts[path_parts.len() - 1];
            let second_last = if path_parts.len() >= 2 {
                Some(path_parts[path_parts.len() - 2])
            } else {
                None
            };

            // Only include context for truly generic names, not just plural endings
            // This prevents "inspections" from becoming "HivesInspections" when "Inspections" is clear enough
            let include_context = second_last.is_some()
                && (last_part == "items"
                    || last_part == "data"
                    || last_part == "list"
                    || last_part == "all"
                    || last_part == "search");

            if include_context {
                // Combine second-to-last and last: e.g., "Hive" + "Inspections" = "HiveInspections"
                to_camel_case(second_last.unwrap()) + &to_camel_case(last_part)
            } else {
                // Just use the last part
                to_camel_case(last_part)
            }
        };

        format!("{}{}", method.to_lowercase(), operation_name)
    }

    /// Generate a readable type name from operation ID
    ///
    /// Examples:
    /// - postAiDiseaseDetection -> AiDiseaseDetectionResponse
    /// - getHiveInspections -> HiveInspectionsResponse
    /// - getUsers -> GetUsersResponse
    pub fn generate_type_name(operation_id: &str, suffix: &str) -> String {
        // Common HTTP method prefixes (lowercase)
        let method_prefixes = ["get", "post", "put", "patch", "delete", "head", "options"];

        // Check if operation_id starts with a method prefix (case-insensitive)
        let operation_lower = operation_id.to_lowercase();
        let without_method = if let Some(prefix) =
            method_prefixes.iter().find(|p| operation_lower.starts_with(*p))
        {
            let remaining = &operation_id[prefix.len()..];

            // Count uppercase letters in remaining part to determine if it's simple or complex
            let uppercase_count = remaining.chars().filter(|c| c.is_uppercase()).count();

            // If it's method + single word (no uppercase letters or just one word), capitalize whole thing
            // Otherwise (multiple words in camelCase), skip the method prefix
            if uppercase_count == 0
                || (uppercase_count == 1
                    && remaining.chars().next().map(|c| c.is_uppercase()).unwrap_or(false))
            {
                // Simple case: method + single word -> capitalize whole thing
                operation_id
            } else {
                // Complex case: method + multiple words -> skip method prefix
                remaining
            }
        } else {
            // No method prefix, use whole string
            operation_id
        };

        // Ensure first letter is uppercase (preserve camelCase structure)
        let capitalized = if let Some(first_char) = without_method.chars().next() {
            if first_char.is_lowercase() {
                // Capitalize first letter, preserve rest
                let mut result = first_char.to_uppercase().collect::<String>();
                result.push_str(&without_method[first_char.len_utf8()..]);
                result
            } else {
                without_method.to_string()
            }
        } else {
            without_method.to_string()
        };

        format!("{}{}", capitalized, suffix)
    }

    /// Convert OpenAPI operation to a more convenient format
    ///
    /// Sanitizes operation IDs to ensure they are valid TypeScript identifiers
    pub fn normalize_operation(
        method: &str,
        path: &str,
        operation: &Operation,
    ) -> NormalizedOperation {
        let raw_operation_id = operation.operation_id.clone().unwrap_or_else(|| {
            // Generate camelCase operation ID from method, path, and summary
            generate_camel_case_operation_id(method, path, &operation.summary)
        });

        // Sanitize the operation ID to ensure it's a valid identifier
        let sanitized_id = sanitize_identifier(&raw_operation_id);

        NormalizedOperation {
            method: method.to_uppercase(),
            path: path.to_string(),
            operation_id: sanitized_id,
            summary: operation.summary.clone(),
            description: operation.description.clone(),
            parameters: operation.parameters.clone().unwrap_or_default(),
            request_body: operation.request_body.clone(),
            responses: operation.responses.clone(),
            tags: operation.tags.clone().unwrap_or_default(),
        }
    }

    /// Normalized operation structure
    #[derive(Debug, Clone)]
    pub struct NormalizedOperation {
        /// HTTP method (GET, POST, etc.)
        pub method: String,
        /// API path
        pub path: String,
        /// Operation identifier
        pub operation_id: String,
        /// Operation summary
        pub summary: Option<String>,
        /// Operation description
        pub description: Option<String>,
        /// Request parameters
        pub parameters: Vec<Parameter>,
        /// Request body specification
        pub request_body: Option<RequestBody>,
        /// Response specifications
        pub responses: HashMap<String, Response>,
        /// Operation tags
        pub tags: Vec<String>,
    }

    /// Generate TypeScript type from OpenAPI schema with proper formatting
    ///
    /// Generates properly formatted TypeScript types with:
    /// - Array<T> syntax for arrays
    /// - Properly indented object types
    /// - Correct handling of nested types
    pub fn schema_to_typescript_type(schema: &Schema) -> String {
        match schema.r#type.as_deref() {
            Some("string") => match schema.format.as_deref() {
                Some("date") => "string".to_string(),
                Some("date-time") => "string".to_string(),
                Some("email") => "string".to_string(),
                Some("uri") => "string".to_string(),
                _ => "string".to_string(),
            },
            Some("integer") | Some("number") => "number".to_string(),
            Some("boolean") => "boolean".to_string(),
            Some("array") => {
                if let Some(items) = &schema.items {
                    // Use Array<T> syntax for better readability
                    format!("Array<{}>", schema_to_typescript_type(items))
                } else {
                    "any[]".to_string()
                }
            }
            Some("object") => {
                if let Some(properties) = &schema.properties {
                    let mut props = Vec::new();
                    for (name, prop_schema) in properties {
                        let prop_type = schema_to_typescript_type(prop_schema);
                        let required =
                            schema.required.as_ref().map(|req| req.contains(name)).unwrap_or(false);

                        // Format property with proper indentation
                        if required {
                            props.push(format!("  {}: {}", name, prop_type));
                        } else {
                            props.push(format!("  {}?: {}", name, prop_type));
                        }
                    }
                    // Format object with proper line breaks
                    format!("{{\n{}\n}}", props.join(";\n"))
                } else {
                    "Record<string, any>".to_string()
                }
            }
            _ => "any".to_string(),
        }
    }

    /// Extract path parameters from OpenAPI path
    pub fn extract_path_parameters(path: &str) -> Vec<String> {
        let mut params = Vec::new();
        let mut chars = path.chars().peekable();

        while let Some(ch) = chars.next() {
            if ch == '{' {
                let mut param = String::new();
                for ch in chars.by_ref() {
                    if ch == '}' {
                        break;
                    }
                    param.push(ch);
                }
                if !param.is_empty() {
                    params.push(param);
                }
            }
        }

        params
    }

    /// Convert OpenAPI path to framework-specific path format
    pub fn convert_path_format(path: &str, framework: &str) -> String {
        match framework {
            "react" | "vue" | "angular" => {
                // Convert {param} to :param for most frontend frameworks
                path.replace('{', ":").replace('}', "")
            }
            "svelte" => {
                // Svelte uses [param] format
                let result = path.to_string();
                let mut chars = result.chars().collect::<Vec<_>>();
                let mut i = 0;
                while i < chars.len() {
                    if chars[i] == '{' {
                        chars[i] = '[';
                        i += 1;
                        while i < chars.len() && chars[i] != '}' {
                            i += 1;
                        }
                        if i < chars.len() {
                            chars[i] = ']';
                        }
                    }
                    i += 1;
                }
                chars.into_iter().collect()
            }
            _ => path.to_string(),
        }
    }
}

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

    #[test]
    fn test_extract_path_parameters() {
        assert_eq!(helpers::extract_path_parameters("/api/users/{id}"), vec!["id"]);
        assert_eq!(
            helpers::extract_path_parameters("/api/users/{id}/posts/{postId}"),
            vec!["id", "postId"]
        );
        assert_eq!(helpers::extract_path_parameters("/api/users"), Vec::<String>::new());
    }

    #[test]
    fn test_convert_path_format() {
        assert_eq!(helpers::convert_path_format("/api/users/{id}", "react"), "/api/users/:id");
        assert_eq!(helpers::convert_path_format("/api/users/{id}", "svelte"), "/api/users/[id]");
    }

    #[test]
    fn test_schema_to_typescript_type() {
        let string_schema = Schema {
            r#type: Some("string".to_string()),
            format: None,
            properties: None,
            required: None,
            items: None,
            description: None,
            example: None,
            r#enum: None,
            ref_path: None,
        };
        assert_eq!(helpers::schema_to_typescript_type(&string_schema), "string");

        let number_schema = Schema {
            r#type: Some("number".to_string()),
            format: None,
            properties: None,
            required: None,
            items: None,
            description: None,
            example: None,
            r#enum: None,
            ref_path: None,
        };
        assert_eq!(helpers::schema_to_typescript_type(&number_schema), "number");

        // Test array type formatting
        let array_schema = Schema {
            r#type: Some("array".to_string()),
            format: None,
            properties: None,
            required: None,
            items: Some(Box::new(string_schema.clone())),
            description: None,
            example: None,
            r#enum: None,
            ref_path: None,
        };
        assert_eq!(helpers::schema_to_typescript_type(&array_schema), "Array<string>");
    }

    #[test]
    fn test_generate_camel_case_operation_id() {
        // Test with summary
        let summary = Some("Detect Disease".to_string());
        let op_id = helpers::generate_camel_case_operation_id(
            "POST",
            "/api/v1/ai/disease-detection",
            &summary,
        );
        assert!(op_id.starts_with("post"));
        assert!(op_id.contains("Detect") || op_id.contains("Disease"));

        // Test without summary - should generate from path
        // For /api/v1/hives/{hiveId}/inspections, should use last meaningful part
        let op_id = helpers::generate_camel_case_operation_id(
            "GET",
            "/api/v1/hives/{hiveId}/inspections",
            &None,
        );
        assert_eq!(op_id, "getInspections");

        // Test with context needed (generic name)
        let op_id =
            helpers::generate_camel_case_operation_id("GET", "/api/v1/hives/{hiveId}/items", &None);
        assert_eq!(op_id, "getHivesItems");

        // Test POST with path
        let op_id = helpers::generate_camel_case_operation_id(
            "POST",
            "/api/v1/ai/disease-detection",
            &None,
        );
        assert_eq!(op_id, "postDiseaseDetection");

        // Test with single word path
        let op_id = helpers::generate_camel_case_operation_id("GET", "/api/users", &None);
        assert_eq!(op_id, "getUsers");
    }

    #[test]
    fn test_generate_type_name() {
        assert_eq!(
            helpers::generate_type_name("postAiDiseaseDetection", "Response"),
            "AiDiseaseDetectionResponse"
        );
        assert_eq!(
            helpers::generate_type_name("getHiveInspections", "Response"),
            "HiveInspectionsResponse"
        );
        // getUsers is method + single word, so capitalize whole thing
        assert_eq!(helpers::generate_type_name("getUsers", "Request"), "GetUsersRequest");
    }

    #[test]
    fn test_normalize_operation_with_camel_case() {
        let operation = Operation {
            summary: Some("Get hive inspections".to_string()),
            description: None,
            operation_id: None,
            parameters: None,
            request_body: None,
            responses: HashMap::new(),
            tags: None,
        };

        let normalized =
            helpers::normalize_operation("GET", "/api/v1/hives/{hiveId}/inspections", &operation);
        assert!(normalized.operation_id.starts_with("get"));
        assert!(
            normalized.operation_id.contains("Inspections")
                || normalized.operation_id.contains("Hive")
        );
    }

    #[test]
    fn test_generate_camel_case_operation_id_with_version_numbers() {
        // Test v10, v123 (previously missed by len <= 3 check)
        let op_id = helpers::generate_camel_case_operation_id("GET", "/api/v10/users", &None);
        assert_eq!(op_id, "getUsers");

        let op_id = helpers::generate_camel_case_operation_id("GET", "/api/v123/resource", &None);
        assert_eq!(op_id, "getResource");

        // Test version1, version10 patterns
        let op_id = helpers::generate_camel_case_operation_id("GET", "/api/version1/users", &None);
        assert_eq!(op_id, "getUsers");

        let op_id =
            helpers::generate_camel_case_operation_id("GET", "/api/version10/resource", &None);
        assert_eq!(op_id, "getResource");
    }

    #[test]
    fn test_generate_camel_case_operation_id_with_long_summary() {
        // Test that short summaries (<= 50 chars) use all words
        let short_summary = Some("Create New User Account".to_string());
        let op_id = helpers::generate_camel_case_operation_id("POST", "/api/users", &short_summary);
        assert!(op_id.starts_with("post"));
        assert!(op_id.contains("Create") || op_id.contains("New") || op_id.contains("User"));

        // Test that long summaries are truncated to first 3 words
        let long_summary = Some(
            "This is a very long summary that should be truncated to first three words only"
                .to_string(),
        );
        let op_id = helpers::generate_camel_case_operation_id("POST", "/api/users", &long_summary);
        assert!(op_id.starts_with("post"));
        // Should only contain first 3 words: "This", "Is", "Very"
        assert!(op_id.contains("This") || op_id.contains("Is") || op_id.contains("Very"));
    }

    #[test]
    fn test_generate_camel_case_operation_id_with_redundant_verb() {
        // Test that summaries starting with the method verb don't create redundant prefixes
        // e.g., "Get apiary by ID" with GET method should become "getApiaryById", not "getGetApiaryById"
        let summary = Some("Get apiary by ID".to_string());
        let op_id =
            helpers::generate_camel_case_operation_id("GET", "/api/v1/apiaries/{id}", &summary);
        assert_eq!(op_id, "getApiaryById");

        // Test with POST
        let summary = Some("Post new user".to_string());
        let op_id = helpers::generate_camel_case_operation_id("POST", "/api/users", &summary);
        assert_eq!(op_id, "postNewUser");

        // Test with PUT
        let summary = Some("Put update user".to_string());
        let op_id = helpers::generate_camel_case_operation_id("PUT", "/api/users/{id}", &summary);
        assert_eq!(op_id, "putUpdateUser");

        // Test that non-matching verbs still work (e.g., "Create" with GET)
        let summary = Some("Create user".to_string());
        let op_id = helpers::generate_camel_case_operation_id("GET", "/api/users", &summary);
        assert_eq!(op_id, "getCreateUser"); // Should include "Create" since it doesn't match "GET"
    }

    #[test]
    fn test_generate_type_name_edge_cases() {
        // Test with lowercase first letter (e.g., from operation_id like "getUsers")
        assert_eq!(helpers::generate_type_name("getUsers", "Response"), "GetUsersResponse");

        // Test with already uppercase first letter
        assert_eq!(helpers::generate_type_name("GetUsers", "Response"), "GetUsersResponse");

        // Test with single word operation ID
        assert_eq!(helpers::generate_type_name("getUser", "Response"), "GetUserResponse");
    }

    #[test]
    fn test_sanitize_identifier() {
        // Test parentheses removal - preserve content as camelCase
        assert_eq!(helpers::sanitize_identifier("getDownloadExport(csv)"), "getDownloadExportCsv");

        // Test slash replacement
        assert_eq!(
            helpers::sanitize_identifier("getUser/organizationSettings"),
            "getUserOrOrganizationSettings"
        );

        // Test complex case with both parentheses and slashes
        // Inside parentheses, slashes become word separators (spaces), then converted to camelCase
        assert_eq!(
            helpers::sanitize_identifier("postSolveRoutes(aliasOf/routes/plan)"),
            "postSolveRoutesAliasOfRoutesPlan"
        );

        // Test parentheses with content
        assert_eq!(
            helpers::sanitize_identifier("getViewPollinationJob(growerPortal)"),
            "getViewPollinationJobGrowerPortal"
        );

        // Test normal identifier (should pass through)
        assert_eq!(helpers::sanitize_identifier("getUsers"), "getUsers");

        // Test with hyphens
        assert_eq!(helpers::sanitize_identifier("get-disease-detection"), "getDiseaseDetection");

        // Test with spaces
        assert_eq!(helpers::sanitize_identifier("get user settings"), "getUserSettings");
    }
}