ggen-core 26.7.2

Core graph-aware code generation engine
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
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
//! Python code generation for FastAPI microservices
//!
//! This module generates FastAPI services, Pydantic v2 models, SQLAlchemy 2.0
//! async repositories, pytest scaffolding, and requirements.txt from specification
//! data derived from RDF ontologies.
//!
//! # WvdA / Armstrong compliance
//! - All SQLAlchemy queries include `execution_options(timeout=30)` (deadlock prevention)
//! - FastAPI uses `lifespan` context manager for proper startup/shutdown
//! - All error handlers use proper HTTP status codes (no silent failures)

use std::fmt::Write;

// ---------------------------------------------------------------------------
// Domain types
// ---------------------------------------------------------------------------

/// A single field in a Pydantic model or SQLAlchemy table.
#[derive(Clone, Debug)]
pub struct Field {
    /// Python identifier (snake_case), e.g. `"order_id"`
    pub name: String,
    /// Python type annotation, e.g. `"str"`, `"int"`, `"UUID"`, `"datetime"`
    pub field_type: String,
    /// Whether the field may be `None` (generates `Optional[T]`)
    pub optional: bool,
    /// Optional default value literal, e.g. `"None"`, `"0"`, `"\"pending\""`
    pub default: Option<String>,
}

/// An HTTP endpoint specification used when generating pytest scaffolding.
#[derive(Clone, Debug)]
pub struct Endpoint {
    /// HTTP method in upper-case, e.g. `"GET"`, `"POST"`, `"DELETE"`
    pub method: String,
    /// URL path, e.g. `"/orders/{order_id}"`
    pub path: String,
    /// Python function name for the route handler, e.g. `"get_order"`
    pub handler: String,
    /// Expected HTTP success status code, e.g. `200`, `201`, `204`
    pub status_code: u16,
}

// ---------------------------------------------------------------------------
// Generator struct
// ---------------------------------------------------------------------------

/// Python microservice code generator (FastAPI / Pydantic v2 / SQLAlchemy 2.0)
pub struct PythonGenerator;

impl PythonGenerator {
    // -----------------------------------------------------------------------
    // generate_fastapi_service
    // -----------------------------------------------------------------------

    /// Generate a complete FastAPI service module.
    ///
    /// The service includes:
    /// - `lifespan` context manager for startup/shutdown (Armstrong let-it-crash)
    /// - `/health` endpoint returning `{"status": "ok", "service": "<name>"}`
    /// - Logging setup
    /// - Router stub for domain routes
    ///
    /// # Arguments
    /// * `service_name` - Human-readable service name, e.g. `"OrderService"`
    /// * `port`         - Port the service listens on (used in log message only)
    /// * `description`  - One-line description embedded in the OpenAPI title
    pub fn generate_fastapi_service(
        service_name: &str, port: u16, description: &str,
    ) -> Result<String, String> {
        let mut out = String::new();
        let snake = to_snake(service_name);

        writeln!(out, "\"\"\"").map_err(|e| e.to_string())?;
        writeln!(out, "{} — {}", service_name, description).map_err(|e| e.to_string())?;
        writeln!(out, "\nAuto-generated by ggen. Edit with care.").map_err(|e| e.to_string())?;
        writeln!(out, "\"\"\"\n").map_err(|e| e.to_string())?;

        writeln!(out, "from contextlib import asynccontextmanager").map_err(|e| e.to_string())?;
        writeln!(out, "import logging\n").map_err(|e| e.to_string())?;
        writeln!(out, "from fastapi import FastAPI, HTTPException, status")
            .map_err(|e| e.to_string())?;
        writeln!(out, "from fastapi.responses import JSONResponse").map_err(|e| e.to_string())?;
        writeln!(out, "from {snake}_router import router as {snake}_router\n")
            .map_err(|e| e.to_string())?;

        writeln!(out, "logger = logging.getLogger(__name__)\n").map_err(|e| e.to_string())?;

        // lifespan context manager — Armstrong: let-it-crash on startup failure
        writeln!(out, "\n@asynccontextmanager").map_err(|e| e.to_string())?;
        writeln!(out, "async def lifespan(app: FastAPI):").map_err(|e| e.to_string())?;
        writeln!(
            out,
            "    logger.info(\"{service_name} starting on port {port}\")"
        )
        .map_err(|e| e.to_string())?;
        writeln!(out, "    # Initialise DB pool, cache, OTEL exporter here")
            .map_err(|e| e.to_string())?;
        writeln!(out, "    yield").map_err(|e| e.to_string())?;
        writeln!(
            out,
            "    # Armstrong: cleanup — let downstream errors propagate"
        )
        .map_err(|e| e.to_string())?;
        writeln!(
            out,
            "    logger.info(\"{service_name} shutdown complete\")\n"
        )
        .map_err(|e| e.to_string())?;

        // FastAPI app
        writeln!(out, "\napp = FastAPI(").map_err(|e| e.to_string())?;
        writeln!(out, "    title=\"{service_name}\",").map_err(|e| e.to_string())?;
        writeln!(out, "    description=\"{description}\",").map_err(|e| e.to_string())?;
        writeln!(out, "    version=\"1.0.0\",").map_err(|e| e.to_string())?;
        writeln!(out, "    lifespan=lifespan,").map_err(|e| e.to_string())?;
        writeln!(out, ")\n").map_err(|e| e.to_string())?;

        // Include domain router
        writeln!(
            out,
            "app.include_router({snake}_router, prefix=\"/api/v1\")\n"
        )
        .map_err(|e| e.to_string())?;

        // Health endpoint
        writeln!(out, "\n@app.get(\"/health\", tags=[\"ops\"])").map_err(|e| e.to_string())?;
        writeln!(out, "async def health():").map_err(|e| e.to_string())?;
        writeln!(
            out,
            "    \"\"\"Liveness probe — returns 200 when the process is running.\"\"\""
        )
        .map_err(|e| e.to_string())?;
        writeln!(
            out,
            "    return {{\"status\": \"ok\", \"service\": \"{service_name}\"}}\n"
        )
        .map_err(|e| e.to_string())?;

        // Generic exception handler — no silent failures
        writeln!(out, "\n@app.exception_handler(Exception)").map_err(|e| e.to_string())?;
        writeln!(
            out,
            "async def unhandled_exception_handler(request, exc: Exception):"
        )
        .map_err(|e| e.to_string())?;
        writeln!(
            out,
            "    logger.error(\"Unhandled exception: %s\", exc, exc_info=True)"
        )
        .map_err(|e| e.to_string())?;
        writeln!(
            out,
            "    return JSONResponse(\n        status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,"
        )
        .map_err(|e| e.to_string())?;
        writeln!(
            out,
            "        content={{\"detail\": \"Internal server error\"}},\n    )"
        )
        .map_err(|e| e.to_string())?;

        Ok(out)
    }

    // -----------------------------------------------------------------------
    // generate_pydantic_model
    // -----------------------------------------------------------------------

    /// Generate a Pydantic v2 model class.
    ///
    /// The generated model:
    /// - Uses `model_config = {"from_attributes": True}` (ORM mode)
    /// - Emits `Optional[T]` with `= None` for optional fields
    /// - Adds a `json_schema_extra` example block
    /// - Includes a `model_validator` stub for cross-field validation
    ///
    /// # Arguments
    /// * `model_name` - PascalCase class name, e.g. `"Order"`
    /// * `fields`     - Slice of `Field` descriptors
    pub fn generate_pydantic_model(model_name: &str, fields: &[Field]) -> Result<String, String> {
        let mut out = String::new();

        writeln!(out, "\"\"\"").map_err(|e| e.to_string())?;
        writeln!(out, "Pydantic v2 model for {}.", model_name).map_err(|e| e.to_string())?;
        writeln!(out, "\nAuto-generated by ggen. Edit with care.").map_err(|e| e.to_string())?;
        writeln!(out, "\"\"\"\n").map_err(|e| e.to_string())?;

        writeln!(out, "from __future__ import annotations\n").map_err(|e| e.to_string())?;
        writeln!(out, "from datetime import datetime").map_err(|e| e.to_string())?;
        writeln!(out, "from typing import Optional").map_err(|e| e.to_string())?;
        writeln!(out, "from uuid import UUID\n").map_err(|e| e.to_string())?;
        writeln!(
            out,
            "from pydantic import BaseModel, Field, model_validator\n"
        )
        .map_err(|e| e.to_string())?;

        writeln!(out, "\nclass {model_name}(BaseModel):").map_err(|e| e.to_string())?;
        writeln!(out, "    model_config = {{\"from_attributes\": True}}\n")
            .map_err(|e| e.to_string())?;

        // Emit fields
        for field in fields {
            let type_annotation = if field.optional {
                format!("Optional[{}]", field.field_type)
            } else {
                field.field_type.clone()
            };

            let default_part = if field.optional {
                let default_val = field.default.as_deref().unwrap_or("None");
                format!(" = Field(default={default_val})")
            } else if let Some(ref d) = field.default {
                format!(" = Field(default={d})")
            } else {
                String::new()
            };

            writeln!(
                out,
                "    {}: {}{}",
                field.name, type_annotation, default_part
            )
            .map_err(|e| e.to_string())?;
        }

        // json_schema_extra example
        writeln!(out, "\n    model_config = {{").map_err(|e| e.to_string())?;
        writeln!(out, "        \"from_attributes\": True,").map_err(|e| e.to_string())?;
        writeln!(out, "        \"json_schema_extra\": {{").map_err(|e| e.to_string())?;
        writeln!(out, "            \"example\": {{").map_err(|e| e.to_string())?;
        for field in fields {
            let example_val = example_value_for_type(&field.field_type, field.optional);
            writeln!(out, "                \"{}\": {},", field.name, example_val)
                .map_err(|e| e.to_string())?;
        }
        writeln!(out, "            }}").map_err(|e| e.to_string())?;
        writeln!(out, "        }}").map_err(|e| e.to_string())?;
        writeln!(out, "    }}\n").map_err(|e| e.to_string())?;

        // Cross-field validator stub
        writeln!(out, "    @model_validator(mode=\"after\")").map_err(|e| e.to_string())?;
        writeln!(out, "    def validate_model(self) -> \"{model_name}\":")
            .map_err(|e| e.to_string())?;
        writeln!(
            out,
            "        \"\"\"Cross-field validation hook — add domain invariants here.\"\"\""
        )
        .map_err(|e| e.to_string())?;
        writeln!(out, "        return self").map_err(|e| e.to_string())?;

        Ok(out)
    }

    // -----------------------------------------------------------------------
    // generate_sqlalchemy_repository
    // -----------------------------------------------------------------------

    /// Generate a SQLAlchemy 2.0 async repository with full CRUD.
    ///
    /// WvdA compliance: every query uses `.execution_options(timeout=30)` to
    /// prevent deadlocks (boundedness guarantee).
    ///
    /// # Arguments
    /// * `model_name` - PascalCase model name, e.g. `"Order"`
    /// * `fields`     - Slice of `Field` descriptors (used to build the ORM table)
    pub fn generate_sqlalchemy_repository(
        model_name: &str, fields: &[Field],
    ) -> Result<String, String> {
        let mut out = String::new();
        let table_name = format!("{}s", to_snake(model_name));
        let snake_model = to_snake(model_name);

        writeln!(out, "\"\"\"").map_err(|e| e.to_string())?;
        writeln!(out, "SQLAlchemy 2.0 async repository for {}.", model_name)
            .map_err(|e| e.to_string())?;
        writeln!(
            out,
            "\nWvdA: all queries use execution_options(timeout=30)."
        )
        .map_err(|e| e.to_string())?;
        writeln!(out, "\nAuto-generated by ggen. Edit with care.").map_err(|e| e.to_string())?;
        writeln!(out, "\"\"\"\n").map_err(|e| e.to_string())?;

        writeln!(out, "from __future__ import annotations\n").map_err(|e| e.to_string())?;
        writeln!(out, "from typing import List, Optional").map_err(|e| e.to_string())?;
        writeln!(out, "from uuid import UUID\n").map_err(|e| e.to_string())?;
        writeln!(
            out,
            "from sqlalchemy import Column, String, Integer, Boolean, DateTime, select, update, delete"
        )
        .map_err(|e| e.to_string())?;
        writeln!(
            out,
            "from sqlalchemy.dialects.postgresql import UUID as PG_UUID"
        )
        .map_err(|e| e.to_string())?;
        writeln!(out, "from sqlalchemy.ext.asyncio import AsyncSession")
            .map_err(|e| e.to_string())?;
        writeln!(
            out,
            "from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column\n"
        )
        .map_err(|e| e.to_string())?;

        // Base
        writeln!(out, "\nclass Base(DeclarativeBase):").map_err(|e| e.to_string())?;
        writeln!(out, "    pass\n").map_err(|e| e.to_string())?;

        // ORM model
        writeln!(out, "\nclass {model_name}ORM(Base):").map_err(|e| e.to_string())?;
        writeln!(
            out,
            "    \"\"\"SQLAlchemy ORM mapping for {model_name}.\"\"\""
        )
        .map_err(|e| e.to_string())?;
        writeln!(out, "\n    __tablename__ = \"{table_name}\"\n").map_err(|e| e.to_string())?;

        for field in fields {
            let sa_type = sqlalchemy_type_for(&field.field_type);
            let nullable_part = if field.optional {
                ", nullable=True"
            } else {
                ""
            };
            writeln!(
                out,
                "    {}: Mapped[{}] = mapped_column({}{nullable_part})",
                field.name, field.field_type, sa_type
            )
            .map_err(|e| e.to_string())?;
        }

        writeln!(out).map_err(|e| e.to_string())?;

        // Repository class
        writeln!(out, "\nclass {model_name}Repository:").map_err(|e| e.to_string())?;
        writeln!(
            out,
            "    \"\"\"Async CRUD repository for {model_name}.\"\"\"\n"
        )
        .map_err(|e| e.to_string())?;
        writeln!(
            out,
            "    def __init__(self, session: AsyncSession) -> None:"
        )
        .map_err(|e| e.to_string())?;
        writeln!(out, "        self._session = session\n").map_err(|e| e.to_string())?;

        // create
        writeln!(
            out,
            "    async def create(self, {snake_model}: {model_name}ORM) -> {model_name}ORM:"
        )
        .map_err(|e| e.to_string())?;
        writeln!(
            out,
            "        \"\"\"Persist a new {model_name} and return the managed instance.\"\"\""
        )
        .map_err(|e| e.to_string())?;
        writeln!(out, "        self._session.add({snake_model})").map_err(|e| e.to_string())?;
        writeln!(out, "        await self._session.flush()").map_err(|e| e.to_string())?;
        writeln!(out, "        await self._session.refresh({snake_model})")
            .map_err(|e| e.to_string())?;
        writeln!(out, "        return {snake_model}\n").map_err(|e| e.to_string())?;

        // get_by_id
        writeln!(
            out,
            "    async def get_by_id(self, record_id: UUID) -> Optional[{model_name}ORM]:"
        )
        .map_err(|e| e.to_string())?;
        writeln!(
            out,
            "        \"\"\"Retrieve a {model_name} by primary key. Returns None if not found.\"\"\""
        )
        .map_err(|e| e.to_string())?;
        writeln!(
            out,
            "        # WvdA: execution_options(timeout=30) prevents query deadlock"
        )
        .map_err(|e| e.to_string())?;
        writeln!(
            out,
            "        stmt = (\n            select({model_name}ORM)\n            .where({model_name}ORM.id == record_id)\n            .execution_options(timeout=30)\n        )"
        )
        .map_err(|e| e.to_string())?;
        writeln!(out, "        result = await self._session.execute(stmt)")
            .map_err(|e| e.to_string())?;
        writeln!(out, "        return result.scalars().first()\n").map_err(|e| e.to_string())?;

        // list_all
        writeln!(
            out,
            "    async def list_all(self, limit: int = 100) -> List[{model_name}ORM]:"
        )
        .map_err(|e| e.to_string())?;
        writeln!(
            out,
            "        \"\"\"Return up to *limit* records (WvdA boundedness: default 100).\"\"\""
        )
        .map_err(|e| e.to_string())?;
        writeln!(
            out,
            "        stmt = (\n            select({model_name}ORM)\n            .limit(limit)\n            .execution_options(timeout=30)\n        )"
        )
        .map_err(|e| e.to_string())?;
        writeln!(out, "        result = await self._session.execute(stmt)")
            .map_err(|e| e.to_string())?;
        writeln!(out, "        return list(result.scalars().all())\n")
            .map_err(|e| e.to_string())?;

        // update
        writeln!(
            out,
            "    async def update(self, record_id: UUID, values: dict) -> Optional[{model_name}ORM]:"
        )
        .map_err(|e| e.to_string())?;
        writeln!(
            out,
            "        \"\"\"Update fields on a {model_name} by primary key.\"\"\""
        )
        .map_err(|e| e.to_string())?;
        writeln!(
            out,
            "        stmt = (\n            update({model_name}ORM)\n            .where({model_name}ORM.id == record_id)\n            .values(**values)\n            .execution_options(timeout=30)\n        )"
        )
        .map_err(|e| e.to_string())?;
        writeln!(out, "        await self._session.execute(stmt)").map_err(|e| e.to_string())?;
        writeln!(out, "        return await self.get_by_id(record_id)\n")
            .map_err(|e| e.to_string())?;

        // delete
        writeln!(out, "    async def delete(self, record_id: UUID) -> bool:")
            .map_err(|e| e.to_string())?;
        writeln!(
            out,
            "        \"\"\"Delete a {model_name} by primary key. Returns True if a row was deleted.\"\"\""
        )
        .map_err(|e| e.to_string())?;
        writeln!(
            out,
            "        stmt = (\n            delete({model_name}ORM)\n            .where({model_name}ORM.id == record_id)\n            .execution_options(timeout=30)\n        )"
        )
        .map_err(|e| e.to_string())?;
        writeln!(out, "        result = await self._session.execute(stmt)")
            .map_err(|e| e.to_string())?;
        writeln!(out, "        return result.rowcount > 0").map_err(|e| e.to_string())?;

        Ok(out)
    }

    // -----------------------------------------------------------------------
    // generate_pytest_tests
    // -----------------------------------------------------------------------

    /// Generate a pytest test suite for a FastAPI service.
    ///
    /// Produces:
    /// - `@pytest.fixture` for `async_client` (httpx AsyncClient)
    /// - A happy-path test and a 404 error test for each endpoint
    ///
    /// # Arguments
    /// * `service_name` - Name used in test module docstring
    /// * `endpoints`    - Slice of `Endpoint` descriptors
    pub fn generate_pytest_tests(
        service_name: &str, endpoints: &[Endpoint],
    ) -> Result<String, String> {
        let mut out = String::new();
        let snake = to_snake(service_name);

        writeln!(out, "\"\"\"").map_err(|e| e.to_string())?;
        writeln!(out, "pytest test suite for {service_name}.").map_err(|e| e.to_string())?;
        writeln!(
            out,
            "\nChicago TDD: behaviour verification via real FastAPI TestClient."
        )
        .map_err(|e| e.to_string())?;
        writeln!(out, "\nAuto-generated by ggen. Edit with care.").map_err(|e| e.to_string())?;
        writeln!(out, "\"\"\"\n").map_err(|e| e.to_string())?;

        writeln!(out, "from __future__ import annotations\n").map_err(|e| e.to_string())?;
        writeln!(out, "import pytest").map_err(|e| e.to_string())?;
        writeln!(out, "import pytest_asyncio").map_err(|e| e.to_string())?;
        writeln!(out, "from httpx import AsyncClient, ASGITransport\n")
            .map_err(|e| e.to_string())?;
        writeln!(
            out,
            "from {snake}_app import app  # FastAPI application instance\n"
        )
        .map_err(|e| e.to_string())?;

        // async_client fixture
        writeln!(out, "\n@pytest_asyncio.fixture").map_err(|e| e.to_string())?;
        writeln!(
            out,
            "async def async_client() -> AsyncClient:  # type: ignore[override]"
        )
        .map_err(|e| e.to_string())?;
        writeln!(
            out,
            "    \"\"\"Fixture — yields an HTTPX async client wired to the FastAPI app.\"\"\""
        )
        .map_err(|e| e.to_string())?;
        writeln!(
            out,
            "    async with AsyncClient(\n        transport=ASGITransport(app=app), base_url=\"http://test\"\n    ) as client:"
        )
        .map_err(|e| e.to_string())?;
        writeln!(out, "        yield client\n").map_err(|e| e.to_string())?;

        // health check test (always present)
        writeln!(out, "\n@pytest.mark.asyncio").map_err(|e| e.to_string())?;
        writeln!(
            out,
            "async def test_health_check(async_client: AsyncClient) -> None:"
        )
        .map_err(|e| e.to_string())?;
        writeln!(
            out,
            "    \"\"\"Liveness probe returns 200 with service name.\"\"\""
        )
        .map_err(|e| e.to_string())?;
        writeln!(out, "    response = await async_client.get(\"/health\")")
            .map_err(|e| e.to_string())?;
        writeln!(out, "    assert response.status_code == 200").map_err(|e| e.to_string())?;
        writeln!(out, "    assert response.json()[\"status\"] == \"ok\"")
            .map_err(|e| e.to_string())?;
        writeln!(
            out,
            "    assert response.json()[\"service\"] == \"{service_name}\"\n"
        )
        .map_err(|e| e.to_string())?;

        // Per-endpoint tests
        for ep in endpoints {
            let method_lower = ep.method.to_lowercase();
            let handler_snake = to_snake(&ep.handler);
            let path_escaped = ep.path.replace('{', "{{").replace('}', "}}");

            // Happy path
            writeln!(out, "\n@pytest.mark.asyncio").map_err(|e| e.to_string())?;
            writeln!(
                out,
                "async def test_{handler_snake}_happy_path(async_client: AsyncClient) -> None:"
            )
            .map_err(|e| e.to_string())?;
            writeln!(
                out,
                "    \"\"\"Happy path: {} {} returns {}.\"\"\"\n    # Provide valid payload / path params",
                ep.method, ep.path, ep.status_code
            )
            .map_err(|e| e.to_string())?;
            writeln!(
                out,
                "    response = await async_client.{method_lower}(\"{path_escaped}\")"
            )
            .map_err(|e| e.to_string())?;
            writeln!(
                out,
                "    assert response.status_code == {}\n",
                ep.status_code
            )
            .map_err(|e| e.to_string())?;

            // Error path (only meaningful for endpoints that accept IDs)
            if ep.path.contains('{') {
                writeln!(out, "\n@pytest.mark.asyncio").map_err(|e| e.to_string())?;
                writeln!(
                    out,
                    "async def test_{handler_snake}_not_found(async_client: AsyncClient) -> None:"
                )
                .map_err(|e| e.to_string())?;
                writeln!(
                    out,
                    "    \"\"\"Error path: non-existent resource returns 404.\"\"\""
                )
                .map_err(|e| e.to_string())?;
                writeln!(
                    out,
                    "    response = await async_client.{method_lower}(\"/api/v1/00000000-0000-0000-0000-000000000000\")"
                )
                .map_err(|e| e.to_string())?;
                writeln!(out, "    assert response.status_code == 404\n")
                    .map_err(|e| e.to_string())?;
            }
        }

        Ok(out)
    }

    // -----------------------------------------------------------------------
    // generate_requirements_txt
    // -----------------------------------------------------------------------

    /// Generate a pinned `requirements.txt` for a FastAPI microservice.
    ///
    /// Core dependencies are always included; optional feature sets are added
    /// when the corresponding feature tag appears in `features`.
    ///
    /// Recognised feature tags: `"postgres"`, `"redis"`, `"otel"`, `"test"`.
    ///
    /// # Arguments
    /// * `service_name` - Used only in the header comment
    /// * `features`     - Slice of feature tag strings
    pub fn generate_requirements_txt(
        service_name: &str, features: &[&str],
    ) -> Result<String, String> {
        let mut out = String::new();

        writeln!(out, "# requirements.txt for {service_name}").map_err(|e| e.to_string())?;
        writeln!(
            out,
            "# Auto-generated by ggen. Pin versions before production deploy."
        )
        .map_err(|e| e.to_string())?;
        writeln!(
            out,
            "# WvdA: explicit versions prevent unbounded dependency drift.\n"
        )
        .map_err(|e| e.to_string())?;

        // Core
        writeln!(out, "# Core framework").map_err(|e| e.to_string())?;
        writeln!(out, "fastapi==0.115.0").map_err(|e| e.to_string())?;
        writeln!(out, "uvicorn[standard]==0.30.6").map_err(|e| e.to_string())?;
        writeln!(out, "pydantic==2.9.2").map_err(|e| e.to_string())?;
        writeln!(out, "pydantic-settings==2.5.2").map_err(|e| e.to_string())?;
        writeln!(out, "httpx==0.27.2\n").map_err(|e| e.to_string())?;

        // Optional: postgres
        if features.contains(&"postgres") {
            writeln!(out, "# PostgreSQL / SQLAlchemy").map_err(|e| e.to_string())?;
            writeln!(out, "sqlalchemy==2.0.36").map_err(|e| e.to_string())?;
            writeln!(out, "asyncpg==0.30.0").map_err(|e| e.to_string())?;
            writeln!(out, "alembic==1.13.3\n").map_err(|e| e.to_string())?;
        }

        // Optional: redis
        if features.contains(&"redis") {
            writeln!(out, "# Redis cache").map_err(|e| e.to_string())?;
            writeln!(out, "redis==5.2.0").map_err(|e| e.to_string())?;
            writeln!(out, "hiredis==3.0.0\n").map_err(|e| e.to_string())?;
        }

        // Optional: otel
        if features.contains(&"otel") {
            writeln!(out, "# OpenTelemetry").map_err(|e| e.to_string())?;
            writeln!(out, "opentelemetry-api==1.27.0").map_err(|e| e.to_string())?;
            writeln!(out, "opentelemetry-sdk==1.27.0").map_err(|e| e.to_string())?;
            writeln!(out, "opentelemetry-exporter-otlp==1.27.0").map_err(|e| e.to_string())?;
            writeln!(out, "opentelemetry-instrumentation-fastapi==0.48b0\n")
                .map_err(|e| e.to_string())?;
        }

        // Optional: test
        if features.contains(&"test") {
            writeln!(out, "# Testing").map_err(|e| e.to_string())?;
            writeln!(out, "pytest==8.3.3").map_err(|e| e.to_string())?;
            writeln!(out, "pytest-asyncio==0.24.0").map_err(|e| e.to_string())?;
            writeln!(out, "anyio==4.6.2\n").map_err(|e| e.to_string())?;
        }

        Ok(out)
    }

    // -----------------------------------------------------------------------
    // generate_main
    // -----------------------------------------------------------------------

    /// Generate a `main.py` entry point with uvicorn startup and signal handling.
    ///
    /// # Arguments
    /// * `service_name` - Used for the log prefix
    /// * `port`         - TCP port uvicorn binds to
    pub fn generate_main(service_name: &str, port: u16) -> Result<String, String> {
        let mut out = String::new();
        let snake = to_snake(service_name);

        writeln!(out, "\"\"\"").map_err(|e| e.to_string())?;
        writeln!(out, "main.py — entry point for {service_name}.").map_err(|e| e.to_string())?;
        writeln!(
            out,
            "\nArmstrong: lifespan context manager handles startup/shutdown."
        )
        .map_err(|e| e.to_string())?;
        writeln!(out, "Let-it-crash: any startup failure exits with code 1.")
            .map_err(|e| e.to_string())?;
        writeln!(out, "\nAuto-generated by ggen. Edit with care.").map_err(|e| e.to_string())?;
        writeln!(out, "\"\"\"\n").map_err(|e| e.to_string())?;

        writeln!(out, "import logging").map_err(|e| e.to_string())?;
        writeln!(out, "import signal").map_err(|e| e.to_string())?;
        writeln!(out, "import sys\n").map_err(|e| e.to_string())?;
        writeln!(out, "import uvicorn\n").map_err(|e| e.to_string())?;
        writeln!(out, "from {snake}_app import app  # noqa: F401\n").map_err(|e| e.to_string())?;

        writeln!(
            out,
            "logging.basicConfig(\n    level=logging.INFO,\n    format=\"%(asctime)s [%(levelname)s] %(name)s: %(message)s\",\n)\nlogger = logging.getLogger(\"{snake}\")\n"
        )
        .map_err(|e| e.to_string())?;

        writeln!(out, "# Armstrong: graceful shutdown on SIGINT / SIGTERM")
            .map_err(|e| e.to_string())?;
        writeln!(out, "_server: uvicorn.Server | None = None\n").map_err(|e| e.to_string())?;

        writeln!(out, "\ndef _handle_signal(signum: int, _frame) -> None:")
            .map_err(|e| e.to_string())?;
        writeln!(
            out,
            "    logger.info(\"{service_name} received signal %d, shutting down\", signum)"
        )
        .map_err(|e| e.to_string())?;
        writeln!(out, "    if _server:").map_err(|e| e.to_string())?;
        writeln!(out, "        _server.should_exit = True\n").map_err(|e| e.to_string())?;

        writeln!(out, "\ndef main() -> None:").map_err(|e| e.to_string())?;
        writeln!(out, "    global _server").map_err(|e| e.to_string())?;
        writeln!(out, "    signal.signal(signal.SIGINT, _handle_signal)")
            .map_err(|e| e.to_string())?;
        writeln!(out, "    signal.signal(signal.SIGTERM, _handle_signal)\n")
            .map_err(|e| e.to_string())?;
        writeln!(
            out,
            "    config = uvicorn.Config(\n        app=\"{snake}_app:app\","
        )
        .map_err(|e| e.to_string())?;
        writeln!(out, "        host=\"0.0.0.0\",").map_err(|e| e.to_string())?;
        writeln!(out, "        port={port},").map_err(|e| e.to_string())?;
        writeln!(out, "        log_level=\"info\",").map_err(|e| e.to_string())?;
        writeln!(out, "        access_log=True,").map_err(|e| e.to_string())?;
        writeln!(out, "    )").map_err(|e| e.to_string())?;
        writeln!(out, "    _server = uvicorn.Server(config)").map_err(|e| e.to_string())?;
        writeln!(
            out,
            "    logger.info(\"{service_name} starting on port {port}\")"
        )
        .map_err(|e| e.to_string())?;
        writeln!(out, "    _server.run()").map_err(|e| e.to_string())?;
        writeln!(out, "    logger.info(\"{service_name} stopped\")\n")
            .map_err(|e| e.to_string())?;

        writeln!(out, "\nif __name__ == \"__main__\":").map_err(|e| e.to_string())?;
        writeln!(out, "    main()").map_err(|e| e.to_string())?;

        Ok(out)
    }
}

// ---------------------------------------------------------------------------
// Private helpers
// ---------------------------------------------------------------------------

/// Convert PascalCase or mixed identifiers to snake_case.
fn to_snake(s: &str) -> String {
    let mut out = String::new();
    let chars: Vec<char> = s.chars().collect();
    for (i, &c) in chars.iter().enumerate() {
        if c.is_uppercase() {
            if i != 0 {
                out.push('_');
            }
            out.push(c.to_ascii_lowercase());
        } else {
            out.push(c);
        }
    }
    out
}

/// Map a Python type name to a SQLAlchemy column type string.
fn sqlalchemy_type_for(py_type: &str) -> &'static str {
    match py_type {
        "str" => "String",
        "int" => "Integer",
        "bool" => "Boolean",
        "float" => "Integer", // use Numeric in real code
        "datetime" => "DateTime",
        "UUID" => "PG_UUID(as_uuid=True)",
        _ => "String",
    }
}

/// Return a plausible JSON example literal for a Python type.
fn example_value_for_type(py_type: &str, optional: bool) -> &'static str {
    if optional {
        return "null";
    }
    match py_type {
        "str" => "\"example\"",
        "int" => "0",
        "bool" => "true",
        "float" => "0.0",
        "datetime" => "\"2024-01-01T00:00:00Z\"",
        "UUID" => "\"00000000-0000-0000-0000-000000000000\"",
        _ => "\"example\"",
    }
}

// ---------------------------------------------------------------------------
// Tests (Chicago TDD — Red→Green→Refactor)
// ---------------------------------------------------------------------------

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

    // Shared helpers -----------------------------------------------------------

    fn order_fields() -> Vec<Field> {
        vec![
            Field {
                name: "id".to_string(),
                field_type: "UUID".to_string(),
                optional: false,
                default: None,
            },
            Field {
                name: "customer_id".to_string(),
                field_type: "UUID".to_string(),
                optional: false,
                default: None,
            },
            Field {
                name: "status".to_string(),
                field_type: "str".to_string(),
                optional: false,
                default: Some("\"pending\"".to_string()),
            },
            Field {
                name: "total".to_string(),
                field_type: "float".to_string(),
                optional: true,
                default: None,
            },
        ]
    }

    fn order_endpoints() -> Vec<Endpoint> {
        vec![
            Endpoint {
                method: "GET".to_string(),
                path: "/api/v1/orders".to_string(),
                handler: "list_orders".to_string(),
                status_code: 200,
            },
            Endpoint {
                method: "POST".to_string(),
                path: "/api/v1/orders".to_string(),
                handler: "create_order".to_string(),
                status_code: 201,
            },
            Endpoint {
                method: "GET".to_string(),
                path: "/api/v1/orders/{order_id}".to_string(),
                handler: "get_order".to_string(),
                status_code: 200,
            },
            Endpoint {
                method: "DELETE".to_string(),
                path: "/api/v1/orders/{order_id}".to_string(),
                handler: "delete_order".to_string(),
                status_code: 204,
            },
        ]
    }

    // -------------------------------------------------------------------------
    // Test 1: FastAPI service contains health endpoint
    // -------------------------------------------------------------------------

    #[test]
    fn test_fastapi_service_contains_health_endpoint() {
        let result =
            PythonGenerator::generate_fastapi_service("OrderService", 8001, "Manages orders");
        assert!(result.is_ok(), "generate_fastapi_service should succeed");
        let code = result.unwrap();
        assert!(
            code.contains("@app.get(\"/health\""),
            "must contain @app.get(\"/health\")"
        );
        assert!(
            code.contains("\"status\": \"ok\""),
            "health response must include status: ok"
        );
        assert!(
            code.contains("\"service\": \"OrderService\""),
            "health response must include service name"
        );
    }

    // -------------------------------------------------------------------------
    // Test 2: FastAPI service uses lifespan context manager
    // -------------------------------------------------------------------------

    #[test]
    fn test_fastapi_service_uses_lifespan() {
        let result =
            PythonGenerator::generate_fastapi_service("OrderService", 8001, "Manages orders");
        assert!(result.is_ok());
        let code = result.unwrap();
        assert!(
            code.contains("@asynccontextmanager"),
            "must use @asynccontextmanager"
        );
        assert!(
            code.contains("async def lifespan(app: FastAPI):"),
            "must define lifespan function"
        );
        assert!(
            code.contains("lifespan=lifespan"),
            "FastAPI() must receive lifespan="
        );
        assert!(code.contains("yield"), "lifespan must yield");
    }

    // -------------------------------------------------------------------------
    // Test 3: FastAPI service is non-empty and contains service name
    // -------------------------------------------------------------------------

    #[test]
    fn test_fastapi_service_non_empty_with_service_name() {
        let result =
            PythonGenerator::generate_fastapi_service("PaymentService", 9001, "Handles payments");
        assert!(result.is_ok());
        let code = result.unwrap();
        assert!(!code.is_empty(), "generated code must not be empty");
        assert!(
            code.contains("PaymentService"),
            "generated code must reference service name"
        );
        assert!(
            code.contains("9001"),
            "generated code must reference the port"
        );
    }

    // -------------------------------------------------------------------------
    // Test 4: Pydantic model with required and optional fields
    // -------------------------------------------------------------------------

    #[test]
    fn test_pydantic_model_required_and_optional_fields() {
        let fields = order_fields();
        let result = PythonGenerator::generate_pydantic_model("Order", &fields);
        assert!(result.is_ok(), "generate_pydantic_model should succeed");
        let code = result.unwrap();

        // Required fields
        assert!(code.contains("id: UUID"), "must emit required UUID field");
        assert!(code.contains("customer_id: UUID"), "must emit customer_id");
        // Optional field
        assert!(
            code.contains("Optional[float]"),
            "optional float must be Optional[float]"
        );
        // Pydantic v2 config
        assert!(
            code.contains("from_attributes"),
            "must include from_attributes ORM mode"
        );
        // Validator
        assert!(
            code.contains("@model_validator"),
            "must include @model_validator stub"
        );
    }

    // -------------------------------------------------------------------------
    // Test 5: SQLAlchemy repository has all four CRUD methods
    // -------------------------------------------------------------------------

    #[test]
    fn test_sqlalchemy_repository_has_crud_methods() {
        let fields = order_fields();
        let result = PythonGenerator::generate_sqlalchemy_repository("Order", &fields);
        assert!(
            result.is_ok(),
            "generate_sqlalchemy_repository should succeed"
        );
        let code = result.unwrap();

        assert!(
            code.contains("async def create("),
            "must have create method"
        );
        assert!(
            code.contains("async def get_by_id("),
            "must have get_by_id method"
        );
        assert!(
            code.contains("async def list_all("),
            "must have list_all method"
        );
        assert!(
            code.contains("async def update("),
            "must have update method"
        );
        assert!(
            code.contains("async def delete("),
            "must have delete method"
        );
    }

    // -------------------------------------------------------------------------
    // Test 6: SQLAlchemy repository uses execution_options(timeout=30)
    // -------------------------------------------------------------------------

    #[test]
    fn test_sqlalchemy_repository_uses_execution_timeout() {
        let fields = order_fields();
        let result = PythonGenerator::generate_sqlalchemy_repository("Order", &fields);
        assert!(result.is_ok());
        let code = result.unwrap();

        // WvdA: count occurrences of the timeout guard
        let timeout_count = code.matches("execution_options(timeout=30)").count();
        assert!(
            timeout_count >= 3,
            "at least 3 queries must use execution_options(timeout=30), found {}",
            timeout_count
        );
    }

    // -------------------------------------------------------------------------
    // Test 7: pytest file contains fixtures and health test
    // -------------------------------------------------------------------------

    #[test]
    fn test_pytest_file_has_fixtures_and_health_test() {
        let endpoints = order_endpoints();
        let result = PythonGenerator::generate_pytest_tests("OrderService", &endpoints);
        assert!(result.is_ok(), "generate_pytest_tests should succeed");
        let code = result.unwrap();

        assert!(
            code.contains("@pytest_asyncio.fixture"),
            "must have async_client fixture"
        );
        assert!(
            code.contains("async def async_client("),
            "fixture must define async_client"
        );
        assert!(
            code.contains("test_health_check"),
            "must include health check test"
        );
        assert!(
            code.contains("@pytest.mark.asyncio"),
            "tests must be marked asyncio"
        );
    }

    // -------------------------------------------------------------------------
    // Test 8: requirements.txt always contains fastapi and pydantic
    // -------------------------------------------------------------------------

    #[test]
    fn test_requirements_txt_contains_fastapi_and_pydantic() {
        let result =
            PythonGenerator::generate_requirements_txt("OrderService", &["postgres", "test"]);
        assert!(result.is_ok(), "generate_requirements_txt should succeed");
        let code = result.unwrap();

        assert!(code.contains("fastapi=="), "must pin fastapi");
        assert!(code.contains("pydantic=="), "must pin pydantic");
        assert!(
            code.contains("sqlalchemy=="),
            "postgres feature must add sqlalchemy"
        );
        assert!(code.contains("pytest=="), "test feature must add pytest");
    }

    // -------------------------------------------------------------------------
    // Test 9: requirements.txt without optional features has no postgres deps
    // -------------------------------------------------------------------------

    #[test]
    fn test_requirements_txt_no_optional_features() {
        let result = PythonGenerator::generate_requirements_txt("MinimalService", &[]);
        assert!(result.is_ok());
        let code = result.unwrap();

        assert!(code.contains("fastapi=="), "must always contain fastapi");
        assert!(code.contains("pydantic=="), "must always contain pydantic");
        assert!(
            !code.contains("sqlalchemy"),
            "sqlalchemy must NOT appear without postgres feature"
        );
        assert!(
            !code.contains("pytest"),
            "pytest must NOT appear without test feature"
        );
    }

    // -------------------------------------------------------------------------
    // Test 10: main.py has uvicorn startup and signal handling
    // -------------------------------------------------------------------------

    #[test]
    fn test_main_has_uvicorn_and_signal_handling() {
        let result = PythonGenerator::generate_main("OrderService", 8001);
        assert!(result.is_ok(), "generate_main should succeed");
        let code = result.unwrap();

        assert!(code.contains("uvicorn"), "must use uvicorn");
        assert!(code.contains("signal.SIGINT"), "must handle SIGINT");
        assert!(code.contains("signal.SIGTERM"), "must handle SIGTERM");
        assert!(code.contains("8001"), "must reference the configured port");
        assert!(
            code.contains("if __name__ == \"__main__\":"),
            "must have __main__ guard"
        );
    }

    // -------------------------------------------------------------------------
    // Test 11: pytest test per endpoint, error paths for ID-parameterised routes
    // -------------------------------------------------------------------------

    #[test]
    fn test_pytest_generates_per_endpoint_tests() {
        let endpoints = order_endpoints();
        let result = PythonGenerator::generate_pytest_tests("OrderService", &endpoints);
        assert!(result.is_ok());
        let code = result.unwrap();

        // Endpoint handlers become test function names
        assert!(
            code.contains("test_list_orders_happy_path"),
            "must have test for list_orders"
        );
        assert!(
            code.contains("test_create_order_happy_path"),
            "must have test for create_order"
        );
        assert!(
            code.contains("test_get_order_happy_path"),
            "must have test for get_order"
        );
        // ID-parameterised routes get a not-found test
        assert!(
            code.contains("test_get_order_not_found"),
            "must have not-found test for get_order"
        );
        assert!(
            code.contains("test_delete_order_not_found"),
            "must have not-found test for delete_order"
        );
    }

    // -------------------------------------------------------------------------
    // Test 12: to_snake helper
    // -------------------------------------------------------------------------

    #[test]
    fn test_to_snake_converts_pascal_case() {
        assert_eq!(to_snake("OrderService"), "order_service");
        assert_eq!(to_snake("PaymentGateway"), "payment_gateway");
        assert_eq!(to_snake("order"), "order");
        assert_eq!(to_snake("A"), "a");
    }
}