elif-openapi 0.2.1

OpenAPI 3.0 specification generation for elif.rs framework
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
/*!
Project discovery and introspection for OpenAPI generation.

This module provides functionality to discover API routes, controllers, and models
from an elif.rs project structure.
*/

use crate::{
    endpoints::{ControllerInfo, EndpointMetadata, EndpointParameter, ParameterSource},
    error::{OpenApiError, OpenApiResult},
};
use std::fs;
use std::path::{Path, PathBuf};
use toml;

/// Project discovery service for analyzing elif.rs projects
pub struct ProjectDiscovery {
    /// Project root directory
    project_root: PathBuf,
}

/// Discovered project structure
#[derive(Debug, Clone)]
pub struct ProjectStructure {
    /// Controllers found in the project
    pub controllers: Vec<ControllerInfo>,
    /// Models/schemas found in the project
    pub models: Vec<ModelInfo>,
    /// Project metadata
    pub metadata: ProjectMetadata,
}

/// Model/schema information
#[derive(Debug, Clone)]
pub struct ModelInfo {
    /// Model name
    pub name: String,
    /// Fields in the model
    pub fields: Vec<ModelField>,
    /// Model documentation
    pub documentation: Option<String>,
    /// Model attributes/derives
    pub derives: Vec<String>,
}

/// Model field information
#[derive(Debug, Clone)]
pub struct ModelField {
    /// Field name
    pub name: String,
    /// Field type
    pub field_type: String,
    /// Field documentation
    pub documentation: Option<String>,
    /// Whether field is optional
    pub optional: bool,
}

/// Project metadata
#[derive(Debug, Clone)]
pub struct ProjectMetadata {
    /// Project name
    pub name: String,
    /// Project version
    pub version: String,
    /// Project description
    pub description: Option<String>,
    /// Authors
    pub authors: Vec<String>,
}

impl ProjectDiscovery {
    /// Create new project discovery service
    pub fn new<P: AsRef<Path>>(project_root: P) -> Self {
        Self {
            project_root: project_root.as_ref().to_path_buf(),
        }
    }

    /// Discover project structure
    pub fn discover(&self) -> OpenApiResult<ProjectStructure> {
        let metadata = self.discover_project_metadata()?;
        let controllers = self.discover_controllers()?;
        let models = self.discover_models()?;

        Ok(ProjectStructure {
            controllers,
            models,
            metadata,
        })
    }

    /// Discover project metadata from Cargo.toml using proper TOML parsing
    fn discover_project_metadata(&self) -> OpenApiResult<ProjectMetadata> {
        let cargo_toml_path = self.project_root.join("Cargo.toml");

        if !cargo_toml_path.exists() {
            return Ok(ProjectMetadata {
                name: "Unknown".to_string(),
                version: "1.0.0".to_string(),
                description: None,
                authors: Vec::new(),
            });
        }

        let cargo_content = fs::read_to_string(&cargo_toml_path).map_err(|e| {
            OpenApiError::route_discovery_error(format!("Failed to read Cargo.toml: {}", e))
        })?;

        // Parse TOML properly using toml crate
        let toml_value: toml::Value = cargo_content.parse().map_err(|e| {
            OpenApiError::route_discovery_error(format!("Failed to parse Cargo.toml: {}", e))
        })?;

        // Extract package information from [package] table
        let package = toml_value.get("package").ok_or_else(|| {
            OpenApiError::route_discovery_error(
                "No [package] section found in Cargo.toml".to_string(),
            )
        })?;

        let name = package
            .get("name")
            .and_then(|v| v.as_str())
            .unwrap_or("Unknown")
            .to_string();

        let version = package
            .get("version")
            .and_then(|v| v.as_str())
            .unwrap_or("1.0.0")
            .to_string();

        let description = package
            .get("description")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());

        // Extract authors array
        let authors = package
            .get("authors")
            .and_then(|v| v.as_array())
            .map(|authors_array| {
                authors_array
                    .iter()
                    .filter_map(|author| author.as_str())
                    .map(|s| s.to_string())
                    .collect()
            })
            .unwrap_or_else(Vec::new);

        Ok(ProjectMetadata {
            name,
            version,
            description,
            authors,
        })
    }

    /// Discover controllers from src/controllers directory
    fn discover_controllers(&self) -> OpenApiResult<Vec<ControllerInfo>> {
        let controllers_dir = self.project_root.join("src").join("controllers");

        if !controllers_dir.exists() {
            return Ok(Vec::new());
        }

        let mut controllers = Vec::new();

        let entries = fs::read_dir(&controllers_dir).map_err(|e| {
            OpenApiError::route_discovery_error(format!(
                "Failed to read controllers directory: {}",
                e
            ))
        })?;

        for entry in entries {
            let entry = entry.map_err(|e| {
                OpenApiError::route_discovery_error(format!(
                    "Failed to read controller entry: {}",
                    e
                ))
            })?;

            let path = entry.path();
            if path.extension().map(|ext| ext == "rs").unwrap_or(false) {
                if let Some(controller) = self.analyze_controller_file(&path)? {
                    controllers.push(controller);
                }
            }
        }

        Ok(controllers)
    }

    /// Analyze a controller file
    fn analyze_controller_file(&self, path: &Path) -> OpenApiResult<Option<ControllerInfo>> {
        let content = fs::read_to_string(path).map_err(|e| {
            OpenApiError::route_discovery_error(format!(
                "Failed to read controller file {}: {}",
                path.display(),
                e
            ))
        })?;

        let controller_name = path
            .file_stem()
            .and_then(|name| name.to_str())
            .unwrap_or("Unknown")
            .replace("_controller", "")
            .replace("_", " ")
            .split_whitespace()
            .map(capitalize)
            .collect::<String>();

        let endpoints = self.extract_endpoints_from_content(&content)?;

        if endpoints.is_empty() {
            return Ok(None);
        }

        let mut controller = ControllerInfo::new(&controller_name);
        for endpoint in endpoints {
            controller = controller.add_endpoint(endpoint);
        }

        Ok(Some(controller))
    }

    /// Extract endpoints from controller file content using AST parsing
    fn extract_endpoints_from_content(
        &self,
        content: &str,
    ) -> OpenApiResult<Vec<EndpointMetadata>> {
        // Parse the Rust source code into an AST
        let ast = syn::parse_file(content).map_err(|e| {
            OpenApiError::route_discovery_error(format!("Failed to parse Rust file: {}", e))
        })?;

        let mut endpoints = Vec::new();

        // Walk the AST to find functions with route attributes
        for item in &ast.items {
            if let syn::Item::Fn(func) = item {
                if let Some(endpoint) = self.extract_endpoint_from_function(func)? {
                    endpoints.push(endpoint);
                }
            }
        }

        Ok(endpoints)
    }

    /// Extract endpoint from a function using AST analysis
    fn extract_endpoint_from_function(
        &self,
        func: &syn::ItemFn,
    ) -> OpenApiResult<Option<EndpointMetadata>> {
        // Look for route attributes
        let mut route_info = None;

        for attr in &func.attrs {
            if let Some((verb, path)) = self.parse_route_attribute_ast(attr)? {
                route_info = Some((verb, path));
                break;
            }
        }

        let Some((verb, path)) = route_info else {
            return Ok(None);
        };

        // Get function name
        let function_name = func.sig.ident.to_string();

        // Create endpoint metadata
        let mut endpoint = EndpointMetadata::new(&function_name, &verb, &path);

        // Extract parameters from function signature
        let params = self.extract_function_parameters_ast(&func.sig)?;
        for param in params {
            endpoint = endpoint.with_parameter(param);
        }

        // Extract documentation from function attributes
        let doc = self.extract_documentation_ast(&func.attrs);
        if let Some(doc) = doc {
            endpoint = endpoint.with_documentation(&doc);
        }

        // Extract return type information
        if let syn::ReturnType::Type(_, ty) = &func.sig.output {
            endpoint.return_type = Some(self.type_to_string(ty));
        }

        Ok(Some(endpoint))
    }

    /// Parse route attribute using AST
    fn parse_route_attribute_ast(
        &self,
        attr: &syn::Attribute,
    ) -> OpenApiResult<Option<(String, String)>> {
        // Check if this is a route attribute
        let path_segments: Vec<String> = attr
            .path()
            .segments
            .iter()
            .map(|seg| seg.ident.to_string())
            .collect();

        // Look for route-like attributes (route, get, post, put, delete, etc.)
        if path_segments.len() != 1 {
            return Ok(None);
        }

        let attr_name = &path_segments[0];
        let (verb, path) = match attr_name.as_str() {
            "route" => {
                // Parse #[route(GET, "/path")] or #[route(method = "GET", path = "/path")]
                self.parse_route_macro(attr)?
            }
            "get" => ("GET".to_string(), self.parse_simple_route_macro(attr)?),
            "post" => ("POST".to_string(), self.parse_simple_route_macro(attr)?),
            "put" => ("PUT".to_string(), self.parse_simple_route_macro(attr)?),
            "delete" => ("DELETE".to_string(), self.parse_simple_route_macro(attr)?),
            "patch" => ("PATCH".to_string(), self.parse_simple_route_macro(attr)?),
            "head" => ("HEAD".to_string(), self.parse_simple_route_macro(attr)?),
            "options" => ("OPTIONS".to_string(), self.parse_simple_route_macro(attr)?),
            _ => return Ok(None),
        };

        Ok(Some((verb, path)))
    }

    /// Parse route macro like #[route(GET, "/path")]
    fn parse_route_macro(&self, attr: &syn::Attribute) -> OpenApiResult<(String, String)> {
        match &attr.meta {
            syn::Meta::List(meta_list) => {
                let tokens = &meta_list.tokens;
                let token_str = tokens.to_string();

                // Simple parsing for now - can be enhanced
                let parts: Vec<&str> = token_str.split(',').map(|s| s.trim()).collect();
                if parts.len() >= 2 {
                    let verb = parts[0].trim_matches('"').to_uppercase();
                    let path = parts[1].trim_matches('"').to_string();
                    Ok((verb, path))
                } else {
                    Err(OpenApiError::route_discovery_error(
                        "Invalid route attribute format".to_string(),
                    ))
                }
            }
            _ => Err(OpenApiError::route_discovery_error(
                "Expected route attribute with arguments".to_string(),
            )),
        }
    }

    /// Parse simple route macro like #[get("/path")]
    fn parse_simple_route_macro(&self, attr: &syn::Attribute) -> OpenApiResult<String> {
        match &attr.meta {
            syn::Meta::List(meta_list) => {
                let tokens = &meta_list.tokens;
                let path = tokens.to_string().trim_matches('"').to_string();
                Ok(path)
            }
            _ => Err(OpenApiError::route_discovery_error(
                "Expected route attribute with path".to_string(),
            )),
        }
    }

    /// Extract function parameters using AST analysis
    fn extract_function_parameters_ast(
        &self,
        sig: &syn::Signature,
    ) -> OpenApiResult<Vec<EndpointParameter>> {
        let mut parameters = Vec::new();

        for input in &sig.inputs {
            match input {
                syn::FnArg::Typed(pat_type) => {
                    let param_name = match &*pat_type.pat {
                        syn::Pat::Ident(ident) => ident.ident.to_string(),
                        _ => continue, // Skip complex patterns
                    };

                    let type_str = self.type_to_string(&pat_type.ty);
                    let (source, optional) = self.determine_parameter_source(&type_str);

                    parameters.push(EndpointParameter {
                        name: param_name,
                        param_type: type_str,
                        source,
                        optional,
                        documentation: None,
                    });
                }
                syn::FnArg::Receiver(_) => continue, // Skip self parameters
            }
        }

        Ok(parameters)
    }

    /// Determine parameter source from type information
    fn determine_parameter_source(&self, type_str: &str) -> (ParameterSource, bool) {
        if type_str.contains("Path<") || type_str.contains("PathParams") {
            (ParameterSource::Path, false)
        } else if type_str.contains("Query<") || type_str.contains("QueryParams") {
            (ParameterSource::Query, type_str.contains("Option<"))
        } else if type_str.contains("Header<") || type_str.contains("HeaderMap") {
            (ParameterSource::Header, type_str.contains("Option<"))
        } else if type_str.contains("Json<")
            || type_str.contains("Form<")
            || type_str.contains("Request")
        {
            (ParameterSource::Body, false)
        } else {
            // Default to query parameter
            (ParameterSource::Query, type_str.contains("Option<"))
        }
    }

    /// Convert syn::Type to string representation
    fn type_to_string(&self, ty: &syn::Type) -> String {
        quote::quote!(#ty).to_string()
    }

    /// Extract documentation from function attributes
    fn extract_documentation_ast(&self, attrs: &[syn::Attribute]) -> Option<String> {
        let mut doc_lines = Vec::new();

        for attr in attrs {
            if attr.path().is_ident("doc") {
                if let syn::Meta::NameValue(meta) = &attr.meta {
                    if let syn::Expr::Lit(syn::ExprLit {
                        lit: syn::Lit::Str(lit_str),
                        ..
                    }) = &meta.value
                    {
                        doc_lines.push(lit_str.value().trim().to_string());
                    }
                }
            }
        }

        if doc_lines.is_empty() {
            None
        } else {
            Some(doc_lines.join("\n"))
        }
    }

    /// Discover models from src/models directory
    fn discover_models(&self) -> OpenApiResult<Vec<ModelInfo>> {
        let models_dir = self.project_root.join("src").join("models");

        if !models_dir.exists() {
            return Ok(Vec::new());
        }

        let mut models = Vec::new();

        let entries = fs::read_dir(&models_dir).map_err(|e| {
            OpenApiError::route_discovery_error(format!("Failed to read models directory: {}", e))
        })?;

        for entry in entries {
            let entry = entry.map_err(|e| {
                OpenApiError::route_discovery_error(format!("Failed to read model entry: {}", e))
            })?;

            let path = entry.path();
            if path.extension().map(|ext| ext == "rs").unwrap_or(false) {
                if let Some(model) = self.analyze_model_file(&path)? {
                    models.push(model);
                }
            }
        }

        Ok(models)
    }

    /// Analyze a model file using AST parsing
    fn analyze_model_file(&self, path: &Path) -> OpenApiResult<Option<ModelInfo>> {
        let content = fs::read_to_string(path).map_err(|e| {
            OpenApiError::route_discovery_error(format!(
                "Failed to read model file {}: {}",
                path.display(),
                e
            ))
        })?;

        let model_name = path
            .file_stem()
            .and_then(|name| name.to_str())
            .unwrap_or("Unknown")
            .to_string();

        // Parse the Rust source code into an AST
        let ast = syn::parse_file(&content).map_err(|e| {
            OpenApiError::route_discovery_error(format!(
                "Failed to parse model file {}: {}",
                path.display(),
                e
            ))
        })?;

        // Extract struct definition using AST
        if let Some(model) = self.extract_struct_from_ast(&ast, &model_name)? {
            return Ok(Some(model));
        }

        Ok(None)
    }

    /// Extract struct definition from AST
    fn extract_struct_from_ast(
        &self,
        ast: &syn::File,
        model_name: &str,
    ) -> OpenApiResult<Option<ModelInfo>> {
        // Walk the AST to find struct definitions
        for item in &ast.items {
            if let syn::Item::Struct(item_struct) = item {
                let struct_name = item_struct.ident.to_string();

                // Check if this is the struct we're looking for (case-insensitive)
                if struct_name.to_lowercase() == model_name.to_lowercase() {
                    // Extract derive attributes
                    let derives = self.extract_derives_from_attrs(&item_struct.attrs);

                    // Extract documentation
                    let doc = self.extract_documentation_ast(&item_struct.attrs);

                    // Extract fields
                    let fields = self.extract_struct_fields_from_ast(&item_struct.fields)?;

                    return Ok(Some(ModelInfo {
                        name: struct_name,
                        fields,
                        documentation: doc,
                        derives,
                    }));
                }
            }
        }

        Ok(None)
    }

    /// Extract derive attributes from struct attributes using AST
    fn extract_derives_from_attrs(&self, attrs: &[syn::Attribute]) -> Vec<String> {
        let mut derives = Vec::new();

        for attr in attrs {
            if attr.path().is_ident("derive") {
                if let syn::Meta::List(meta_list) = &attr.meta {
                    let derive_tokens = meta_list.tokens.to_string();
                    // Parse comma-separated derive tokens
                    derives.extend(
                        derive_tokens
                            .split(',')
                            .map(|d| d.trim().to_string())
                            .filter(|d| !d.is_empty()),
                    );
                }
            }
        }

        derives
    }

    /// Extract struct fields from AST Fields
    fn extract_struct_fields_from_ast(
        &self,
        fields: &syn::Fields,
    ) -> OpenApiResult<Vec<ModelField>> {
        let mut model_fields = Vec::new();

        match fields {
            syn::Fields::Named(fields_named) => {
                for field in &fields_named.named {
                    if let Some(field_name) = &field.ident {
                        let field_name = field_name.to_string();
                        let field_type = self.type_to_string(&field.ty);
                        let optional =
                            field_type.starts_with("Option<") || field_type.contains("Option <");

                        // Extract field documentation
                        let documentation = self.extract_documentation_ast(&field.attrs);

                        model_fields.push(ModelField {
                            name: field_name,
                            field_type,
                            documentation,
                            optional,
                        });
                    }
                }
            }
            syn::Fields::Unnamed(fields_unnamed) => {
                // Handle tuple structs
                for (index, field) in fields_unnamed.unnamed.iter().enumerate() {
                    let field_name = format!("field_{}", index);
                    let field_type = self.type_to_string(&field.ty);
                    let optional =
                        field_type.starts_with("Option<") || field_type.contains("Option <");

                    // Extract field documentation
                    let documentation = self.extract_documentation_ast(&field.attrs);

                    model_fields.push(ModelField {
                        name: field_name,
                        field_type,
                        documentation,
                        optional,
                    });
                }
            }
            syn::Fields::Unit => {
                // Unit structs have no fields
            }
        }

        Ok(model_fields)
    }

    /// Bridge function for old line-based documentation extraction (used by model parsing)
    /// TODO: Replace with AST-based model parsing
    #[allow(dead_code)]
    fn extract_documentation_from_lines(
        &self,
        lines: &[&str],
        route_index: usize,
    ) -> Option<String> {
        let mut doc_lines = Vec::new();

        // Look backwards for documentation comments
        for i in (0..route_index).rev() {
            let line = lines[i].trim();
            if line.starts_with("///") {
                doc_lines.insert(0, line.trim_start_matches("///").trim());
            } else if line.starts_with("//!") {
                doc_lines.insert(0, line.trim_start_matches("//!").trim());
            } else if !line.is_empty() && !line.starts_with("//") {
                break;
            }
        }

        if doc_lines.is_empty() {
            None
        } else {
            Some(doc_lines.join(" "))
        }
    }
}

/// Helper function to capitalize first letter
fn capitalize(s: &str) -> String {
    let mut chars = s.chars();
    match chars.next() {
        None => String::new(),
        Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn test_project_discovery_creation() {
        let temp_dir = TempDir::new().unwrap();
        let discovery = ProjectDiscovery::new(temp_dir.path());
        assert_eq!(discovery.project_root, temp_dir.path());
    }

    #[test]
    fn test_ast_based_struct_parsing() {
        let discovery = ProjectDiscovery::new(".");

        let test_code = r#"
            #[derive(Debug, Clone, Serialize)]
            /// A test user model
            pub struct User {
                /// User ID
                pub id: i32,
                /// User email address
                pub email: Option<String>,
                pub name: String,
            }
        "#;

        let ast = syn::parse_file(test_code).unwrap();
        let model = discovery
            .extract_struct_from_ast(&ast, "user")
            .unwrap()
            .unwrap();

        assert_eq!(model.name, "User");
        assert_eq!(model.fields.len(), 3);
        assert!(model.derives.contains(&"Debug".to_string()));
        assert!(model.derives.contains(&"Clone".to_string()));
        assert!(model.derives.contains(&"Serialize".to_string()));
        assert!(model.documentation.is_some());

        // Check fields
        let id_field = model.fields.iter().find(|f| f.name == "id").unwrap();
        assert_eq!(id_field.field_type, "i32");
        assert!(!id_field.optional);

        let email_field = model.fields.iter().find(|f| f.name == "email").unwrap();
        assert_eq!(email_field.field_type, "Option < String >");
        assert!(email_field.optional);
    }

    #[test]
    fn test_robust_toml_parsing() {
        // Test with realistic Cargo.toml content including comments, tables, and various TOML features
        let temp_dir = TempDir::new().unwrap();
        let cargo_toml_path = temp_dir.path().join("Cargo.toml");

        let complex_toml_content = r#"
# This is a comment
[package]
name = "test-project"  # Inline comment
version = "1.2.3"
description = "A test project with complex TOML structure"
authors = ["John Doe <john@example.com>", "Jane Smith <jane@example.com>"]

# Some other sections that should not interfere
[dependencies]
serde = "1.0"

[dev-dependencies]
tokio-test = "0.4"

# Another comment
[features]
default = []
        "#;

        fs::write(&cargo_toml_path, complex_toml_content).unwrap();

        let discovery = ProjectDiscovery::new(temp_dir.path());
        let metadata = discovery.discover_project_metadata().unwrap();

        assert_eq!(metadata.name, "test-project");
        assert_eq!(metadata.version, "1.2.3");
        assert_eq!(
            metadata.description,
            Some("A test project with complex TOML structure".to_string())
        );
        assert_eq!(metadata.authors.len(), 2);
        assert!(metadata
            .authors
            .contains(&"John Doe <john@example.com>".to_string()));
        assert!(metadata
            .authors
            .contains(&"Jane Smith <jane@example.com>".to_string()));
    }

    #[test]
    fn test_toml_parsing_with_missing_package_section() {
        let temp_dir = TempDir::new().unwrap();
        let cargo_toml_path = temp_dir.path().join("Cargo.toml");

        let invalid_toml_content = r#"
# No package section
[dependencies]
serde = "1.0"
        "#;

        fs::write(&cargo_toml_path, invalid_toml_content).unwrap();

        let discovery = ProjectDiscovery::new(temp_dir.path());
        let result = discovery.discover_project_metadata();

        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("No [package] section found"));
    }

    #[test]
    fn test_toml_parsing_with_minimal_package() {
        let temp_dir = TempDir::new().unwrap();
        let cargo_toml_path = temp_dir.path().join("Cargo.toml");

        let minimal_toml_content = r#"
[package]
name = "minimal-project"
version = "0.1.0"
        "#;

        fs::write(&cargo_toml_path, minimal_toml_content).unwrap();

        let discovery = ProjectDiscovery::new(temp_dir.path());
        let metadata = discovery.discover_project_metadata().unwrap();

        assert_eq!(metadata.name, "minimal-project");
        assert_eq!(metadata.version, "0.1.0");
        assert_eq!(metadata.description, None);
        assert!(metadata.authors.is_empty());
    }

    #[test]
    fn test_toml_parsing_with_different_key_ordering() {
        let temp_dir = TempDir::new().unwrap();
        let cargo_toml_path = temp_dir.path().join("Cargo.toml");

        // Test with different key ordering than typical
        let reordered_toml_content = r#"
[package]
authors = ["Author One"]
description = "Description first"
name = "reordered-project"
version = "2.0.0"
        "#;

        fs::write(&cargo_toml_path, reordered_toml_content).unwrap();

        let discovery = ProjectDiscovery::new(temp_dir.path());
        let metadata = discovery.discover_project_metadata().unwrap();

        assert_eq!(metadata.name, "reordered-project");
        assert_eq!(metadata.version, "2.0.0");
        assert_eq!(metadata.description, Some("Description first".to_string()));
        assert_eq!(metadata.authors, vec!["Author One".to_string()]);
    }
}