rustango-cms-macros 0.4.0

Derive macros for rustango-cms: #[derive(PageType)] and #[derive(Block)]
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
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
//! `#[derive(PageType)]` codegen.
//!
//! Two passes:
//!
//! 1. Parse struct-level `#[page_type(...)]` + adjacent `#[rustango(...)]`
//!    attrs into [`StructConfig`]. The Model derive parses `#[rustango]`
//!    independently; we re-read the bits we need (`app`, `table`).
//!
//! 2. Walk fields, parse `#[field(...)]` per-field attrs into
//!    [`FieldConfig`], remember each field's Rust type. Unit structs
//!    (no `{ … }` body) skip this — the derived handler is a
//!    no-extension page type (e.g. `HomePage`).
//!
//! Then emit:
//!
//! - `impl PageTypeHandler for $ty { … }` with the four required
//!   string methods, optional `feed_kind`, the six `<Self as
//!   PageTypeOverrides>::*` delegators, and (for field-bearing
//!   structs) `widgets`, `load_extension`, `save_extension`.
//! - `inventory::submit!` with a `PageTypeHandlerRegistration`.

use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use syn::{
    parse::{Parse, ParseStream},
    spanned::Spanned,
    Data, DeriveInput, Expr, Fields, Lit, Result, Token, Type,
};

/// Struct-level `#[page_type(...)]` + inherited `#[rustango(...)]`.
struct StructConfig {
    app: Option<String>,
    type_name: String,
    verbose_name: String,
    template: String,
    feed_kind: Option<String>,
    /// `#[page_type(workflow = "Editorial review")]` — opt in to a
    /// multi-step approval workflow by name. `None` ⇒ direct-publish.
    workflow: Option<String>,
    /// Extension-table name. `None` ⇒ unit-struct (no extension row).
    /// Inferred from `#[rustango(table = …)]` when the struct has
    /// `Fields::Named` and the user didn't pass `extension_table`
    /// explicitly.
    extension_table: Option<String>,
    /// `#[page_type(allowed_parents(Foo, Bar))]` — string list. `None`
    /// → delegate to `<Self as PageTypeOverrides>::allowed_parent_types`;
    /// `Some(vec)` → emit a literal `&["Foo", "Bar"]` and skip the
    /// override delegator.
    allowed_parents: Option<Vec<String>>,
    /// `#[page_type(allowed_children(Foo, Bar))]` — same shape as
    /// `allowed_parents`.
    allowed_children: Option<Vec<String>>,
    /// `#[page_type(creatable = false)]` — when `Some(false)` the type
    /// is hidden from the admin "Add page" picker.
    creatable: Option<bool>,
    /// `#[page_type(icon = "article")]` — Material-symbols name for
    /// the page-type picker tile.
    icon: Option<String>,
    /// `#[page_type(description = "…")]` — one-line description under
    /// `verbose_name` in the picker.
    description: Option<String>,
    /// `#[page_type(view_mode = "auto" | "html" | "api")]` — which
    /// representation the type serves publicly. `Some("api")` also makes
    /// the otherwise-mandatory `template` attribute optional, since a
    /// JSON-only type has no template to name. `None` → delegate to
    /// `<Self as PageTypeOverrides>::view_mode`.
    view_mode: Option<String>,
    /// `#[page_type(snippet_m2m(categories = "Category", authors = "Author"))]`
    /// — declarative Page↔Snippet many-to-many relations.
    /// Each pair is `(relation_name, snippet_type_name)`: the key is the
    /// editor-facing relation / form field, the value is the
    /// `cms_snippet.type_name` the chooser lists. Declared at the struct
    /// level (not as a `#[field]`) because the relation has no backing
    /// column — its rows live in `cms_page_snippet_m2m` — so it must not
    /// participate in the `#[derive(Model)]` column surface.
    snippet_m2m: Vec<(String, String)>,
}

impl StructConfig {
    fn parse(input: &DeriveInput) -> Result<Self> {
        let mut app: Option<String> = None;
        let mut type_name: Option<String> = None;
        let mut verbose_name: Option<String> = None;
        let mut template: Option<String> = None;
        let mut feed_kind: Option<String> = None;
        let mut workflow: Option<String> = None;
        let mut extension_table: Option<String> = None;
        let mut allowed_parents: Option<Vec<String>> = None;
        let mut allowed_children: Option<Vec<String>> = None;
        let mut creatable: Option<bool> = None;
        let mut icon: Option<String> = None;
        let mut description: Option<String> = None;
        let mut view_mode: Option<String> = None;
        let mut snippet_m2m: Vec<(String, String)> = Vec::new();
        let mut rustango_app: Option<String> = None;
        let mut rustango_table: Option<String> = None;

        for attr in &input.attrs {
            if attr.path().is_ident("page_type") {
                attr.parse_nested_meta(|meta| {
                    let key = meta
                        .path
                        .get_ident()
                        .map(ToString::to_string)
                        .unwrap_or_default();
                    match key.as_str() {
                        "app" => app = Some(string_lit(&meta)?),
                        "type_name" => type_name = Some(string_lit(&meta)?),
                        "verbose_name" => verbose_name = Some(string_lit(&meta)?),
                        "template" => template = Some(string_lit(&meta)?),
                        "feed_kind" => feed_kind = Some(string_lit(&meta)?),
                        "workflow" => workflow = Some(string_lit(&meta)?),
                        "extension_table" => extension_table = Some(string_lit(&meta)?),
                        "allowed_parents" => {
                            let content;
                            syn::parenthesized!(content in meta.input);
                            let names: syn::punctuated::Punctuated<AllowedName, Token![,]> =
                                content.parse_terminated(AllowedName::parse, Token![,])?;
                            allowed_parents = Some(names.into_iter().map(|n| n.0).collect());
                        }
                        "allowed_children" => {
                            let content;
                            syn::parenthesized!(content in meta.input);
                            let names: syn::punctuated::Punctuated<AllowedName, Token![,]> =
                                content.parse_terminated(AllowedName::parse, Token![,])?;
                            allowed_children = Some(names.into_iter().map(|n| n.0).collect());
                        }
                        "creatable" => {
                            let value = meta.value()?;
                            let lit: syn::LitBool = value.parse()?;
                            creatable = Some(lit.value);
                        }
                        "icon" => icon = Some(string_lit(&meta)?),
                        "description" => description = Some(string_lit(&meta)?),
                        "view_mode" => {
                            let s = string_lit(&meta)?;
                            if !matches!(s.as_str(), "auto" | "html" | "api") {
                                return Err(meta.error(
                                    "#[page_type(view_mode = …)] must be one of: \
                                     \"auto\", \"html\", \"api\"",
                                ));
                            }
                            view_mode = Some(s);
                        }
                        "snippet_m2m" => {
                            // snippet_m2m(relation = "SnippetType", …) —
                            // reuse the `k = "v"` OptionPair shape.
                            let content;
                            syn::parenthesized!(content in meta.input);
                            let pairs: syn::punctuated::Punctuated<OptionPair, Token![,]> =
                                content.parse_terminated(OptionPair::parse, Token![,])?;
                            for p in pairs {
                                snippet_m2m.push((p.key, p.value));
                            }
                        }
                        other => {
                            return Err(meta.error(format!(
                                "unknown #[page_type] key `{other}` — \
                                valid: app, type_name, verbose_name, \
                                template, feed_kind, workflow, extension_table, \
                                allowed_parents, allowed_children, creatable, \
                                icon, description, view_mode, snippet_m2m"
                            )));
                        }
                    }
                    Ok(())
                })?;
            } else if attr.path().is_ident("rustango") {
                // Best-effort: pluck `app = "…"` and `table = "…"`
                // out of the Model derive's attrs without re-parsing
                // its full grammar. Unrecognized keys are silently
                // ignored — the Model derive will yell about them if
                // they're invalid.
                let _ = attr.parse_nested_meta(|meta| {
                    let key = meta
                        .path
                        .get_ident()
                        .map(ToString::to_string)
                        .unwrap_or_default();
                    match key.as_str() {
                        "app" => {
                            if let Ok(s) = string_lit(&meta) {
                                rustango_app = Some(s);
                            }
                        }
                        "table" => {
                            if let Ok(s) = string_lit(&meta) {
                                rustango_table = Some(s);
                            }
                        }
                        _ => {
                            // Best-effort: skip any value tail so we
                            // don't choke on nested forms (admin(...)).
                            if meta.input.peek(Token![=]) {
                                let _: Token![=] = meta.input.parse()?;
                                let _: Expr = meta.input.parse()?;
                            }
                        }
                    }
                    Ok(())
                });
            }
        }

        let type_name = type_name.ok_or_else(|| {
            syn::Error::new(
                input.span(),
                "#[derive(PageType)] requires #[page_type(type_name = \"…\")]",
            )
        })?;
        let verbose_name = verbose_name.ok_or_else(|| {
            syn::Error::new(
                input.span(),
                "#[derive(PageType)] requires #[page_type(verbose_name = \"…\")]",
            )
        })?;
        // A JSON-only type has no template to name, so `view_mode = "api"`
        // waives the requirement. It stays a hard error otherwise: without
        // that guardrail a forgotten `template` would stop being a loud
        // compile failure and quietly become a template-less page type.
        let template = match template {
            Some(t) => t,
            None if view_mode.as_deref() == Some("api") => String::new(),
            None => {
                return Err(syn::Error::new(
                    input.span(),
                    "#[derive(PageType)] requires #[page_type(template = \"…\")] — \
                     or #[page_type(view_mode = \"api\")] for a JSON-only type \
                     that has no template",
                ))
            }
        };

        let app = app.or(rustango_app);

        // Only inherit table when this is a field-bearing struct.
        let has_fields = matches!(
            &input.data,
            Data::Struct(s) if matches!(s.fields, Fields::Named(_))
        );
        let extension_table = extension_table.or(if has_fields { rustango_table } else { None });

        let app = app.ok_or_else(|| {
            syn::Error::new(
                input.span(),
                "#[derive(PageType)] requires `app` — either \
                 #[page_type(app = \"…\")] or #[rustango(app = \"…\")]",
            )
        })?;

        Ok(Self {
            app: Some(app),
            type_name,
            verbose_name,
            template,
            feed_kind,
            workflow,
            extension_table,
            allowed_parents,
            allowed_children,
            creatable,
            view_mode,
            icon,
            description,
            snippet_m2m,
        })
    }
}

pub(crate) fn string_lit(meta: &syn::meta::ParseNestedMeta<'_>) -> Result<String> {
    let value = meta.value()?;
    let lit: syn::LitStr = value.parse()?;
    Ok(lit.value())
}

/// One `#[field(...)]`-tagged column.
pub(crate) struct FieldConfig {
    /// Rust field name (Ident).
    pub(crate) name: syn::Ident,
    /// Original Rust type — used to pick the form-parse + value
    /// stringifier.
    pub(crate) ty: Type,
    /// `WidgetKind` variant identifier (e.g. `Markdown`).
    pub(crate) widget: syn::Ident,
    pub(crate) label: String,
    help: Option<String>,
    placeholder: Option<String>,
    pub(crate) required: bool,
    /// `#[field(default = "…")]` — used as the widget's `value` when
    /// no row exists yet.
    pub(crate) default_value: Option<String>,
    min: Option<TokenStream>,
    max: Option<TokenStream>,
    /// `#[field(step = "0.1")]` — kept as a literal string so users
    /// can pass `"any"` for free-form decimals.
    step: Option<String>,
    max_length: Option<u32>,
    /// `#[field(options(k = "v", k2 = "v2"))]` — `(value, label)` pairs.
    options: Vec<(String, String)>,
    /// `#[field(allowed(name1, name2))]` — Stream variant.
    allowed: Vec<String>,
    /// `#[field(custom_name = "latlng")]` — required when `widget = Custom`
    /// to identify which registered custom widget template to use.
    /// Ignored for built-in `WidgetKind` variants.
    custom_name: Option<String>,
}

impl FieldConfig {
    /// Parse one struct field. Returns `Ok(None)` when there's no
    /// `#[field(...)]` attr — that column is data-only (e.g. `id`,
    /// `page_id`, `updated_at`) and doesn't surface in the editor.
    pub(crate) fn parse(field: &syn::Field) -> Result<Option<Self>> {
        let mut found_attr = None;
        for attr in &field.attrs {
            if attr.path().is_ident("field") {
                found_attr = Some(attr);
                break;
            }
        }
        let Some(attr) = found_attr else {
            return Ok(None);
        };
        let name = field
            .ident
            .clone()
            .ok_or_else(|| syn::Error::new(field.span(), "tuple structs not supported"))?;
        let ty = field.ty.clone();

        let mut widget: Option<syn::Ident> = None;
        let mut label: Option<String> = None;
        let mut help: Option<String> = None;
        let mut placeholder: Option<String> = None;
        let mut required = false;
        let mut default_value: Option<String> = None;
        let mut min: Option<TokenStream> = None;
        let mut max: Option<TokenStream> = None;
        let mut step: Option<String> = None;
        let mut max_length: Option<u32> = None;
        let mut options: Vec<(String, String)> = Vec::new();
        let mut allowed: Vec<String> = Vec::new();
        let mut custom_name: Option<String> = None;

        attr.parse_nested_meta(|meta| {
            let key = meta
                .path
                .get_ident()
                .map(ToString::to_string)
                .unwrap_or_default();
            match key.as_str() {
                "widget" => {
                    let value = meta.value()?;
                    let id: syn::Ident = value.parse()?;
                    widget = Some(id);
                }
                "label" => label = Some(string_lit(&meta)?),
                "help" => help = Some(string_lit(&meta)?),
                "placeholder" => placeholder = Some(string_lit(&meta)?),
                "required" => required = true,
                "default" => default_value = Some(string_lit(&meta)?),
                "min" => {
                    let value = meta.value()?;
                    let lit: Lit = value.parse()?;
                    min = Some(quote!(#lit));
                }
                "max" => {
                    let value = meta.value()?;
                    let lit: Lit = value.parse()?;
                    max = Some(quote!(#lit));
                }
                "step" => {
                    let value = meta.value()?;
                    // Accept either a string ("any") or a number (5).
                    if value.peek(syn::LitStr) {
                        let lit: syn::LitStr = value.parse()?;
                        step = Some(lit.value());
                    } else {
                        let lit: Lit = value.parse()?;
                        step = Some(quote!(#lit).to_string());
                    }
                }
                "max_length" => {
                    let value = meta.value()?;
                    let lit: syn::LitInt = value.parse()?;
                    max_length = Some(lit.base10_parse()?);
                }
                "options" => {
                    // options(k1 = "v1", k2 = "v2", …)
                    let content;
                    syn::parenthesized!(content in meta.input);
                    let pairs: syn::punctuated::Punctuated<OptionPair, Token![,]> =
                        content.parse_terminated(OptionPair::parse, Token![,])?;
                    for p in pairs {
                        options.push((p.key, p.value));
                    }
                }
                "allowed" => {
                    // allowed(name1, name2, …) — accept idents OR string literals.
                    let content;
                    syn::parenthesized!(content in meta.input);
                    let names: syn::punctuated::Punctuated<AllowedName, Token![,]> =
                        content.parse_terminated(AllowedName::parse, Token![,])?;
                    for n in names {
                        allowed.push(n.0);
                    }
                }
                "custom_name" => custom_name = Some(string_lit(&meta)?),
                other => {
                    return Err(meta.error(format!(
                        "unknown #[field] key `{other}` — valid: widget, label, \
                         help, placeholder, required, default, min, max, step, \
                         max_length, options, allowed, custom_name"
                    )));
                }
            }
            Ok(())
        })?;

        let widget = widget
            .ok_or_else(|| syn::Error::new(attr.span(), "#[field(widget = …)] is required"))?;
        let label = label
            .ok_or_else(|| syn::Error::new(attr.span(), "#[field(label = \"…\")] is required"))?;

        Ok(Some(Self {
            name,
            ty,
            widget,
            label,
            help,
            placeholder,
            required,
            default_value,
            min,
            max,
            step,
            max_length,
            options,
            allowed,
            custom_name,
        }))
    }
}

/// `options(k = "v")` parser — accepts `k = "v"` per pair.
struct OptionPair {
    key: String,
    value: String,
}

impl Parse for OptionPair {
    fn parse(input: ParseStream<'_>) -> Result<Self> {
        // key can be an ident or a string literal
        let key = if input.peek(syn::LitStr) {
            let lit: syn::LitStr = input.parse()?;
            lit.value()
        } else {
            let id: syn::Ident = input.parse()?;
            id.to_string()
        };
        let _: Token![=] = input.parse()?;
        let value: syn::LitStr = input.parse()?;
        Ok(Self {
            key,
            value: value.value(),
        })
    }
}

struct AllowedName(String);
impl Parse for AllowedName {
    fn parse(input: ParseStream<'_>) -> Result<Self> {
        if input.peek(syn::LitStr) {
            let lit: syn::LitStr = input.parse()?;
            Ok(Self(lit.value()))
        } else {
            let id: syn::Ident = input.parse()?;
            Ok(Self(id.to_string()))
        }
    }
}

/// Top-level expand.
/// Names the page editor's own form already uses (`PageForm` in
/// rustango-cms, plus its action and CSRF fields).
const PAGE_FORM_FIELDS: &[&str] = &[
    "title", "slug", "page_type_id", "status", "action", "seo_title", "seo_description",
    "robots_index", "sitemap_priority", "show_in_menus", "parent_id", "theme_id", "go_live_at",
    "expire_at", "preview_path", "template_override", "og_title", "og_description",
    "og_image_media_id", "twitter_card", "tags", "categories", "_action", "_csrf",
];

pub fn expand(input: DeriveInput) -> Result<TokenStream> {
    let cfg = StructConfig::parse(&input)?;
    let ident = &input.ident;

    let fields: Vec<FieldConfig> = match &input.data {
        Data::Struct(s) => match &s.fields {
            Fields::Named(named) => named
                .named
                .iter()
                .filter_map(|f| FieldConfig::parse(f).transpose())
                .collect::<Result<_>>()?,
            Fields::Unit => Vec::new(),
            Fields::Unnamed(_) => {
                return Err(syn::Error::new(
                    input.span(),
                    "tuple structs are not supported",
                ))
            }
        },
        _ => {
            return Err(syn::Error::new(
                input.span(),
                "#[derive(PageType)] only supports structs",
            ))
        }
    };

    // The page editor posts its own fields in the same form; an extension
    // field with one of their names would overwrite it (a `status` field
    // silently unpublished the page on every save).
    for f in &fields {
        let name = f.name.to_string();
        if PAGE_FORM_FIELDS.contains(&name.as_str()) {
            return Err(syn::Error::new(
                f.name.span(),
                format!(
                    "#[field] `{name}` clashes with the page editor's own `{name}` field; \
                     rename it (keep the column with #[rustango(column = \"{name}\")])"
                ),
            ));
        }
    }

    let app = cfg.app.as_deref().unwrap();
    let type_name = &cfg.type_name;
    let verbose_name = &cfg.verbose_name;
    let template = &cfg.template;
    let feed_kind_method = match cfg.feed_kind.as_deref() {
        Some(slug) => quote! {
            fn feed_kind(&self) -> ::core::option::Option<&'static str> {
                ::core::option::Option::Some(#slug)
            }
        },
        None => quote! {
            fn feed_kind(&self) -> ::core::option::Option<&'static str> {
                <Self as ::rustango_cms::PageTypeOverrides>::feed_kind(self)
            }
        },
    };
    let view_mode_method = match cfg.view_mode.as_deref() {
        Some(mode) => {
            let variant = syn::Ident::new(
                match mode {
                    "api" => "Api",
                    "html" => "Html",
                    _ => "Auto",
                },
                proc_macro2::Span::call_site(),
            );
            quote! {
                fn view_mode(&self) -> ::rustango_cms::PageViewMode {
                    ::rustango_cms::PageViewMode::#variant
                }
            }
        }
        None => quote! {
            fn view_mode(&self) -> ::rustango_cms::PageViewMode {
                <Self as ::rustango_cms::PageTypeOverrides>::view_mode(self)
            }
        },
    };
    let workflow_method = match cfg.workflow.as_deref() {
        Some(slug) => quote! {
            fn workflow_slug(&self) -> ::core::option::Option<&'static str> {
                ::core::option::Option::Some(#slug)
            }
        },
        None => quote! {
            fn workflow_slug(&self) -> ::core::option::Option<&'static str> {
                <Self as ::rustango_cms::PageTypeOverrides>::workflow_slug(self)
            }
        },
    };

    // Topology + creatable methods: when the struct-level attr is
    // present, emit a literal return. Otherwise delegate to
    // `PageTypeOverrides` so the author can override there. This is
    // the "ergonomic configuration" surface — most types only need
    // these as data, not as method overrides.
    let allowed_parents_method = match &cfg.allowed_parents {
        Some(names) => {
            let lits = names.iter();
            quote! {
                fn allowed_parent_types(&self) -> &'static [&'static str] {
                    &[ #( #lits ),* ]
                }
            }
        }
        None => quote! {
            fn allowed_parent_types(&self) -> &'static [&'static str] {
                <Self as ::rustango_cms::PageTypeOverrides>::allowed_parent_types(self)
            }
        },
    };
    let allowed_children_method = match &cfg.allowed_children {
        Some(names) => {
            let lits = names.iter();
            quote! {
                fn allowed_child_types(&self) -> &'static [&'static str] {
                    &[ #( #lits ),* ]
                }
            }
        }
        None => quote! {
            fn allowed_child_types(&self) -> &'static [&'static str] {
                <Self as ::rustango_cms::PageTypeOverrides>::allowed_child_types(self)
            }
        },
    };
    let is_creatable_method = match cfg.creatable {
        Some(b) => quote! {
            fn is_creatable(&self) -> bool { #b }
        },
        None => quote! {
            fn is_creatable(&self) -> bool {
                <Self as ::rustango_cms::PageTypeOverrides>::is_creatable(self)
            }
        },
    };
    let icon_method = match cfg.icon.as_deref() {
        Some(name) => quote! {
            fn icon(&self) -> ::core::option::Option<&'static str> {
                ::core::option::Option::Some(#name)
            }
        },
        None => quote! {
            fn icon(&self) -> ::core::option::Option<&'static str> {
                ::core::option::Option::None
            }
        },
    };
    let description_method = match cfg.description.as_deref() {
        Some(text) => quote! {
            fn description(&self) -> ::core::option::Option<&'static str> {
                ::core::option::Option::Some(#text)
            }
        },
        None => quote! {
            fn description(&self) -> ::core::option::Option<&'static str> {
                ::core::option::Option::None
            }
        },
    };

    // The widgets / load_extension / save_extension bodies depend on
    // whether this struct has a backing extension table (column-bearing
    // `#[field]`s) and/or declares Page↔Snippet M2M relations. Either is
    // sufficient to emit real bodies; a unit struct with neither stays
    // a no-op. M2M relations are handled independently of the extension
    // row — they persist to `cms_page_snippet_m2m`, not a column — so a
    // pure-M2M page type with no extension table still gets live bodies.
    let has_ext = !fields.is_empty() && cfg.extension_table.is_some();
    let m2m = cfg.snippet_m2m.clone();
    // Reject silent footguns at expand time: a duplicate relation name
    // would emit two widgets / double saves under one form key, and a
    // relation that shadows a `#[field]` column would clobber it in the
    // shared form map + loaded extension JSON.
    {
        let field_names: ::std::collections::HashSet<String> =
            fields.iter().map(|f| f.name.to_string()).collect();
        let mut seen: ::std::collections::HashSet<&str> = ::std::collections::HashSet::new();
        for (rel, _ty) in &m2m {
            if !seen.insert(rel.as_str()) {
                return Err(syn::Error::new(
                    input.span(),
                    format!("duplicate snippet_m2m relation `{rel}`"),
                ));
            }
            if field_names.contains(rel) {
                return Err(syn::Error::new(
                    input.span(),
                    format!(
                        "snippet_m2m relation `{rel}` collides with a #[field] column of the same name"
                    ),
                ));
            }
        }
    }
    let (widgets_body, load_body, save_body) = if !has_ext && m2m.is_empty() {
        let empty_widgets = quote! {
            async fn widgets(
                &self,
                _pool: &::rustango_cms::__private::Pool,
                _page_id: i64,
            ) -> ::core::result::Result<
                ::std::vec::Vec<::rustango_cms::Widget>,
                ::rustango_cms::__private::ExecError,
            > {
                ::core::result::Result::Ok(::std::vec::Vec::new())
            }
        };
        let empty_load = quote! {
            async fn load_extension(
                &self,
                _pool: &::rustango_cms::__private::Pool,
                _page_id: i64,
            ) -> ::core::result::Result<
                ::serde_json::Value,
                ::rustango_cms::__private::ExecError,
            > {
                ::core::result::Result::Ok(::serde_json::Value::Null)
            }
        };
        let empty_save = quote! {
            async fn save_extension(
                &self,
                _pool: &::rustango_cms::__private::Pool,
                _page_id: i64,
                _form: &::std::collections::HashMap<::std::string::String, ::std::string::String>,
            ) -> ::core::result::Result<(), ::rustango_cms::__private::ExecError> {
                ::core::result::Result::Ok(())
            }
        };
        (empty_widgets, empty_load, empty_save)
    } else {
        let widgets = emit_widgets_body(ident, &fields, has_ext, &m2m)?;
        let load = emit_load_body(ident, has_ext, &m2m);
        let save = emit_save_body(ident, &fields, has_ext, &m2m)?;
        (widgets, load, save)
    };

    // #243 — surface the declared M2M relations to the public renderer,
    // which resolves each into `snippet_relations.<name>`. Only emitted
    // when relations are declared; the trait default returns none.
    let m2m_relations_method = if m2m.is_empty() {
        quote! {}
    } else {
        let pairs = m2m.iter().map(|(rel, ty)| quote! { (#rel, #ty) });
        quote! {
            fn snippet_m2m_relations(&self) -> ::std::vec::Vec<(&'static str, &'static str)> {
                ::std::vec![ #(#pairs),* ]
            }
        }
    };

    let registration = quote! {
        ::rustango_cms::__private::inventory::submit! {
            ::rustango_cms::PageTypeHandlerRegistration {
                factory: || ::std::boxed::Box::new(<#ident as ::core::default::Default>::default()),
            }
        }
    };

    // #934 — the hooks run on the page's stored row, not on the
    // registered (default) handler, so `self.<field>` is the page's value.
    let stored_row = if has_ext {
        quote! {
            {
                use ::rustango::core::Column as _;
                use ::rustango::sql::FetcherPool as _;
                let __pid = page.id.get().copied().unwrap_or_default();
                #ident::objects()
                    .where_(#ident::page_id.eq(__pid))
                    .fetch(pool)
                    .await?
                    .into_iter()
                    .next()
            }
        }
    } else {
        quote! { ::core::option::Option::<#ident>::None }
    };
    Ok(quote! {
        #[::rustango_cms::__private::async_trait::async_trait]
        impl ::rustango_cms::PageTypeHandler for #ident {
            fn app_label(&self) -> &'static str { #app }
            fn type_name(&self) -> &'static str { #type_name }
            fn verbose_name(&self) -> &'static str { #verbose_name }
            fn default_template(&self) -> &'static str { #template }

            #feed_kind_method
            #view_mode_method
            #workflow_method
            #allowed_parents_method
            #allowed_children_method
            #is_creatable_method
            #icon_method
            #description_method

            fn view_restriction(
                &self,
            ) -> ::core::option::Option<::rustango_cms::TypeViewRestriction> {
                <Self as ::rustango_cms::PageTypeOverrides>::view_restriction(self)
            }

            async fn display_fields(
                &self,
                pool: &::rustango_cms::__private::Pool,
                page_id: i64,
            ) -> ::core::result::Result<
                ::std::vec::Vec<::rustango_cms::DisplayField>,
                ::rustango_cms::__private::ExecError,
            > {
                <Self as ::rustango_cms::PageTypeOverrides>::display_fields(self, pool, page_id).await
            }

            async fn extra_tabs(
                &self,
                pool: &::rustango_cms::__private::Pool,
                page_id: i64,
            ) -> ::core::result::Result<
                ::std::vec::Vec<::rustango_cms::TabSpec>,
                ::rustango_cms::__private::ExecError,
            > {
                <Self as ::rustango_cms::PageTypeOverrides>::extra_tabs(self, pool, page_id).await
            }

            async fn inline_panels(
                &self,
                pool: &::rustango_cms::__private::Pool,
                page_id: i64,
            ) -> ::core::result::Result<
                ::std::vec::Vec<::rustango_cms::InlinePanelSpec>,
                ::rustango_cms::__private::ExecError,
            > {
                <Self as ::rustango_cms::PageTypeOverrides>::inline_panels(self, pool, page_id).await
            }

            async fn load_inline_panel(
                &self,
                pool: &::rustango_cms::__private::Pool,
                page_id: i64,
                panel_name: &str,
            ) -> ::core::result::Result<
                ::std::vec::Vec<::serde_json::Map<::std::string::String, ::serde_json::Value>>,
                ::rustango_cms::__private::ExecError,
            > {
                <Self as ::rustango_cms::PageTypeOverrides>::load_inline_panel(self, pool, page_id, panel_name).await
            }

            async fn save_inline_panel(
                &self,
                pool: &::rustango_cms::__private::Pool,
                page_id: i64,
                panel_name: &str,
                rows: &[::serde_json::Map<::std::string::String, ::serde_json::Value>],
            ) -> ::core::result::Result<(), ::rustango_cms::__private::ExecError> {
                <Self as ::rustango_cms::PageTypeOverrides>::save_inline_panel(self, pool, page_id, panel_name, rows).await
            }

            async fn inline_rows(
                &self,
                pool: &::rustango_cms::__private::Pool,
                page_id: i64,
                panel: &str,
            ) -> ::core::result::Result<
                ::std::vec::Vec<::rustango_cms::InlineRowSummary>,
                ::rustango_cms::__private::ExecError,
            > {
                <Self as ::rustango_cms::PageTypeOverrides>::inline_rows(self, pool, page_id, panel).await
            }

            async fn inline_row(
                &self,
                pool: &::rustango_cms::__private::Pool,
                page_id: i64,
                panel: &str,
                row_id: ::core::option::Option<i64>,
            ) -> ::core::result::Result<
                ::core::option::Option<::serde_json::Map<::std::string::String, ::serde_json::Value>>,
                ::rustango_cms::__private::ExecError,
            > {
                <Self as ::rustango_cms::PageTypeOverrides>::inline_row(self, pool, page_id, panel, row_id).await
            }

            async fn save_inline_row(
                &self,
                pool: &::rustango_cms::__private::Pool,
                page_id: i64,
                panel: &str,
                row_id: ::core::option::Option<i64>,
                values: &::serde_json::Map<::std::string::String, ::serde_json::Value>,
            ) -> ::core::result::Result<::rustango_cms::InlineRowSaved, ::rustango_cms::__private::ExecError> {
                <Self as ::rustango_cms::PageTypeOverrides>::save_inline_row(self, pool, page_id, panel, row_id, values).await
            }

            async fn delete_inline_row(
                &self,
                pool: &::rustango_cms::__private::Pool,
                page_id: i64,
                panel: &str,
                row_id: i64,
            ) -> ::core::result::Result<bool, ::rustango_cms::__private::ExecError> {
                <Self as ::rustango_cms::PageTypeOverrides>::delete_inline_row(self, pool, page_id, panel, row_id).await
            }

            async fn reorder_inline_rows(
                &self,
                pool: &::rustango_cms::__private::Pool,
                page_id: i64,
                panel: &str,
                ids: &[i64],
            ) -> ::core::result::Result<(), ::rustango_cms::__private::ExecError> {
                <Self as ::rustango_cms::PageTypeOverrides>::reorder_inline_rows(self, pool, page_id, panel, ids).await
            }

            // #246 — handler-injected template ctx. Forwards to
            // `PageTypeOverrides::public_context`; default returns
            // an empty map.
            async fn public_context(
                &self,
                pool: &::rustango_cms::__private::Pool,
                page: &::rustango_cms::Page,
            ) -> ::core::result::Result<
                ::serde_json::Map<::std::string::String, ::serde_json::Value>,
                ::rustango_cms::__private::ExecError,
            > {
                let __row: ::core::option::Option<#ident> = #stored_row;
                <Self as ::rustango_cms::PageTypeOverrides>::public_context(
                    __row.as_ref().unwrap_or(self), pool, page,
                )
                .await
            }

            // Children listing. Forwards to
            // `PageTypeOverrides::children_query`; when that returns
            // `None` (the default) fall back to the framework default
            // (all immediate children, `sort_order, id`, drafts included)
            // so a type that doesn't override behaves exactly as before.
            async fn children_query(
                &self,
                pool: &::rustango_cms::__private::Pool,
                page: &::rustango_cms::Page,
            ) -> ::core::result::Result<
                ::std::vec::Vec<::rustango_cms::Page>,
                ::rustango_cms::__private::ExecError,
            > {
                match <Self as ::rustango_cms::PageTypeOverrides>::children_query(self, pool, page)
                    .await?
                {
                    ::core::option::Option::Some(pages) => ::core::result::Result::Ok(pages),
                    ::core::option::Option::None => {
                        ::rustango_cms::default_children(pool, page).await
                    }
                }
            }

            // #198 — routable_page URL patterns. Forwards to
            // `PageTypeOverrides::routes` / `route_context`; defaults
            // return empty (no routable surface) so existing handlers
            // that don't override stay non-routable.
            fn routes(&self) -> ::std::vec::Vec<::rustango_cms::routable::RouteSpec> {
                <Self as ::rustango_cms::PageTypeOverrides>::routes(self)
            }

            async fn route_context(
                &self,
                pool: &::rustango_cms::__private::Pool,
                page: &::rustango_cms::Page,
                matched: &::rustango_cms::routable::RouteMatch,
            ) -> ::core::result::Result<
                ::serde_json::Map<::std::string::String, ::serde_json::Value>,
                ::rustango_cms::__private::ExecError,
            > {
                let __row: ::core::option::Option<#ident> = #stored_row;
                <Self as ::rustango_cms::PageTypeOverrides>::route_context(
                    __row.as_ref().unwrap_or(self), pool, page, matched,
                )
                .await
            }

            fn route_outcome(
                &self,
                matched: &::rustango_cms::routable::RouteMatch,
                route_ctx: &::serde_json::Map<::std::string::String, ::serde_json::Value>,
            ) -> ::rustango_cms::routable::RouteOutcome {
                <Self as ::rustango_cms::PageTypeOverrides>::route_outcome(self, matched, route_ctx)
            }

            #m2m_relations_method
            #widgets_body
            #load_body
            #save_body
        }

        #registration
    })
}

/// Emit `widgets()` — load the extension row (if any) + build one Widget
/// per `#[field]`, then append one SnippetM2M chooser per declared
/// `snippet_m2m` relation (options fetched from `cms_snippet` by type,
/// current selection from `cms_page_snippet_m2m`).
fn emit_widgets_body(
    struct_ident: &syn::Ident,
    fields: &[FieldConfig],
    has_ext: bool,
    m2m: &[(String, String)],
) -> Result<TokenStream> {
    let ext_part = if has_ext {
        let with_row: Vec<TokenStream> = fields
            .iter()
            .map(|f| emit_widget_call(f, emit_value_stringify(&f.ty, &f.name)))
            .collect::<Result<_>>()?;
        let no_row: Vec<TokenStream> = fields
            .iter()
            .map(|f| emit_widget_call(f, default_value_expr(f)))
            .collect::<Result<_>>()?;
        quote! {
            let row: ::core::option::Option<#struct_ident> = #struct_ident::objects()
                .where_(#struct_ident::page_id.eq(page_id))
                .fetch(pool)
                .await?
                .into_iter()
                .next();
            match row {
                ::core::option::Option::Some(r) => {
                    #(#with_row)*
                }
                ::core::option::Option::None => {
                    #(#no_row)*
                }
            }
        }
    } else {
        quote! {}
    };

    let m2m_pushes: Vec<TokenStream> = m2m
        .iter()
        .map(|(relation, ty)| {
            let label = humanize_label(relation);
            quote! {
                {
                    // Eligible candidates: every snippet of this type,
                    // surfaced as (id_string, title) for the chooser, in
                    // a deterministic title order. Rows without a set id
                    // are dropped rather than offered as a fake "0".
                    let __opts: ::std::vec::Vec<(::std::string::String, ::std::string::String)> =
                        ::rustango_cms::Snippet::objects()
                            .where_(::rustango_cms::Snippet::type_name.eq(::std::string::String::from(#ty)))
                            .order_by(&[("title", false)])
                            .fetch(pool)
                            .await?
                            .into_iter()
                            .filter_map(|s| {
                                s.id.get()
                                    .copied()
                                    .map(|id| (id.to_string(), s.title.clone()))
                            })
                            .collect();
                    // Current selection in chooser order → JSON id array.
                    let __rows = ::rustango_cms::page_snippet_m2m::rows_for_relation(
                        pool, page_id, #relation,
                    )
                    .await?;
                    let __ids: ::std::vec::Vec<i64> =
                        __rows.iter().map(|r| r.snippet_id).collect();
                    let __value = ::serde_json::to_string(&__ids)
                        .unwrap_or_else(|_| ::std::string::String::from("[]"));
                    widgets.push(
                        ::rustango_cms::Widget::snippet_m2m(#relation, #label, #ty)
                            .with_options(__opts)
                            .with_value(__value),
                    );
                }
            }
        })
        .collect();

    Ok(quote! {
        async fn widgets(
            &self,
            pool: &::rustango_cms::__private::Pool,
            page_id: i64,
        ) -> ::core::result::Result<
            ::std::vec::Vec<::rustango_cms::Widget>,
            ::rustango_cms::__private::ExecError,
        > {
            use ::rustango::core::Column as _;
            use ::rustango::sql::FetcherPool as _;

            let mut widgets: ::std::vec::Vec<::rustango_cms::Widget> = ::std::vec::Vec::new();
            #ext_part
            #(#m2m_pushes)*
            ::core::result::Result::Ok(widgets)
        }
    })
}

/// The widget value for a form with no row yet: the field's
/// `#[field(default = …)]`, else empty.
fn default_value_expr(f: &FieldConfig) -> TokenStream {
    match &f.default_value {
        Some(d) => quote! { ::std::string::String::from(#d) },
        None => quote! { ::std::string::String::new() },
    }
}

/// Emit one Widget constructor + builder chain, pushed onto `widgets`.
/// `value_expr` is the pre-fill value, an expression giving a `String`.
pub(crate) fn emit_widget_call(f: &FieldConfig, value_expr: TokenStream) -> Result<TokenStream> {
    let name_str = f.name.to_string();
    let label = &f.label;
    let widget_ident = &f.widget;
    let widget_str = widget_ident.to_string();

    let is_stream = widget_str == "Stream";
    let is_custom = widget_str == "Custom";
    // #421 — `widget = ModelChooser` declares a chooser for a
    // `register_chooser!`ed model; the registered slug rides in
    // `custom_name` (→ `Widget::model_chooser`, which sets it as the
    // `data-chooser-kind` the overlay resolves).
    let is_model_chooser = widget_str == "ModelChooser";

    if is_custom && f.custom_name.is_none() {
        return Err(syn::Error::new(
            f.name.span(),
            "#[field(widget = Custom)] requires `custom_name = \"…\"` so the \
             custom-widget registry knows which template to render",
        ));
    }
    if is_model_chooser && f.custom_name.is_none() {
        return Err(syn::Error::new(
            f.name.span(),
            "#[field(widget = ModelChooser)] requires `custom_name = \"<slug>\"` — \
             the `register_chooser!` slug the chooser resolves against",
        ));
    }

    let constructor = if is_stream {
        let allowed = &f.allowed;
        quote! {
            ::rustango_cms::Widget::stream(
                #name_str,
                #label,
                [#( #allowed ),*],
            )
        }
    } else if is_custom {
        // SAFETY: checked above that custom_name is Some.
        let custom_name = f.custom_name.as_deref().unwrap();
        quote! {
            ::rustango_cms::Widget::custom(
                #custom_name,
                #name_str,
                #label,
            )
        }
    } else if is_model_chooser {
        // SAFETY: checked above that custom_name is Some.
        let slug = f.custom_name.as_deref().unwrap();
        quote! {
            ::rustango_cms::Widget::model_chooser(
                #name_str,
                #label,
                #slug,
            )
        }
    } else {
        quote! {
            ::rustango_cms::Widget::new(
                ::rustango_cms::WidgetKind::#widget_ident,
                #name_str,
                #label,
            )
        }
    };

    // Builder chain — only emit setters whose attr is present.
    let mut chain = TokenStream::new();
    // value: always emit (even for empty)
    chain.extend(quote! { .with_value(#value_expr) });
    if let Some(help) = &f.help {
        chain.extend(quote! { .with_help(#help) });
    }
    if let Some(placeholder) = &f.placeholder {
        chain.extend(quote! { .with_placeholder(#placeholder) });
    }
    if f.required {
        chain.extend(quote! { .required() });
    }
    if let Some(min) = &f.min {
        chain.extend(quote! { .with_min(#min as f64) });
    }
    if let Some(max) = &f.max {
        chain.extend(quote! { .with_max(#max as f64) });
    }
    if let Some(step) = &f.step {
        chain.extend(quote! { .with_step(#step) });
    }
    if let Some(ml) = f.max_length {
        chain.extend(quote! { .with_max_length(#ml) });
    }
    if !f.options.is_empty() && !is_stream {
        let pairs = f.options.iter().map(|(k, v)| quote! { (#k, #v) });
        chain.extend(quote! { .with_options([#(#pairs),*]) });
    }

    Ok(quote! {
        widgets.push(#constructor #chain);
    })
}

/// `r.<field>` → owned String for the widget's `value` slot.
fn emit_value_stringify(ty: &Type, field: &syn::Ident) -> TokenStream {
    let cat = classify_type(ty);
    match cat {
        TypeCat::String => quote! { r.#field.clone() },
        TypeCat::OptionString => {
            quote! { r.#field.clone().unwrap_or_default() }
        }
        TypeCat::Int => quote! { r.#field.to_string() },
        TypeCat::OptionInt => {
            quote! { r.#field.map(|v| v.to_string()).unwrap_or_default() }
        }
        TypeCat::Float => quote! { r.#field.to_string() },
        TypeCat::OptionFloat => {
            quote! { r.#field.map(|v| v.to_string()).unwrap_or_default() }
        }
        TypeCat::Bool => {
            quote! { if r.#field { ::std::string::String::from("true") } else { ::std::string::String::new() } }
        }
        // Unknown — fall back to Display via to_string().
        TypeCat::Unknown => quote! { r.#field.to_string() },
    }
}

/// Emit `load_extension()`. With no M2M relations this is the original
/// "fetch row, serialize to JSON (or Null)" behavior. With M2M relations
/// it returns a JSON object merging the extension row's fields (if any)
/// with one `"<relation>": [snippet ids…]` key per relation, so public
/// templates can read `extension.<relation>`.
fn emit_load_body(
    struct_ident: &syn::Ident,
    has_ext: bool,
    m2m: &[(String, String)],
) -> TokenStream {
    if m2m.is_empty() {
        // No M2M — `has_ext` is guaranteed true here (else this body
        // isn't emitted). Preserve the exact original shape.
        return quote! {
            async fn load_extension(
                &self,
                pool: &::rustango_cms::__private::Pool,
                page_id: i64,
            ) -> ::core::result::Result<
                ::serde_json::Value,
                ::rustango_cms::__private::ExecError,
            > {
                use ::rustango::core::Column as _;
                use ::rustango::sql::FetcherPool as _;

                let row: ::core::option::Option<#struct_ident> = #struct_ident::objects()
                    .where_(#struct_ident::page_id.eq(page_id))
                    .fetch(pool)
                    .await?
                    .into_iter()
                    .next();
                ::core::result::Result::Ok(match row {
                    ::core::option::Option::Some(r) => ::serde_json::to_value(r)
                        .unwrap_or(::serde_json::Value::Null),
                    ::core::option::Option::None => ::serde_json::Value::Null,
                })
            }
        };
    }

    let ext_load = if has_ext {
        quote! {
            {
                use ::rustango::core::Column as _;
                use ::rustango::sql::FetcherPool as _;
                let row: ::core::option::Option<#struct_ident> = #struct_ident::objects()
                    .where_(#struct_ident::page_id.eq(page_id))
                    .fetch(pool)
                    .await?
                    .into_iter()
                    .next();
                if let ::core::option::Option::Some(r) = row {
                    if let ::serde_json::Value::Object(m) =
                        ::serde_json::to_value(r).unwrap_or(::serde_json::Value::Null)
                    {
                        for (k, v) in m {
                            __obj.insert(k, v);
                        }
                    }
                }
            }
        }
    } else {
        quote! {}
    };

    let m2m_loads: Vec<TokenStream> = m2m
        .iter()
        .map(|(relation, _ty)| {
            quote! {
                {
                    // Resolve to full Snippet rows (in chooser order) so a
                    // public template reading `extension.<relation>` gets
                    // objects with `.title` / `.slug` / `.body_markdown`,
                    // matching the documented `{% for c in page.<rel> %}`
                    // accessor (#243 AC: "reads back as Vec<SnippetRef>").
                    let __snippets = ::rustango_cms::page_snippet_m2m::related_snippets(
                        pool, page_id, #relation,
                    )
                    .await?;
                    __obj.insert(
                        ::std::string::String::from(#relation),
                        ::serde_json::to_value(__snippets).unwrap_or(::serde_json::Value::Null),
                    );
                }
            }
        })
        .collect();

    quote! {
        async fn load_extension(
            &self,
            pool: &::rustango_cms::__private::Pool,
            page_id: i64,
        ) -> ::core::result::Result<
            ::serde_json::Value,
            ::rustango_cms::__private::ExecError,
        > {
            let mut __obj = ::serde_json::Map::new();
            #ext_load
            #(#m2m_loads)*
            ::core::result::Result::Ok(::serde_json::Value::Object(__obj))
        }
    }
}

/// Emit `save_extension()` — upsert the extension row from the form (when
/// the struct has column-bearing `#[field]`s) and persist each declared
/// `snippet_m2m` relation into `cms_page_snippet_m2m` via `replace_all`.
fn emit_save_body(
    struct_ident: &syn::Ident,
    fields: &[FieldConfig],
    has_ext: bool,
    m2m: &[(String, String)],
) -> Result<TokenStream> {
    // The column-upsert (and its trait imports) is scoped inside its own
    // block so a pure-M2M page type — which never touches the extension
    // row — doesn't emit unused `use` warnings.
    let ext_part = if has_ext {
        let assigns_update: Vec<TokenStream> = fields
            .iter()
            .map(|f| {
                let name = &f.name;
                let key = name.to_string();
                let parse_expr = emit_form_parse(&f.ty, &key);
                quote! { row.#name = #parse_expr; }
            })
            .collect();
        let assigns_insert: Vec<TokenStream> = fields
            .iter()
            .map(|f| {
                let name = &f.name;
                let key = name.to_string();
                let parse_expr = emit_form_parse(&f.ty, &key);
                quote! { #name: #parse_expr, }
            })
            .collect();
        quote! {
            {
                use ::rustango::core::Column as _;
                use ::rustango::sql::FetcherPool as _;
                use ::rustango::Model as _;

                let existing: ::core::option::Option<#struct_ident> = #struct_ident::objects()
                    .where_(#struct_ident::page_id.eq(page_id))
                    .fetch(pool)
                    .await?
                    .into_iter()
                    .next();
                if let ::core::option::Option::Some(mut row) = existing {
                    #(#assigns_update)*
                    row.save(pool).await?;
                } else {
                    let mut row = #struct_ident {
                        page_id,
                        #(#assigns_insert)*
                        ..::core::default::Default::default()
                    };
                    row.save(pool).await?;
                }
            }
        }
    } else {
        quote! {}
    };

    let m2m_saves: Vec<TokenStream> = m2m
        .iter()
        .map(|(relation, _ty)| {
            quote! {
                {
                    // The chooser posts a JSON array of i64 snippet ids
                    // under the relation name (see _widget.html snippetm2m
                    // arm). Only touch the relation when the form actually
                    // carries the key AND it parses: an absent key means
                    // "this form didn't edit the relation", and a malformed
                    // payload must NOT silently wipe the existing links
                    // (replace_all with an empty set deletes everything).
                    if let ::core::option::Option::Some(__raw) = form.get(#relation) {
                        match ::serde_json::from_str::<::std::vec::Vec<i64>>(__raw) {
                            ::core::result::Result::Ok(__ids) => {
                                ::rustango_cms::page_snippet_m2m::replace_all(
                                    pool, page_id, #relation, &__ids,
                                )
                                .await?;
                            }
                            ::core::result::Result::Err(_) => {
                                // Malformed value — leave the relation intact.
                            }
                        }
                    }
                }
            }
        })
        .collect();

    Ok(quote! {
        async fn save_extension(
            &self,
            pool: &::rustango_cms::__private::Pool,
            page_id: i64,
            form: &::std::collections::HashMap<::std::string::String, ::std::string::String>,
        ) -> ::core::result::Result<(), ::rustango_cms::__private::ExecError> {
            #ext_part
            #(#m2m_saves)*
            ::core::result::Result::Ok(())
        }
    })
}

/// `form.get(key)` → typed value for one column.
fn emit_form_parse(ty: &Type, key: &str) -> TokenStream {
    match classify_type(ty) {
        TypeCat::String => quote! {
            form.get(#key).cloned().unwrap_or_default()
        },
        TypeCat::OptionString => quote! {
            form.get(#key).and_then(|s| {
                let t = s.trim();
                if t.is_empty() { ::core::option::Option::None }
                else { ::core::option::Option::Some(s.clone()) }
            })
        },
        TypeCat::Int => quote! {
            form.get(#key).and_then(|s| s.parse::<i64>().ok()).unwrap_or_default()
        },
        TypeCat::OptionInt => quote! {
            form.get(#key).and_then(|s| s.parse::<i64>().ok())
        },
        TypeCat::Float => quote! {
            form.get(#key).and_then(|s| s.parse::<f64>().ok()).unwrap_or_default()
        },
        TypeCat::OptionFloat => quote! {
            form.get(#key).and_then(|s| s.parse::<f64>().ok())
        },
        TypeCat::Bool => quote! {
            ::core::matches!(form.get(#key).map(|s| s.as_str()), ::core::option::Option::Some("on" | "true" | "1" | "yes"))
        },
        TypeCat::Unknown => quote! {
            // The macro doesn't know how to parse this Rust type from
            // a form string. Fall back to attempting `parse()` via
            // `FromStr` — the consumer's row may implement it.
            form.get(#key).and_then(|s| s.parse().ok()).unwrap_or_default()
        },
    }
}

#[derive(Debug, Clone, Copy)]
pub(crate) enum TypeCat {
    String,
    OptionString,
    Int,
    OptionInt,
    Float,
    OptionFloat,
    Bool,
    Unknown,
}

pub(crate) fn classify_type(ty: &Type) -> TypeCat {
    let last = path_last_segment(ty);
    match last.as_deref() {
        Some("String") => TypeCat::String,
        Some("bool") => TypeCat::Bool,
        Some("i8" | "i16" | "i32" | "i64" | "isize" | "u8" | "u16" | "u32" | "u64" | "usize") => {
            TypeCat::Int
        }
        Some("f32" | "f64") => TypeCat::Float,
        Some("Option") => {
            let inner = option_inner(ty);
            match inner.as_deref() {
                Some("String") => TypeCat::OptionString,
                Some(
                    "i8" | "i16" | "i32" | "i64" | "isize" | "u8" | "u16" | "u32" | "u64" | "usize",
                ) => TypeCat::OptionInt,
                Some("f32" | "f64") => TypeCat::OptionFloat,
                _ => TypeCat::Unknown,
            }
        }
        _ => TypeCat::Unknown,
    }
}

fn path_last_segment(ty: &Type) -> Option<String> {
    if let Type::Path(tp) = ty {
        tp.path.segments.last().map(|s| s.ident.to_string())
    } else {
        None
    }
}

fn option_inner(ty: &Type) -> Option<String> {
    if let Type::Path(tp) = ty {
        let last = tp.path.segments.last()?;
        if last.ident != "Option" {
            return None;
        }
        if let syn::PathArguments::AngleBracketed(args) = &last.arguments {
            for arg in &args.args {
                if let syn::GenericArgument::Type(inner_ty) = arg {
                    return path_last_segment(inner_ty);
                }
            }
        }
    }
    None
}

/// Derive a human display label from a relation name:
/// `"categories"` → `"Categories"`, `"featured_authors"` → `"Featured
/// Authors"`. Used as the SnippetM2M widget label when the author
/// declares the relation at the struct level (no per-field label).
pub(crate) fn humanize_label(s: &str) -> String {
    s.split(['_', '-', ' '])
        .filter(|w| !w.is_empty())
        .map(|w| {
            let mut chars = w.chars();
            match chars.next() {
                Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
                None => String::new(),
            }
        })
        .collect::<Vec<_>>()
        .join(" ")
}

// `format_ident!` is imported but not used directly yet; keep so future
// codegen tweaks don't need a fresh import.
#[allow(dead_code)]
fn _format_ident_unused() {
    let _ = format_ident!("placeholder");
}