spikard-cli 0.15.6-rc.21

Command-line interface for building and validating Spikard applications
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
//! Python GraphQL code generator.
//!
//! This generator produces type-safe Python code for GraphQL resolver implementations.
//! Generated code uses type hints compatible with Python 3.10+, msgspec for serialization,
//! and Ariadne for GraphQL schema binding.

use super::GraphQLGenerator;
use crate::codegen::common::case_conversion::to_snake_case;
use crate::codegen::common::escaping::{EscapeContext, escape_for_docstring};
use crate::codegen::graphql::sdl::{SdlBuilder, TargetLanguage, TypeMapper};
use crate::codegen::graphql::spec_parser::GraphQLSchema;
use anyhow::Result;

#[derive(Default, Debug, Clone, Copy)]
pub struct PythonGenerator;

impl GraphQLGenerator for PythonGenerator {
    fn generate_types(&self, schema: &GraphQLSchema) -> Result<String> {
        use crate::codegen::graphql::spec_parser::TypeKind;

        let mut code = String::new();
        code.push_str("#!/usr/bin/env python3\n");
        code.push_str("# ruff: noqa: EXE001, I001\n");
        code.push_str("# DO NOT EDIT - Auto-generated by Spikard CLI\n");
        code.push_str("#\n");
        code.push_str("# This file was automatically generated from your GraphQL schema.\n");
        code.push_str("# Any manual changes will be overwritten on the next generation.\n");
        code.push_str("\"\"\"GraphQL types generated from schema.\"\"\"\n\n");

        // Check if we need to import Enum
        let has_enums = schema.types.values().any(|t| t.kind == TypeKind::Enum);
        // Check if we need to import Struct
        let has_structs = schema.types.values().any(|t| {
            matches!(t.kind, TypeKind::InputObject | TypeKind::Object)
                && t.name != "Query"
                && t.name != "Mutation"
                && t.name != "Subscription"
        });
        // Check if we need to import TypeAlias
        let has_unions = schema.types.values().any(|t| t.kind == TypeKind::Union);

        code.push_str("from __future__ import annotations\n");

        if has_enums {
            code.push_str("from enum import Enum\n");
        }
        if has_structs {
            code.push_str("from msgspec import Struct\n");
        }
        if has_unions {
            code.push_str("from typing import TypeAlias\n");
        }

        code.push('\n');

        // Create type mapper for Python
        let mapper = TypeMapper::new(TargetLanguage::Python, Some(schema));

        // Generate enums first
        for type_def in schema.types.values() {
            if type_def.kind == TypeKind::Enum {
                code.push_str(&format!("class {}(str, Enum):\n", type_def.name));
                if let Some(desc) = &type_def.description {
                    code.push_str(&format!(
                        "    \"\"\"{}\"\"\"\n",
                        escape_for_docstring(desc, EscapeContext::Python)
                    ));
                }
                for value in &type_def.enum_values {
                    if let Some(desc) = &value.description {
                        code.push_str(&format!("    # {desc}\n"));
                    }
                    code.push_str(&format!("    {} = \"{}\"\n", value.name, value.name));
                }
                code.push_str("\n\n");
            }
        }

        // Generate input objects and types
        for type_def in schema.types.values() {
            if type_def.kind == TypeKind::InputObject {
                code.push_str(&format!(
                    "class {}(Struct, frozen=True, kw_only=True):\n",
                    type_def.name
                ));
                if let Some(desc) = &type_def.description {
                    code.push_str(&format!(
                        "    \"\"\"{}\"\"\"\n",
                        escape_for_docstring(desc, EscapeContext::Python)
                    ));
                } else {
                    code.push_str(&format!("    \"\"\"GraphQL input type {}.\"\"\"\n", type_def.name));
                }
                if type_def.input_fields.is_empty() {
                    code.push_str("    pass\n");
                } else {
                    for field in &type_def.input_fields {
                        if let Some(desc) = &field.description {
                            code.push_str(&format!("    # {desc}\n"));
                        }
                        let py_type = mapper.map_type_with_list_nullability(
                            &field.type_name,
                            field.is_nullable,
                            field.is_list,
                            field.list_item_nullable,
                        );
                        code.push_str(&format!("    {}: {}\n", field.name, py_type));
                    }
                }
                code.push_str("\n\n");
            } else if type_def.kind == TypeKind::Object
                && type_def.name != "Query"
                && type_def.name != "Mutation"
                && type_def.name != "Subscription"
            {
                code.push_str(&format!(
                    "class {}(Struct, frozen=True, kw_only=True):\n",
                    type_def.name
                ));
                if let Some(desc) = &type_def.description {
                    code.push_str(&format!(
                        "    \"\"\"{}\"\"\"\n",
                        escape_for_docstring(desc, EscapeContext::Python)
                    ));
                } else {
                    code.push_str(&format!("    \"\"\"GraphQL object type {}.\"\"\"\n", type_def.name));
                }
                if type_def.fields.is_empty() {
                    code.push_str("    pass\n");
                } else {
                    for field in &type_def.fields {
                        if let Some(desc) = &field.description {
                            code.push_str(&format!("    # {desc}\n"));
                        }
                        let py_type = mapper.map_type_with_list_nullability(
                            &field.type_name,
                            field.is_nullable,
                            field.is_list,
                            field.list_item_nullable,
                        );
                        code.push_str(&format!("    {}: {}\n", field.name, py_type));
                    }
                }
                code.push_str("\n\n");
            } else if type_def.kind == TypeKind::Union {
                // Union types: use TypeAlias with quoted string for forward references
                // Quote the value to avoid "used before definition" errors in mypy --strict
                // The TypeAlias annotation tells mypy this is a type alias, not a string variable
                let members = type_def.possible_types.join(" | ");
                code.push_str(&format!("{}: TypeAlias = \"{}\"\n", type_def.name, members));
                code.push('\n');
            }
        }

        Ok(code)
    }

    fn generate_resolvers(&self, schema: &GraphQLSchema) -> Result<String> {
        let mut code = String::new();
        code.push_str("#!/usr/bin/env python3\n");
        code.push_str("# ruff: noqa: EXE001\n");
        code.push_str("# DO NOT EDIT - Auto-generated by Spikard CLI\n");
        code.push_str("#\n");
        code.push_str("# This file was automatically generated from your GraphQL schema.\n");
        code.push_str("# Any manual changes will be overwritten on the next generation.\n");
        code.push_str("\"\"\"GraphQL resolver functions.\"\"\"\n\n");
        code.push_str("from __future__ import annotations\n\n");
        if !schema.subscriptions.is_empty() {
            code.push_str("from collections.abc import AsyncIterator\n");
        }
        code.push_str("from typing import TYPE_CHECKING\n\n");
        code.push_str("if TYPE_CHECKING:\n");
        code.push_str("    from graphql import GraphQLResolveInfo\n");

        // Collect all type names used in resolver return types and arguments
        let mut used_types: std::collections::HashSet<String> = std::collections::HashSet::new();

        for query in &schema.queries {
            // Add return type
            if let Some(type_name) = extract_base_type_name(&query.type_name)
                && is_custom_type(&type_name, schema)
            {
                used_types.insert(type_name);
            }
            // Add argument types
            for arg in &query.arguments {
                if let Some(type_name) = extract_base_type_name(&arg.type_name)
                    && is_custom_type(&type_name, schema)
                {
                    used_types.insert(type_name);
                }
            }
        }

        for mutation in &schema.mutations {
            // Add return type
            if let Some(type_name) = extract_base_type_name(&mutation.type_name)
                && is_custom_type(&type_name, schema)
            {
                used_types.insert(type_name);
            }
            // Add argument types
            for arg in &mutation.arguments {
                if let Some(type_name) = extract_base_type_name(&arg.type_name)
                    && is_custom_type(&type_name, schema)
                {
                    used_types.insert(type_name);
                }
            }
        }

        for subscription in &schema.subscriptions {
            if let Some(type_name) = extract_base_type_name(&subscription.type_name)
                && is_custom_type(&type_name, schema)
            {
                used_types.insert(type_name);
            }
            for arg in &subscription.arguments {
                if let Some(type_name) = extract_base_type_name(&arg.type_name)
                    && is_custom_type(&type_name, schema)
                {
                    used_types.insert(type_name);
                }
            }
        }

        // Add imports for all used types
        if !used_types.is_empty() {
            let mut sorted_types: Vec<_> = used_types.iter().collect();
            sorted_types.sort();
            let types_list = sorted_types.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", ");
            code.push_str(&format!("from .types import {types_list}\n"));
        }

        code.push('\n');

        // Create type mapper for Python
        let _mapper = TypeMapper::new(TargetLanguage::Python, Some(schema));

        // Helper closure to format resolver signature
        let format_resolver =
            |name: &str, field: &crate::codegen::graphql::spec_parser::GraphQLField, schema: &GraphQLSchema| {
                let mut sig = format!(
                    "async def resolve_{}(parent: dict[str, object], info: GraphQLResolveInfo",
                    to_snake_case(name)
                );
                let needs_builtin_noqa = field.arguments.iter().any(|arg| is_python_builtin_name(&arg.name));

                let mapper = TypeMapper::new(TargetLanguage::Python, Some(schema));
                for arg in &field.arguments {
                    let arg_type = mapper.map_type_with_list_nullability(
                        &arg.type_name,
                        arg.is_nullable,
                        arg.is_list,
                        arg.list_item_nullable,
                    );
                    sig.push_str(&format!(", {}: {}", arg.name, arg_type));
                }

                let py_type = mapper.map_type_with_list_nullability(
                    &field.type_name,
                    field.is_nullable,
                    field.is_list,
                    field.list_item_nullable,
                );
                sig.push_str(&format!(") -> {py_type}:"));
                if needs_builtin_noqa {
                    sig.push_str("  # noqa: A002");
                }
                sig
            };

        // Query resolvers
        if !schema.queries.is_empty() {
            code.push_str("# Query resolvers\n\n");
            for field in &schema.queries {
                code.push_str(&format_resolver(&field.name, field, schema));
                code.push('\n');
                code.push_str("    \"\"\"Resolve query field.\"\"\"\n");
                code.push_str("    raise NotImplementedError\n\n");
            }
            code.push('\n');
        }

        // Mutation resolvers
        if !schema.mutations.is_empty() {
            code.push_str("# Mutation resolvers\n\n");
            for field in &schema.mutations {
                code.push_str(&format_resolver(&field.name, field, schema));
                code.push('\n');
                code.push_str("    \"\"\"Resolve mutation field.\"\"\"\n");
                code.push_str("    raise NotImplementedError\n\n");
            }
        }

        if !schema.subscriptions.is_empty() {
            code.push_str("\n# Subscription resolvers\n\n");
            for field in &schema.subscriptions {
                let mapper = TypeMapper::new(TargetLanguage::Python, Some(schema));
                let field_type = mapper.map_type_with_list_nullability(
                    &field.type_name,
                    field.is_nullable,
                    field.is_list,
                    field.list_item_nullable,
                );
                let needs_builtin_noqa = field.arguments.iter().any(|arg| is_python_builtin_name(&arg.name));

                let mut source_signature = format!(
                    "async def subscribe_{}(parent: dict[str, object], info: GraphQLResolveInfo",
                    to_snake_case(&field.name)
                );
                for arg in &field.arguments {
                    let arg_type = mapper.map_type_with_list_nullability(
                        &arg.type_name,
                        arg.is_nullable,
                        arg.is_list,
                        arg.list_item_nullable,
                    );
                    source_signature.push_str(&format!(", {}: {}", arg.name, arg_type));
                }
                source_signature.push_str(&format!(") -> AsyncIterator[{field_type}]:"));
                if needs_builtin_noqa {
                    source_signature.push_str("  # noqa: A002");
                }
                code.push_str(&source_signature);
                code.push('\n');
                code.push_str("    \"\"\"Stream subscription events.\"\"\"\n");
                code.push_str("    raise NotImplementedError\n\n");

                let mut resolver_signature = format!(
                    "async def resolve_{}(value: {}, info: GraphQLResolveInfo",
                    to_snake_case(&field.name),
                    field_type
                );
                for arg in &field.arguments {
                    let arg_type = mapper.map_type_with_list_nullability(
                        &arg.type_name,
                        arg.is_nullable,
                        arg.is_list,
                        arg.list_item_nullable,
                    );
                    resolver_signature.push_str(&format!(", {}: {}", arg.name, arg_type));
                }
                resolver_signature.push_str(&format!(") -> {field_type}:"));
                if needs_builtin_noqa {
                    resolver_signature.push_str("  # noqa: A002");
                }
                code.push_str(&resolver_signature);
                code.push('\n');
                code.push_str("    \"\"\"Resolve a streamed subscription event.\"\"\"\n");
                code.push_str("    raise NotImplementedError\n\n");
            }
        }

        Ok(code)
    }

    fn generate_schema_definition(&self, schema: &GraphQLSchema) -> Result<String> {
        let mut code = String::new();

        // Header with generation info
        code.push_str("#!/usr/bin/env python3\n");
        code.push_str("# ruff: noqa: EXE001\n");
        code.push_str("# DO NOT EDIT - Auto-generated by Spikard CLI\n");
        code.push_str("#\n");
        code.push_str("# This file was automatically generated from your GraphQL schema.\n");
        code.push_str("# Any manual changes will be overwritten on the next generation.\n");
        code.push_str("\"\"\"GraphQL Schema Definition.\"\"\"\n\n");
        code.push_str("from __future__ import annotations\n\n");

        // Build imports based on what's in the schema
        let mut ariadne_imports = vec!["make_executable_schema", "QueryType"];
        if !schema.mutations.is_empty() {
            ariadne_imports.push("MutationType");
        }
        if !schema.subscriptions.is_empty() {
            ariadne_imports.push("SubscriptionType");
        }
        code.push_str(&format!("from ariadne import {}\n\n", ariadne_imports.join(", ")));

        // Reconstruct and embed the SDL using SdlBuilder
        let sdl = SdlBuilder::new(schema).build();
        code.push_str("# GraphQL Schema Definition Language (SDL)\n");
        code.push_str("#\n");
        code.push_str("# Defines all types, queries, mutations, and subscriptions\n");
        code.push_str("# in the GraphQL schema.\n");
        code.push_str("type_defs = \"\"\"\n");

        // Embed the SDL in triple-quoted string with proper indentation
        for line in sdl.lines() {
            if line.is_empty() {
                code.push('\n');
            } else {
                code.push_str("    ");
                code.push_str(line);
                code.push('\n');
            }
        }

        code.push_str("\"\"\"\n\n");

        // Create QueryType instance
        code.push_str("# Query resolvers\n");
        code.push_str("query = QueryType()\n\n");
        code.push_str("def _register_query_resolvers() -> None:\n");
        if schema.queries.is_empty() {
            code.push_str("    return\n\n");
        } else {
            for field in &schema.queries {
                let resolver_name = format!("resolve_{}", to_snake_case(&field.name));
                code.push_str(&format!("    resolver = globals().get(\"{resolver_name}\")\n"));
                code.push_str("    if resolver is not None:\n");
                code.push_str(&format!("        query.set_field(\"{}\", resolver)\n", field.name));
            }
            code.push('\n');
        }
        code.push_str("_register_query_resolvers()\n\n");

        // Create MutationType instance (if mutations exist)
        if !schema.mutations.is_empty() {
            code.push_str("# Mutation resolvers\n");
            code.push_str("mutation = MutationType()\n\n");
            code.push_str("def _register_mutation_resolvers() -> None:\n");
            for field in &schema.mutations {
                let resolver_name = format!("resolve_{}", to_snake_case(&field.name));
                code.push_str(&format!("    resolver = globals().get(\"{resolver_name}\")\n"));
                code.push_str("    if resolver is not None:\n");
                code.push_str(&format!("        mutation.set_field(\"{}\", resolver)\n", field.name));
            }
            code.push('\n');
            code.push_str("_register_mutation_resolvers()\n\n");
        }

        // Create SubscriptionType instance (if subscriptions exist)
        if !schema.subscriptions.is_empty() {
            code.push_str("# Subscription resolvers\n");
            code.push_str("subscription = SubscriptionType()\n\n");
            code.push_str("def _register_subscription_resolvers() -> None:\n");
            for field in &schema.subscriptions {
                let source_name = format!("subscribe_{}", to_snake_case(&field.name));
                let resolver_name = format!("resolve_{}", to_snake_case(&field.name));
                code.push_str(&format!("    source = globals().get(\"{source_name}\")\n"));
                code.push_str("    if source is not None:\n");
                code.push_str(&format!(
                    "        subscription.set_source(\"{}\", source)\n",
                    field.name
                ));
                code.push_str(&format!("    resolver = globals().get(\"{resolver_name}\")\n"));
                code.push_str("    if resolver is not None:\n");
                code.push_str(&format!(
                    "        subscription.set_field(\"{}\", resolver)\n",
                    field.name
                ));
            }
            code.push('\n');
            code.push_str("_register_subscription_resolvers()\n\n");
        }

        // Build the executable schema
        code.push_str("# Executable GraphQL Schema\n");
        code.push_str("#\n");
        code.push_str("# Combines the type definitions with resolvers to create\n");
        code.push_str("# a fully functional GraphQL schema ready for use with\n");
        code.push_str("# Ariadne GraphQL or similar frameworks.\n");

        // Determine which resolvers to pass
        let mut resolvers = vec!["query".to_string()];
        if !schema.mutations.is_empty() {
            resolvers.push("mutation".to_string());
        }
        if !schema.subscriptions.is_empty() {
            resolvers.push("subscription".to_string());
        }

        code.push_str("schema = make_executable_schema(type_defs, ");
        code.push_str(&resolvers.join(", "));
        code.push_str(")\n\n");

        // Export type_defs for advanced use cases
        code.push_str("# Exported for advanced use cases where the SDL\n");
        code.push_str("# string might be needed directly.\n");
        code.push_str("__all__ = [\"schema\", \"type_defs\"]\n");

        Ok(code)
    }

    /// Override `generate_complete` to merge sections without duplicate headers
    ///
    /// When generating a complete file, each section has its own header (shebang,
    /// comments, docstrings). This reorganizes the code to have:
    /// 1. types header + imports from types section
    /// 2. external imports from resolvers/schema
    /// 3. all code from all sections
    fn generate_complete(&self, schema: &GraphQLSchema) -> Result<String> {
        let types = self.generate_types(schema)?;
        let resolvers = self.generate_resolvers(schema)?;
        let schema_def = self.generate_schema_definition(schema)?;

        // Extract imports and code, separately tracking what was in types section
        fn extract_header_imports_and_code(s: &str) -> (Vec<String>, Vec<String>, Vec<String>) {
            let mut header_lines: Vec<String> = Vec::new(); // shebang, comments, docstring
            let mut imports: Vec<String> = Vec::new();
            let mut code: Vec<String> = Vec::new();
            let mut in_header_docstring = false;
            let mut in_type_checking_block = false;
            let mut past_header = false;
            let mut found_import_section = false;

            for line in s.lines() {
                let trimmed = line.trim();

                // Skip header section before code starts
                if !past_header {
                    // Handle header docstrings (module-level docstrings at top)
                    if trimmed.starts_with("\"\"\"") {
                        // One-line docstring: starts and ends with """
                        if trimmed.len() >= 6 && trimmed.ends_with("\"\"\"") && !trimmed.starts_with("\"\"\"\"") {
                            // Skip one-line docstring entirely
                            header_lines.push(line.to_string());
                            continue;
                        }
                        // Multi-line docstring: toggle state
                        header_lines.push(line.to_string());
                        in_header_docstring = !in_header_docstring;
                        continue;
                    }

                    // Lines inside multi-line docstring
                    if in_header_docstring {
                        header_lines.push(line.to_string());
                        continue;
                    }

                    // Lines in preamble (shebang, DO NOT EDIT, etc.)
                    if trimmed.starts_with("#!/")
                        || trimmed.starts_with("# ruff:")
                        || trimmed.starts_with("# DO NOT EDIT")
                        || trimmed == "#"
                        || (trimmed.starts_with("# This file") && trimmed.contains("generated"))
                        || (trimmed.starts_with("# Any manual"))
                    {
                        header_lines.push(line.to_string());
                        continue;
                    }

                    // Skip empty lines in header
                    if trimmed.is_empty() {
                        continue;
                    }

                    // We've hit actual content; mark header as passed
                    past_header = true;
                }

                if in_type_checking_block {
                    if trimmed.is_empty() || line.starts_with(' ') || line.starts_with('\t') {
                        code.push(line.to_string());
                        if trimmed.is_empty() {
                            in_type_checking_block = false;
                        }
                        continue;
                    }
                    in_type_checking_block = false;
                }

                // Now past header - categorize the rest
                // Skip __future__ imports - only keep in types section
                if trimmed.starts_with("from __future__") {
                    if !found_import_section {
                        imports.push(line.to_string());
                        found_import_section = true;
                    }
                    continue;
                }

                if trimmed == "if TYPE_CHECKING:" {
                    code.push(line.to_string());
                    in_type_checking_block = true;
                    found_import_section = true;
                    continue;
                }

                // Categorize: imports vs. code
                if trimmed.starts_with("import ") || trimmed.starts_with("from ") {
                    imports.push(line.to_string());
                    found_import_section = true;
                } else {
                    if trimmed.is_empty() && !found_import_section && imports.is_empty() {
                        // Skip empty lines before imports start
                        continue;
                    }
                    code.push(line.to_string());
                }
            }

            (header_lines, imports, code)
        }

        let (types_header, types_imports, types_code) = extract_header_imports_and_code(&types);
        let (_resolvers_header, resolvers_imports, resolvers_code) = extract_header_imports_and_code(&resolvers);
        let (_schema_def_header, schema_def_imports, schema_def_code) = extract_header_imports_and_code(&schema_def);

        // Collect all external imports (skip "from .types" imports)
        let mut all_imports: Vec<String> = types_imports;
        for imp in resolvers_imports.iter().chain(schema_def_imports.iter()) {
            let trimmed = imp.trim();
            // Skip imports from .types (relative imports from types module)
            if trimmed.starts_with("from .types") {
                continue;
            }
            if !all_imports.contains(imp) {
                all_imports.push(imp.clone());
            }
        }

        // Build final result with proper Python import structure:
        // 1. Header (shebang, comments)
        // 2. All imports
        // 3. All code (type definitions + resolvers + schema)
        let mut result = String::new();

        // Add header
        for header_line in types_header {
            result.push_str(&header_line);
            result.push('\n');
        }

        // Add all imports
        for imp in &all_imports {
            result.push_str(imp);
            result.push('\n');
        }

        // Add types code
        if !types_code.is_empty() {
            result.push('\n');
            for line in types_code {
                result.push_str(&line);
                result.push('\n');
            }
        }

        // Add resolvers code
        if !resolvers_code.is_empty() {
            result.push('\n');
            for line in resolvers_code {
                result.push_str(&line);
                result.push('\n');
            }
        }

        // Add schema definition code
        if !schema_def_code.is_empty() {
            result.push('\n');
            for line in schema_def_code {
                result.push_str(&line);
                result.push('\n');
            }
        }

        // Trim excess trailing newlines and add single newline
        result = result.trim_end().to_string();
        result.push('\n');

        Ok(result)
    }
}

fn is_python_builtin_name(name: &str) -> bool {
    matches!(
        name,
        "abs"
            | "all"
            | "any"
            | "ascii"
            | "bin"
            | "bool"
            | "bytes"
            | "callable"
            | "chr"
            | "dict"
            | "dir"
            | "enumerate"
            | "filter"
            | "float"
            | "format"
            | "frozenset"
            | "hash"
            | "hex"
            | "id"
            | "input"
            | "int"
            | "iter"
            | "len"
            | "list"
            | "map"
            | "max"
            | "min"
            | "next"
            | "object"
            | "oct"
            | "open"
            | "ord"
            | "pow"
            | "print"
            | "range"
            | "repr"
            | "reversed"
            | "round"
            | "set"
            | "slice"
            | "sorted"
            | "str"
            | "sum"
            | "tuple"
            | "type"
            | "vars"
            | "zip"
    )
}

/// Extract the base type name from a GraphQL type string.
///
/// Removes wrappers like !, [, ] to get the raw type name.
/// Examples: "String!" → "String", "[User]" → "User", "Post!" → "Post"
fn extract_base_type_name(type_name: &str) -> Option<String> {
    let clean = type_name.trim_matches(|c| c == '!' || c == '[' || c == ']');
    if clean.is_empty() {
        None
    } else {
        Some(clean.to_string())
    }
}

/// Check if a type is a custom type (not a built-in scalar).
///
/// Built-in scalars: String, Int, Float, Boolean, ID, `DateTime`, Date, Time, JSON, Upload
fn is_custom_type(type_name: &str, schema: &GraphQLSchema) -> bool {
    let built_ins = [
        "String", "Int", "Float", "Boolean", "ID", "DateTime", "Date", "Time", "JSON", "Upload",
    ];

    if built_ins.contains(&type_name) {
        return false;
    }

    // Check if it's defined in the schema
    schema.types.contains_key(type_name)
}