tui-dispatch-macros 0.7.0

Procedural macros for tui-dispatch
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
//! Procedural macros for tui-dispatch

use darling::{FromDeriveInput, FromField, FromVariant};
use proc_macro::TokenStream;
use proc_macro2::Ident;
use quote::{format_ident, quote};
use std::collections::HashMap;
use syn::{parse_macro_input, DeriveInput};
use tui_dispatch_shared::{infer_action_category, pascal_to_snake_case};

/// Container-level attributes for #[derive(Action)]
#[derive(Debug, FromDeriveInput)]
#[darling(attributes(action), supports(enum_any))]
struct ActionOpts {
    ident: syn::Ident,
    data: darling::ast::Data<ActionVariant, ()>,

    /// Enable automatic category inference from variant name prefixes
    #[darling(default)]
    infer_categories: bool,

    /// Generate dispatcher trait
    #[darling(default)]
    generate_dispatcher: bool,
}

/// Variant-level attributes
#[derive(Debug, FromVariant)]
#[darling(attributes(action))]
struct ActionVariant {
    ident: syn::Ident,
    fields: darling::ast::Fields<()>,

    /// Explicit category override
    #[darling(default)]
    category: Option<String>,

    /// Exclude from category inference
    #[darling(default)]
    skip_category: bool,
}

/// Convert PascalCase to snake_case
fn to_snake_case(s: &str) -> String {
    pascal_to_snake_case(s)
}

/// Convert snake_case to PascalCase
fn to_pascal_case(s: &str) -> String {
    s.split('_')
        .map(|part| {
            let mut chars = part.chars();
            match chars.next() {
                None => String::new(),
                Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
            }
        })
        .collect()
}

/// Infer category from a variant name using naming patterns
fn infer_category(name: &str) -> Option<String> {
    infer_action_category(name)
}

/// Derive macro for the Action trait
///
/// Generates a `name()` method that returns the variant name as a static string.
///
/// With `#[action(infer_categories)]`, also generates:
/// - `category() -> Option<&'static str>` - Get action's category
/// - `category_enum() -> {Name}Category` - Get category as enum
/// - `is_{category}()` predicates for each category
/// - `{Name}Category` enum with all discovered categories
///
/// With `#[action(generate_dispatcher)]`, also generates:
/// - `{Name}Dispatcher` trait with category-based dispatch methods
///
/// # Example
/// ```ignore
/// #[derive(Action, Clone, Debug)]
/// #[action(infer_categories, generate_dispatcher)]
/// enum MyAction {
///     SearchStart,
///     SearchClear,
///     ConnectionFormOpen,
///     ConnectionFormSubmit,
///     DidConnect,
///     Tick,  // uncategorized
/// }
///
/// let action = MyAction::SearchStart;
/// assert_eq!(action.name(), "SearchStart");
/// assert_eq!(action.category(), Some("search"));
/// assert!(action.is_search());
/// ```
#[proc_macro_derive(Action, attributes(action))]
pub fn derive_action(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);

    // Try to parse with darling for attributes
    let opts = match ActionOpts::from_derive_input(&input) {
        Ok(opts) => opts,
        Err(e) => return e.write_errors().into(),
    };

    let name = &opts.ident;

    let variants = match &opts.data {
        darling::ast::Data::Enum(variants) => variants,
        _ => {
            return syn::Error::new_spanned(&input, "Action can only be derived for enums")
                .to_compile_error()
                .into();
        }
    };

    // Get the original syn variants for field info (darling loses field names)
    let syn_variants = match &input.data {
        syn::Data::Enum(data) => &data.variants,
        _ => unreachable!(), // Already checked above
    };

    // Generate basic name() implementation
    let name_arms = variants.iter().map(|v| {
        let variant_name = &v.ident;
        let variant_str = variant_name.to_string();

        match &v.fields.style {
            darling::ast::Style::Unit => quote! {
                #name::#variant_name => #variant_str
            },
            darling::ast::Style::Tuple => quote! {
                #name::#variant_name(..) => #variant_str
            },
            darling::ast::Style::Struct => quote! {
                #name::#variant_name { .. } => #variant_str
            },
        }
    });

    // Generate params() implementation - outputs field values without variant name
    let params_arms = syn_variants.iter().map(|v| {
        let variant_name = &v.ident;

        match &v.fields {
            syn::Fields::Unit => quote! {
                #name::#variant_name => ::std::string::String::new()
            },
            syn::Fields::Unnamed(fields) => {
                let field_count = fields.unnamed.len();
                let field_names: Vec<_> =
                    (0..field_count).map(|i| format_ident!("_{}", i)).collect();
                if field_count == 1 {
                    quote! {
                        #name::#variant_name(#(#field_names),*) => {
                            tui_dispatch::debug::debug_string(&#(#field_names),*)
                        }
                    }
                } else {
                    let parts = field_names.iter().map(|field| {
                        quote! { tui_dispatch::debug::debug_string(&#field) }
                    });
                    quote! {
                        #name::#variant_name(#(#field_names),*) => {
                            let values = ::std::vec![#(#parts),*];
                            format!("({})", values.join(", "))
                        }
                    }
                }
            }
            syn::Fields::Named(fields) => {
                let field_names: Vec<_> = fields
                    .named
                    .iter()
                    .filter_map(|f| f.ident.as_ref())
                    .collect();
                if field_names.is_empty() {
                    quote! {
                        #name::#variant_name { .. } => ::std::string::String::new()
                    }
                } else {
                    let parts = field_names.iter().map(|field| {
                        let label = field.to_string();
                        quote! {
                            format!("{}: {}", #label, tui_dispatch::debug::debug_string(&#field))
                        }
                    });
                    quote! {
                        #name::#variant_name { #(#field_names),*, .. } => {
                            let values = ::std::vec![#(#parts),*];
                            format!("{{{}}}", values.join(", "))
                        }
                    }
                }
            }
        }
    });

    let params_pretty_arms = syn_variants.iter().map(|v| {
        let variant_name = &v.ident;

        match &v.fields {
            syn::Fields::Unit => quote! {
                #name::#variant_name => ::std::string::String::new()
            },
            syn::Fields::Unnamed(fields) => {
                let field_count = fields.unnamed.len();
                let field_names: Vec<_> =
                    (0..field_count).map(|i| format_ident!("_{}", i)).collect();
                if field_count == 1 {
                    quote! {
                        #name::#variant_name(#(#field_names),*) => {
                            tui_dispatch::debug::debug_string_pretty(&#(#field_names),*)
                        }
                    }
                } else {
                    let parts = field_names.iter().map(|field| {
                        quote! { tui_dispatch::debug::debug_string_pretty(&#field) }
                    });
                    quote! {
                        #name::#variant_name(#(#field_names),*) => {
                            let values = ::std::vec![#(#parts),*];
                            format!("({})", values.join(", "))
                        }
                    }
                }
            }
            syn::Fields::Named(fields) => {
                let field_names: Vec<_> = fields
                    .named
                    .iter()
                    .filter_map(|f| f.ident.as_ref())
                    .collect();
                if field_names.is_empty() {
                    quote! {
                        #name::#variant_name { .. } => ::std::string::String::new()
                    }
                } else {
                    let parts = field_names.iter().map(|field| {
                        let label = field.to_string();
                        quote! {
                            format!("{}: {}", #label, tui_dispatch::debug::debug_string_pretty(&#field))
                        }
                    });
                    quote! {
                        #name::#variant_name { #(#field_names),*, .. } => {
                            let values = ::std::vec![#(#parts),*];
                            format!("{{{}}}", values.join(", "))
                        }
                    }
                }
            }
        }
    });

    let mut expanded = quote! {
        impl tui_dispatch::Action for #name {
            fn name(&self) -> &'static str {
                match self {
                    #(#name_arms),*
                }
            }
        }

        impl tui_dispatch::ActionParams for #name {
            fn params(&self) -> ::std::string::String {
                match self {
                    #(#params_arms),*
                }
            }

            fn params_pretty(&self) -> ::std::string::String {
                match self {
                    #(#params_pretty_arms),*
                }
            }
        }
    };

    // If category inference is enabled, generate category-related code
    if opts.infer_categories {
        // Collect categories and their variants
        let mut categories: HashMap<String, Vec<&Ident>> = HashMap::new();
        let mut variant_categories: Vec<(&Ident, Option<String>)> = Vec::new();

        for v in variants.iter() {
            let cat = if v.skip_category {
                None
            } else if let Some(ref explicit_cat) = v.category {
                Some(explicit_cat.clone())
            } else {
                infer_category(&v.ident.to_string())
            };

            variant_categories.push((&v.ident, cat.clone()));

            if let Some(ref category) = cat {
                categories
                    .entry(category.clone())
                    .or_default()
                    .push(&v.ident);
            }
        }

        // Sort categories for deterministic output
        let mut sorted_categories: Vec<_> = categories.keys().cloned().collect();
        sorted_categories.sort();

        // Create deduplicated category match arms
        let category_arms_dedup: Vec<_> = variant_categories
            .iter()
            .map(|(variant, cat)| {
                let cat_expr = match cat {
                    Some(c) => quote! { ::core::option::Option::Some(#c) },
                    None => quote! { ::core::option::Option::None },
                };
                // Use wildcard pattern to handle all field types
                quote! { #name::#variant { .. } => #cat_expr }
            })
            .collect();

        // Generate category enum
        let category_enum_name = format_ident!("{}Category", name);
        let category_variants: Vec<_> = sorted_categories
            .iter()
            .map(|c| format_ident!("{}", to_pascal_case(c)))
            .collect();
        let category_variant_names: Vec<_> = sorted_categories.clone();

        // Generate category_enum() method arms
        let category_enum_arms: Vec<_> = variant_categories
            .iter()
            .map(|(variant, cat)| {
                let cat_variant = match cat {
                    Some(c) => format_ident!("{}", to_pascal_case(c)),
                    None => format_ident!("Uncategorized"),
                };
                quote! { #name::#variant { .. } => #category_enum_name::#cat_variant }
            })
            .collect();

        // Generate is_* predicates
        let predicates: Vec<_> = sorted_categories
            .iter()
            .map(|cat| {
                let predicate_name = format_ident!("is_{}", cat);
                let cat_variants = categories.get(cat).unwrap();
                let patterns: Vec<_> = cat_variants
                    .iter()
                    .map(|v| quote! { #name::#v { .. } })
                    .collect();
                let doc = format!(
                    "Returns true if this action belongs to the `{}` category.",
                    cat
                );

                quote! {
                    #[doc = #doc]
                    pub fn #predicate_name(&self) -> bool {
                        matches!(self, #(#patterns)|*)
                    }
                }
            })
            .collect();

        // Add category-related implementations
        let category_enum_doc = format!(
            "Action categories for [`{}`].\n\n\
             Use [`{}::category_enum()`] to get the category of an action.",
            name, name
        );

        expanded = quote! {
            #expanded

            #[doc = #category_enum_doc]
            #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
            pub enum #category_enum_name {
                #(#category_variants,)*
                /// Actions that don't belong to any specific category.
                Uncategorized,
            }

            impl #category_enum_name {
                /// Get all category values
                pub fn all() -> &'static [Self] {
                    &[#(Self::#category_variants,)* Self::Uncategorized]
                }

                /// Get category name as string
                pub fn name(&self) -> &'static str {
                    match self {
                        #(Self::#category_variants => #category_variant_names,)*
                        Self::Uncategorized => "uncategorized",
                    }
                }
            }

            impl #name {
                /// Get the action's category (if categorized)
                pub fn category(&self) -> ::core::option::Option<&'static str> {
                    match self {
                        #(#category_arms_dedup,)*
                    }
                }

                /// Get the category as an enum value
                pub fn category_enum(&self) -> #category_enum_name {
                    match self {
                        #(#category_enum_arms,)*
                    }
                }

                #(#predicates)*
            }

            impl tui_dispatch::ActionCategory for #name {
                type Category = #category_enum_name;

                fn category(&self) -> ::core::option::Option<&'static str> {
                    #name::category(self)
                }

                fn category_enum(&self) -> Self::Category {
                    #name::category_enum(self)
                }
            }
        };

        // Generate dispatcher trait if requested
        if opts.generate_dispatcher {
            let dispatcher_trait_name = format_ident!("{}Dispatcher", name);

            let dispatch_methods: Vec<_> = sorted_categories
                .iter()
                .map(|cat| {
                    let method_name = format_ident!("dispatch_{}", cat);
                    let doc = format!("Handle actions in the `{}` category.", cat);
                    quote! {
                        #[doc = #doc]
                        fn #method_name(&mut self, action: &#name) -> bool {
                            false
                        }
                    }
                })
                .collect();

            let dispatch_arms: Vec<_> = sorted_categories
                .iter()
                .map(|cat| {
                    let method_name = format_ident!("dispatch_{}", cat);
                    let cat_variant = format_ident!("{}", to_pascal_case(cat));
                    quote! {
                        #category_enum_name::#cat_variant => self.#method_name(action)
                    }
                })
                .collect();

            let dispatcher_doc = format!(
                "Dispatcher trait for [`{}`].\n\n\
                 Implement the `dispatch_*` methods for each category you want to handle.\n\
                 The [`dispatch()`](Self::dispatch) method automatically routes to the correct handler.",
                name
            );

            expanded = quote! {
                #expanded

                #[doc = #dispatcher_doc]
                pub trait #dispatcher_trait_name {
                    #(#dispatch_methods)*

                    /// Handle uncategorized actions.
                    fn dispatch_uncategorized(&mut self, action: &#name) -> bool {
                        false
                    }

                    /// Main dispatch entry point - routes to category-specific handlers.
                    fn dispatch(&mut self, action: &#name) -> bool {
                        match action.category_enum() {
                            #(#dispatch_arms,)*
                            #category_enum_name::Uncategorized => self.dispatch_uncategorized(action),
                        }
                    }
                }
            };
        }
    }

    TokenStream::from(expanded)
}

/// Derive macro for the BindingContext trait
///
/// Generates implementations for `name()`, `from_name()`, and `all()` methods.
/// The context name is derived from the variant name converted to snake_case.
///
/// # Example
/// ```ignore
/// #[derive(BindingContext, Clone, Copy, PartialEq, Eq, Hash)]
/// enum MyContext {
///     Default,
///     Search,
///     ConnectionForm,
/// }
///
/// // Generated names: "default", "search", "connection_form"
/// assert_eq!(MyContext::Default.name(), "default");
/// assert_eq!(MyContext::from_name("search"), Some(MyContext::Search));
/// ```
#[proc_macro_derive(BindingContext)]
pub fn derive_binding_context(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let name = &input.ident;

    let expanded = match &input.data {
        syn::Data::Enum(data) => {
            // Check that all variants are unit variants
            for variant in &data.variants {
                if !matches!(variant.fields, syn::Fields::Unit) {
                    return syn::Error::new_spanned(
                        variant,
                        "BindingContext can only be derived for enums with unit variants",
                    )
                    .to_compile_error()
                    .into();
                }
            }

            let variant_names: Vec<_> = data.variants.iter().map(|v| &v.ident).collect();
            let variant_strings: Vec<_> = variant_names
                .iter()
                .map(|v| to_snake_case(&v.to_string()))
                .collect();

            let name_arms = variant_names
                .iter()
                .zip(variant_strings.iter())
                .map(|(v, s)| {
                    quote! { #name::#v => #s }
                });

            let from_name_arms = variant_names
                .iter()
                .zip(variant_strings.iter())
                .map(|(v, s)| {
                    quote! { #s => ::core::option::Option::Some(#name::#v) }
                });

            let all_variants = variant_names.iter().map(|v| quote! { #name::#v });

            quote! {
                impl tui_dispatch::BindingContext for #name {
                    fn name(&self) -> &'static str {
                        match self {
                            #(#name_arms),*
                        }
                    }

                    fn from_name(name: &str) -> ::core::option::Option<Self> {
                        match name {
                            #(#from_name_arms,)*
                            _ => ::core::option::Option::None,
                        }
                    }

                    fn all() -> &'static [Self] {
                        static ALL: &[#name] = &[#(#all_variants),*];
                        ALL
                    }
                }
            }
        }
        _ => {
            return syn::Error::new_spanned(input, "BindingContext can only be derived for enums")
                .to_compile_error()
                .into();
        }
    };

    TokenStream::from(expanded)
}

/// Derive macro for the ComponentId trait
///
/// Generates implementations for `name()` method that returns the variant name.
///
/// # Example
/// ```ignore
/// #[derive(ComponentId, Clone, Copy, PartialEq, Eq, Hash, Debug)]
/// enum MyComponentId {
///     Sidebar,
///     MainContent,
///     StatusBar,
/// }
///
/// assert_eq!(MyComponentId::Sidebar.name(), "Sidebar");
/// ```
#[proc_macro_derive(ComponentId)]
pub fn derive_component_id(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let name = &input.ident;

    let expanded = match &input.data {
        syn::Data::Enum(data) => {
            // Check that all variants are unit variants
            for variant in &data.variants {
                if !matches!(variant.fields, syn::Fields::Unit) {
                    return syn::Error::new_spanned(
                        variant,
                        "ComponentId can only be derived for enums with unit variants",
                    )
                    .to_compile_error()
                    .into();
                }
            }

            let variant_names: Vec<_> = data.variants.iter().map(|v| &v.ident).collect();
            let variant_strings: Vec<_> = variant_names.iter().map(|v| v.to_string()).collect();

            let name_arms = variant_names
                .iter()
                .zip(variant_strings.iter())
                .map(|(v, s)| {
                    quote! { #name::#v => #s }
                });

            quote! {
                impl tui_dispatch::ComponentId for #name {
                    fn name(&self) -> &'static str {
                        match self {
                            #(#name_arms),*
                        }
                    }
                }
            }
        }
        _ => {
            return syn::Error::new_spanned(input, "ComponentId can only be derived for enums")
                .to_compile_error()
                .into();
        }
    };

    TokenStream::from(expanded)
}

// ============================================================================
// DebugState derive macro
// ============================================================================

/// Container-level attributes for #[derive(DebugState)]
#[derive(Debug, FromDeriveInput)]
#[darling(attributes(debug_state), supports(struct_named))]
struct DebugStateOpts {
    ident: syn::Ident,
    data: darling::ast::Data<(), DebugStateField>,
}

/// Field-level attributes for DebugState
#[derive(Debug, FromField)]
#[darling(attributes(debug))]
struct DebugStateField {
    ident: Option<syn::Ident>,

    /// Section name for this field (groups fields together)
    #[darling(default)]
    section: Option<String>,

    /// Skip this field in debug output
    #[darling(default)]
    skip: bool,

    /// Custom display format (e.g., "{:?}" for Debug, "{:#?}" for pretty Debug)
    #[darling(default)]
    format: Option<String>,

    /// Custom label for this field (defaults to field name)
    #[darling(default)]
    label: Option<String>,

    /// Use Debug trait instead of Display
    #[darling(default)]
    debug_fmt: bool,
}

/// Derive macro for the DebugState trait
///
/// Automatically generates `debug_sections()` implementation from struct fields.
///
/// # Attributes
///
/// - `#[debug(section = "Name")]` - Group field under a section
/// - `#[debug(skip)]` - Exclude field from debug output
/// - `#[debug(label = "Custom Label")]` - Use custom label instead of field name
/// - `#[debug(debug_fmt)]` - Use `{:?}` format instead of `Display`
/// - `#[debug(format = "{:#?}")]` - Use custom format string
///
/// # Example
///
/// ```ignore
/// use tui_dispatch::DebugState;
///
/// #[derive(DebugState)]
/// struct AppState {
///     #[debug(section = "Connection")]
///     host: String,
///     #[debug(section = "Connection")]
///     port: u16,
///
///     #[debug(section = "UI")]
///     scroll_offset: usize,
///
///     #[debug(skip)]
///     internal_cache: HashMap<String, Data>,
///
///     #[debug(section = "Stats", debug_fmt)]
///     status: ConnectionStatus,
/// }
/// ```
///
/// Fields without a section attribute are grouped under a section named after
/// the struct (e.g., "AppState").
#[proc_macro_derive(DebugState, attributes(debug, debug_state))]
pub fn derive_debug_state(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);

    let opts = match DebugStateOpts::from_derive_input(&input) {
        Ok(opts) => opts,
        Err(e) => return e.write_errors().into(),
    };

    let name = &opts.ident;
    let default_section = name.to_string();

    let fields = match &opts.data {
        darling::ast::Data::Struct(fields) => fields,
        _ => {
            return syn::Error::new_spanned(&input, "DebugState can only be derived for structs")
                .to_compile_error()
                .into();
        }
    };

    // Group fields by section
    let mut sections: HashMap<String, Vec<&DebugStateField>> = HashMap::new();
    let mut section_order: Vec<String> = Vec::new();

    for field in fields.iter() {
        if field.skip {
            continue;
        }

        let section_name = field
            .section
            .clone()
            .unwrap_or_else(|| default_section.clone());

        if !section_order.contains(&section_name) {
            section_order.push(section_name.clone());
        }

        sections.entry(section_name).or_default().push(field);
    }

    // Generate code for each section
    let section_code: Vec<_> = section_order
        .iter()
        .map(|section_name| {
            let fields_in_section = sections.get(section_name).unwrap();

            let entry_calls: Vec<_> = fields_in_section
                .iter()
                .filter_map(|field| {
                    let field_ident = field.ident.as_ref()?;
                    let label = field
                        .label
                        .clone()
                        .unwrap_or_else(|| field_ident.to_string());

                    let value_expr = if let Some(ref fmt) = field.format {
                        quote! { format!(#fmt, self.#field_ident) }
                    } else if field.debug_fmt {
                        quote! { format!("{:?}", self.#field_ident) }
                    } else {
                        quote! { tui_dispatch::debug::debug_string(&self.#field_ident) }
                    };

                    Some(quote! {
                        .entry(#label, #value_expr)
                    })
                })
                .collect();

            quote! {
                tui_dispatch::debug::DebugSection::new(#section_name)
                    #(#entry_calls)*
            }
        })
        .collect();

    let expanded = quote! {
        impl tui_dispatch::debug::DebugState for #name {
            fn debug_sections(&self) -> ::std::vec::Vec<tui_dispatch::debug::DebugSection> {
                ::std::vec![
                    #(#section_code),*
                ]
            }
        }
    };

    TokenStream::from(expanded)
}

// ============================================================================
// FeatureFlags derive macro
// ============================================================================

/// Field-level attributes for FeatureFlags
#[derive(Debug, FromField)]
#[darling(attributes(flag))]
struct FeatureFlagsField {
    ident: Option<syn::Ident>,
    ty: syn::Type,

    /// Default value for this feature (defaults to false)
    #[darling(default)]
    default: Option<bool>,
}

/// Container-level attributes for #[derive(FeatureFlags)]
#[derive(Debug, FromDeriveInput)]
#[darling(attributes(feature_flags), supports(struct_named))]
struct FeatureFlagsOpts {
    ident: syn::Ident,
    data: darling::ast::Data<(), FeatureFlagsField>,
}

/// Derive macro for the FeatureFlags trait
///
/// Generates implementations for `is_enabled()`, `set()`, and `all_flags()` methods.
/// Also generates a `Default` implementation using the specified defaults.
///
/// # Attributes
///
/// - `#[flag(default = true)]` - Set default value (defaults to false)
///
/// # Example
///
/// ```ignore
/// use tui_dispatch::FeatureFlags;
///
/// #[derive(FeatureFlags)]
/// struct Features {
///     #[flag(default = false)]
///     new_search_ui: bool,
///
///     #[flag(default = true)]
///     vim_bindings: bool,
/// }
///
/// let mut features = Features::default();
/// assert!(!features.new_search_ui);
/// assert!(features.vim_bindings);
///
/// features.enable("new_search_ui");
/// assert!(features.new_search_ui);
/// ```
#[proc_macro_derive(FeatureFlags, attributes(flag, feature_flags))]
pub fn derive_feature_flags(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);

    let opts = match FeatureFlagsOpts::from_derive_input(&input) {
        Ok(opts) => opts,
        Err(e) => return e.write_errors().into(),
    };

    let name = &opts.ident;

    let fields = match &opts.data {
        darling::ast::Data::Struct(fields) => fields,
        _ => {
            return syn::Error::new_spanned(
                &input,
                "FeatureFlags can only be derived for structs with named fields",
            )
            .to_compile_error()
            .into();
        }
    };

    // Collect bool fields only
    let bool_fields: Vec<_> = fields
        .iter()
        .filter_map(|f| {
            let ident = f.ident.as_ref()?;
            // Check if type is bool
            if let syn::Type::Path(type_path) = &f.ty {
                if type_path.path.is_ident("bool") {
                    return Some((ident.clone(), f.default.unwrap_or(false)));
                }
            }
            None
        })
        .collect();

    if bool_fields.is_empty() {
        return syn::Error::new_spanned(
            &input,
            "FeatureFlags struct must have at least one bool field",
        )
        .to_compile_error()
        .into();
    }

    // Generate is_enabled match arms
    let is_enabled_arms: Vec<_> = bool_fields
        .iter()
        .map(|(ident, _)| {
            let name_str = ident.to_string();
            quote! { #name_str => ::core::option::Option::Some(self.#ident) }
        })
        .collect();

    // Generate set match arms
    let set_arms: Vec<_> = bool_fields
        .iter()
        .map(|(ident, _)| {
            let name_str = ident.to_string();
            quote! {
                #name_str => {
                    self.#ident = enabled;
                    true
                }
            }
        })
        .collect();

    // Generate all_flags array
    let flag_names: Vec<_> = bool_fields
        .iter()
        .map(|(ident, _)| ident.to_string())
        .collect();

    // Generate Default impl with proper defaults
    let default_fields: Vec<_> = bool_fields
        .iter()
        .map(|(ident, default)| {
            quote! { #ident: #default }
        })
        .collect();

    let expanded = quote! {
        impl tui_dispatch::FeatureFlags for #name {
            fn is_enabled(&self, name: &str) -> ::core::option::Option<bool> {
                match name {
                    #(#is_enabled_arms,)*
                    _ => ::core::option::Option::None,
                }
            }

            fn set(&mut self, name: &str, enabled: bool) -> bool {
                match name {
                    #(#set_arms)*
                    _ => false,
                }
            }

            fn all_flags() -> &'static [&'static str] {
                &[#(#flag_names),*]
            }
        }

        impl ::core::default::Default for #name {
            fn default() -> Self {
                Self {
                    #(#default_fields,)*
                }
            }
        }
    };

    TokenStream::from(expanded)
}

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

    #[test]
    fn test_to_snake_case_handles_acronyms() {
        assert_eq!(to_snake_case("APIFetch"), "api_fetch");
        assert_eq!(to_snake_case("HTTPResult"), "http_result");
    }

    #[test]
    fn test_infer_category_handles_acronyms() {
        assert_eq!(infer_category("APIFetchStart"), Some("api".to_string()));
        assert_eq!(
            infer_category("SearchHTTPStart"),
            Some("search_http".to_string())
        );
    }
}