metrique-macro 0.1.14

Library for working with unit of work metrics - #[metrics] macro
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
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

#![deny(missing_docs)]
#![doc = include_str!("../README.md")]
#![cfg_attr(docsrs, feature(doc_cfg))]

mod aggregate;
mod derive_utils;
mod emf;
mod entry_impl;
mod enums;
mod inflect;
mod structs;
mod value_impl;

use darling::{
    FromField, FromMeta,
    ast::NestedMeta,
    util::{Flag, SpannedValue},
};
use emf::DimensionSets;
use inflect::NameStyle;
use proc_macro::TokenStream;
use proc_macro2::{Span, TokenStream as Ts2};
use quote::{ToTokens, quote, quote_spanned};
use syn::{
    Attribute, Data, DeriveInput, Error, Fields, GenericParam, Generics, Ident, Result, Type,
    Visibility, parse_macro_input, spanned::Spanned,
};

use crate::inflect::{name_contains_dot, name_contains_uninflectables, name_ends_with_delimiter};

/// Transforms a struct or enum into a unit-of-work metric.
///
/// # Container Attributes
///
/// | Attribute | Type | Description | Example |
/// |-----------|------|-------------|---------|
/// | `rename_all` | String | Changes the case style of all field names | `#[metrics(rename_all = "PascalCase")]` |
/// | `prefix` | String | Adds a prefix to all field names (prefix gets inflected) | `#[metrics(prefix = "api_")]` |
/// | `exact_prefix` | String | Adds a prefix to all field names without inflection | `#[metrics(exact_prefix = "API_")]` |
/// | `emf::dimension_sets` | Array | Defines dimension sets for CloudWatch metrics | `#[metrics(emf::dimension_sets = [["Status", "Operation"]])]` |
/// | `tag` | Nested | On entry enums, adds a tag field with the variant name. Tag value respects `rename_all` and variant `name`, but not `prefix`. | |
/// | - `name` | String | Name of the tag field (inflectable, respects `prefix` and `rename_all`) | `#[metrics(tag(name = "operation"))]` |
/// | - `name_exact` | String | Name of the tag field (exact, not affected by `prefix` or `rename_all`) | `#[metrics(tag(name_exact = "operation"))]` |
/// | - `sample_group` | Flag | Include tag in sample group | `#[metrics(tag(name = "op", sample_group))]` |
/// | `subfield` | Flag | When set, this metric can only be used when nested within other metrics, and can be consumed by reference (has both `impl CloseValue for &MyStruct` and `impl CloseValue for MyStruct`). It cannot be added to a sink directly. | `#[metrics(subfield)]` |
/// | `subfield_owned` | Flag | When set, this metric can only be used when nested within other metrics. It cannot be added to a sink directly. | `#[metrics(subfield_owned)]` |
/// | `value` | Flag | Used for *structs*. Makes the struct a value newtype | `#[metrics(value)]` |
/// | `value(string)` | Flag | Used for *enums*. Transforms the enum into a string value. | `#[metrics(value(string))]` |
/// | `sample_group` | Flag | On `#[metrics(value)]`, forwards `sample_group` to the inner field | `#[metrics(value, sample_group)]` |
///
/// # Field Attributes
///
/// | Attribute | Type | Description | Example |
/// |-----------|------|-------------|---------|
/// | `name` | String | Overrides the field name in metrics | `#[metrics(name = "CustomName")]` |
/// | `unit` | Path | Specifies the unit for the metric value | `#[metrics(unit = Millisecond)]` |
/// | `format` | Path | Specifies the formatter (`ValueFormatter`) for the metric value | `#[metrics(format=EpochSeconds)]` |
/// | `timestamp` | Flag | Marks a field as the canonical timestamp | `#[metrics(timestamp)]` |
/// | `sample_group` | Flag | Marks a field as a sample group - it will still be emitted as a value | `#[metrics(sample_group)]` |
/// | `prefix` | String | Adds a prefix to flattened entries. Prefix will get inflected to the right case style | `#[metrics(flatten, prefix="prefix-")]` |
/// | `exact_prefix` | String | Adds a prefix to flattened entries without inflection | `#[metrics(flatten, exact_prefix="API_")]` |
/// | `flatten` | Flag | Flattens nested `CloseEntry` metric structs | `#[metrics(flatten)]` |
/// | `flatten_entry` | Flag | Flattens nested `CloseValue<Closed: Entry>` metric structs, with no prefix or inflection | `#[metrics(flatten_entry)]` |
/// | `no_close` | Flag | Use the entry directly instead of closing it | `#[metrics(no_close)]` |
/// | `ignore` | Flag | Excludes the field from metrics | `#[metrics(ignore)]` |
///
/// # Variant Attributes
///
/// For enum usage, see the [Enums](#enums) section below.
///
/// | Attribute | Type | Description | Example |
/// |-----------|------|-------------|---------|
/// | `name` | String | Overrides the variant name in metrics | `#[metrics(name = "CustomName")]` |
///
/// # Metric Names
///
/// ## Prefixes
///
/// Prefixes can be attached to metrics in 2 different ways:
///
/// 1. Prefixes on flattened subfields, which affect all the metrics contained within
///    the flattened subfield:
///
///    ```rust
///    # use metrique::unit_of_work::metrics;
///    # use std::time::Duration;
///    #[metrics(subfield)]
///    struct Subfield {
///        request_latency: Duration, // inflected
///        #[metrics(name="NDucks")] // not inflected (since `name` is not inflected), prefixed
///        number_of_ducks: u32,
///    }
///
///    #[metrics(rename_all = "kebab-case")]
///    struct Base {
///        // uses `exact_prefix`, not inflected
///        #[metrics(flatten, exact_prefix = "API:")]
///        api: Subfield,
///        // uses `prefix`, inflected
///        #[metrics(flatten, prefix = "alt")]
///        alt: Subfield,
///    }
///
///    let vec_sink = metrique::writer::sink::VecEntrySink::new();
///    Base {
///        api: Subfield { request_latency: Duration::from_millis(1), number_of_ducks: 0 },
///        alt: Subfield { request_latency: Duration::from_millis(1), number_of_ducks: 0 }
///    }.append_on_drop(vec_sink.clone());
///    let entries = vec_sink.drain();
///    let entry = metrique::test_util::to_test_entry(&entries[0]);
///    assert_eq!(entry.metrics["API:request-latency"], 1.0);
///    assert_eq!(entry.metrics["alt-request-latency"], 1.0);
///    assert_eq!(entry.metrics["API:NDucks"], 0);
///    assert_eq!(entry.metrics["alt-NDucks"], 0);
///    ```
/// 2. Prefixes on the struct itself, which *only* affect fields within the metric
///    that don't have a `name` or a `flatten` attribute:
///
///    ```rust
///    # use metrique::unit_of_work::metrics;
///    # use std::time::Duration;
///    #[metrics(subfield)]
///    struct Subfield {
///        request_latency: Duration, // inflected
///    }
///
///    #[metrics(prefix = "Foo-" /* prefix gets inflected */, rename_all = "kebab-case")]
///    struct Base {
///        // prefix does not propagate to subfield. Use `prefix = "Foo-"` to propagate
///        #[metrics(flatten)]
///        sub: Subfield,
///        // prefix does not propagate to named field
///        #[metrics(name = "n-ducks")]
///        number_of_ducks: u32,
///        // prefix does propagate to other
///        number_of_geese: u32,
///    }
///
///    let vec_sink = metrique::writer::sink::VecEntrySink::new();
///    Base {
///        sub: Subfield { request_latency: Duration::from_millis(1) },
///        number_of_ducks: 0,
///        number_of_geese: 0
///    }.append_on_drop(vec_sink.clone());
///    let entries = vec_sink.drain();
///    let entry = metrique::test_util::to_test_entry(&entries[0]);
///    assert_eq!(entry.metrics["request-latency"], 1.0);
///    assert_eq!(entry.metrics["n-ducks"], 0);
///    // prefix-on-struct only applies to this
///    assert_eq!(entry.metrics["foo-number-of-geese"], 0);
///    ```
///
/// Note that prefix-attribute-on-flatten *does* apply to nested fields that have
/// a `name` attribute.
///
/// Prefixes can either be inflectable (with the `prefix` attribute) or non-inflectable
/// (with the `exact_prefix` attribute).
///
/// ## Inflection
///
/// Metric names are inflected to allow them to fit into the name style used by the
/// application. This uses the `Inflector` crate and supports inflecting metrics into
/// PascalCase, snake_case, and kebab-case.
///
/// Metric names assigned via the `name` attribute are not inflected, but if they are
/// contained in a metric with a prefix, the prefix can be inflected. Prefixes assigned via
/// `exact_prefix` are similarly not inflected.
///
/// For example, this emits a metric named "foo_Bar", since "Bar" is assigned via a
/// `name` attribute and therefore not inflected, but the prefix is assigned
/// via `prefix` and is therefore inflected.
///
/// ```rust
/// # use metrique::unit_of_work::metrics;
///
/// #[metrics(subfield)]
/// struct Subfield {
///     #[metrics(name = "NDucks")]
///     number_of_ducks: u32,
/// }
///
/// #[metrics(rename_all = "snake_case")]
/// struct Base {
///     #[metrics(flatten, prefix = "Waterfowl_")]
///     waterfowl: Subfield,
/// }
///
/// let vec_sink = metrique::writer::sink::VecEntrySink::new();
/// Base { waterfowl: Subfield { number_of_ducks: 0 } }
///     .append_on_drop(vec_sink.clone());
/// let entries = vec_sink.drain();
/// let entry = metrique::test_util::to_test_entry(&entries[0]);
/// assert_eq!(entry.metrics["waterfowl_NDucks"], 0);
/// ```
///
/// # Example
///
/// ```rust
/// use metrique::unit_of_work::metrics;
/// use metrique::timers::{Timestamp, Timer};
/// use metrique::unit::{Count, Millisecond};
/// use metrique::writer::GlobalEntrySink;
/// use metrique::ServiceMetrics;
/// use std::time::SystemTime;
///
/// #[metrics(value(string), rename_all = "snake_case")]
/// enum Operation {
///    CountDucks
/// }
///
/// #[metrics(value)]
/// struct RequestCount(#[metrics(unit=Count)] usize);
///
/// #[metrics(rename_all = "PascalCase")]
/// struct RequestMetrics {
///     #[metrics(sample_group)]
///     operation: Operation,
///
///     #[metrics(timestamp)]
///     timestamp: SystemTime,
///
///     #[metrics(unit = Millisecond)]
///     operation_time: Timer,
///
///     #[metrics(flatten, prefix = "sub_")]
///     nested: NestedMetrics,
///
///     request_count: RequestCount,
/// }
///
/// #[metrics(subfield)]
/// struct NestedMetrics {
///     #[metrics(name = "CustomCounter")]
///     counter: usize,
/// }
///
/// impl RequestMetrics {
///     fn init(operation: Operation) -> RequestMetricsGuard {
///         RequestMetrics {
///             timestamp: SystemTime::now(),
///             operation,
///             operation_time: Timer::start_now(),
///             nested: NestedMetrics { counter: 0 },
///             request_count: RequestCount(0),
///         }.append_on_drop(ServiceMetrics::sink())
///     }
/// }
/// ```
/// # Enums
///
/// Enums can be used in two ways: as value enums or entry enums.
///
/// ## Value Enums
///
/// Value enums with `#[metrics(value(string))]` convert enum variants to string values.
/// Only unit variants are allowed. Variant names respect `#[metrics(name = "...")]` and `rename_all`:
///
/// ```rust
/// # use metrique::unit_of_work::metrics;
/// #[metrics(value(string), rename_all = "snake_case")]
/// enum Operation {
///     #[metrics(name = "custom_read")]
///     ReadData,
///     WriteData,
/// }
/// // Operation::ReadData converts to "custom_read"
/// // Operation::WriteData converts to "write_data"
///
/// #[metrics]
/// struct Request {
///     #[metrics(sample_group)]
///     operation: Operation,
///     count: usize,
/// }
/// ```
///
/// ## Entry Enums
///
/// Entry enums allow different metric fields per variant. Contained fields respect container and
/// field attributes as used by structs.
///
/// Variants can be tuple variants (which must use flatten/flatten_entry/ignore attributes, since
/// their fields are unnamed). Or, they can use struct variants with named fields and the full
/// range of field attributes available. (Unit variants are also supported but don't do much unless
/// used with a `tag` field; see the following `Tag field` section.)
///
/// ```rust
/// # use metrique::unit_of_work::metrics;
/// # use metrique::unit::Millisecond;
/// # use std::time::Duration;
///
/// #[metrics(subfield)]
/// struct ReadMetrics {
///     bytes_read: usize,
/// }
///
/// #[metrics(rename_all = "PascalCase")]
/// enum Operation {
///     Read(#[metrics(flatten)] ReadMetrics),
///     Write {
///         #[metrics(unit = Millisecond)]
///         latency: Duration,
///         bytes_written: usize,
///     },
/// }
///
/// let entry = metrique::test_util::test_metric(
///     Operation::Read(ReadMetrics { bytes_read: 1024 })
/// );
/// assert_eq!(entry.metrics["BytesRead"], 1024);
///
/// let entry = metrique::test_util::test_metric(
///     Operation::Write { latency: Duration::from_millis(5), bytes_written: 2048 }
/// );
/// assert_eq!(entry.metrics["Latency"], 5);
/// assert_eq!(entry.metrics["BytesWritten"], 2048);
/// ```
///
/// ### Tag Field
///
/// Entry enums can include a `tag` attribute to add a field containing the variant name:
///
/// ```rust
/// # use metrique::unit_of_work::metrics;
/// # use metrique::test_util::test_metric;
/// # use metrique::unit::Millisecond;
/// # use std::time::Duration;
///
/// #[metrics(tag(name = "Operation"), rename_all = "PascalCase")]
/// enum Request {
///     Read { bytes: usize },
///     Write {
///         #[metrics(unit = Millisecond)]
///         latency: Duration,
///     },
///     // doesn't contain fields, but still has the tag field injected
///     Delete,
/// }
///
/// let entry = test_metric(Request::Read { bytes: 1024 });
/// assert_eq!(entry.values["Operation"], "Read");  // Tag field with variant name
/// assert_eq!(entry.metrics["Bytes"], 1024);
/// ```
///
/// The tag field name is specified explicitly and not affected by `prefix` or `rename_all`.
/// The tag value (variant name) respects `rename_all` and variant `name` attributes, but not `prefix`.
///
/// The optional `sample_group` flag includes the tag field in the sample group:
///
/// ```rust
/// # use metrique::unit_of_work::metrics;
/// # use metrique::test_util::test_metric;
///
/// #[metrics(tag(name = "Operation", sample_group))]
/// enum Request {
///     Read { bytes: usize },
///     Write { bytes: usize },
/// }
///
/// let entry = test_metric(Request::Read { bytes: 1024 });
/// // The tag field "Operation" with value "Read" is included in sample_group
/// ```
///
/// # Generated Types
///
/// For a struct or entry enum named `MyMetrics`, the macro generates:
/// - `MyMetricsEntry`: The internal representation used for serialization, implements `InflectableEntry`
/// - `MyMetricsGuard`: A wrapper that implements `Deref`/`DerefMut` to the original struct and handles emission on drop.
///   A type alias to ``AppendAndCloseOnDrop`.
/// - `MyMetricsHandle`: A shareable handle for concurrent access to the metrics.
///   A type alias to ``AppendAndCloseOnDropHandle`.
///
/// Value enums do not have new types generated, only trait implementations (`From<&MyEnum> for &'static str`, `SampleGroup`, `Value`).
#[proc_macro_attribute]
pub fn metrics(attr: TokenStream, input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let input = parse_macro_input!(input as DeriveInput);

    // There's a little bit of juggling here so we can return errors both from the root attribute & the inner attribute.
    // We will also write the compiler error from the root attribute into the token stream if it failed. But if it did fail,
    // we still analyze the main macro by passing in an empty root attributes instead.

    let mut base_token_stream = Ts2::new();
    let root_attrs = match parse_root_attrs(attr) {
        Ok(root_attrs) => root_attrs,
        Err(e) => {
            // recover and use an empty root attributes
            e.to_compile_error().to_tokens(&mut base_token_stream);
            RootAttributes::default()
        }
    };

    // Try to generate the full metrics implementation
    match generate_metrics(root_attrs, input.clone()) {
        Ok(output) => output.to_tokens(&mut base_token_stream),
        Err(err) => {
            // Always generate the base struct without metrics attributes to avoid cascading errors
            clean_base_adt(&input).to_tokens(&mut base_token_stream);
            // Include the error and the base struct without metrics attributes
            err.to_compile_error().to_tokens(&mut base_token_stream);
        }
    };
    base_token_stream.into()
}

/// Generates aggregation support for metrics structs.
///
/// This macro enables combining multiple observations of the same metric into a single aggregated
/// entry. It must be placed before `#[metrics]` and generates:
/// - An `Aggregated{StructName}` struct with aggregated field types
/// - An `AggregateEntry` trait implementation for merging observations
///
/// For renaming fields and adding unit, `#[aggregate]` relies on the `#[metrics]` macro.
///
/// # Container Attributes
///
/// | Attribute | Type | Description | Example |
/// |-----------|------|-------------|---------|
/// | `direct` | Flag | Aggregates on the struct itself instead of the closed entry (default: aggregates on closed entry) | `#[aggregate(direct)]` |
///
/// # Field Attributes
///
/// | Attribute | Type | Description | Example |
/// |-----------|------|-------------|---------|
/// | `strategy` | Path | Specifies the aggregation strategy (required for non-key fields) | `#[aggregate(strategy = Histogram<Duration>)]` |
/// | `key` | Flag | Marks a field as part of the aggregation key - observations with different keys are aggregated separately | `#[aggregate(key)]` |
/// | `ignore` | Flag | Ignore a field during aggregation. The field will still be part of the non-aggregated metric entry unless also marked `#[metrics(ignore)`] |
///
/// # Aggregation Modes
///
/// ## Entry Mode (Default)
///
/// By default, `#[aggregate]` implements aggregation on the closed metric entry. This means
/// aggregation happens after `CloseValue` has been applied to all fields:
///
/// ```
/// use metrique::unit_of_work::metrics;
/// use metrique_aggregation::{aggregate, histogram::Histogram, value::Sum};
/// use std::time::Duration;
///
/// #[aggregate]
/// #[metrics]
/// struct ApiCall {
///     #[aggregate(strategy = Histogram<Duration>)]
///     #[metrics(unit = metrique::writer::unit::Millisecond)]
///     latency: Duration,  // Aggregates Duration values
///
///     #[aggregate(strategy = Sum)]
///     response_size: usize,
/// }
/// ```
///
/// ## Direct Mode
///
/// Use `#[aggregate(direct)]` to aggregate on the struct iteslf. In direct mode:
/// - Aggregation strategies receive the raw field type before `CloseValue` is applied
/// - Use this if the base struct is not also a metric
///
/// # Aggregation Keys
///
/// Fields marked with `#[aggregate(key)]` define the aggregation key. Observations with different
/// keys are aggregated into separate entries:
///
/// ```
/// use metrique::unit_of_work::metrics;
/// use metrique_aggregation::{aggregate, histogram::Histogram};
/// use std::time::Duration;
///
/// #[aggregate]
/// #[metrics]
/// struct ApiCall {
///     #[aggregate(key)]
///     endpoint: String,  // Separate aggregation per endpoint
///
///     #[aggregate(strategy = Histogram<Duration>)]
///     latency: Duration,
/// }
/// ```
///
/// Key behavior:
/// - Key fields are cloned into the aggregated struct unchanged
/// - Multiple key fields create a tuple key: `(Field1, Field2, ...)`
/// - Without key fields, all observations aggregate into a single entry
/// - Key fields must implement `Clone`
///
/// # Aggregation Strategies
///
/// Each non-key field must specify an aggregation strategy that implements `AggregateValue<T>`:
///
/// ## Built-in Strategies
///
/// - **`Sum`** - Sums numeric values together
/// - **`Histogram<T>`** - Collects values into a distribution. Histogram has a second generic that can control how values are stored. See the `Histogram` docs for more info.
/// - **`KeepLast`** - Keeps the most recent value
///
/// ```
/// use metrique::unit_of_work::metrics;
/// use metrique_aggregation::{aggregate, histogram::Histogram, value::Sum};
/// use std::time::Duration;
///
/// #[aggregate]
/// #[metrics]
/// struct ApiCall {
///     #[aggregate(strategy = Histogram<Duration>)]
///     latency: Duration,
///
///     #[aggregate(strategy = Sum)]
///     bytes_sent: usize,
/// }
/// ```
///
/// # Generated Types
///
/// For a struct with `#[aggregate]`, the macro generates:
/// - `AggregatedMyMetrics`: The aggregated struct where each field is replaced with its aggregated type
/// - `impl AggregateEntry for MyMetrics`: Trait implementation for merging observations
///
/// For more details on the aggregation trait system, see the
/// [traits module documentation](https://docs.rs/metrique-aggregation/latest/metrique_aggregation/traits/index.html).
///
/// The aggregated struct can be used with `Aggregate<T>` or `MutexSink<T>`:
///
/// ```
/// use metrique::unit_of_work::metrics;
/// use metrique_aggregation::{aggregate, histogram::Histogram, aggregator::Aggregate};
/// use std::time::Duration;
///
/// #[aggregate]
/// #[metrics]
/// struct ApiCall {
///     #[aggregate(strategy = Histogram<Duration>)]
///     latency: Duration,
/// }
///
/// #[metrics]
/// struct RequestMetrics {
///     request_id: String,
///     #[metrics(flatten)]
///     api_calls: Aggregate<ApiCall>,
/// }
/// ```
///
/// For more examples, see the `examples` directory in `metrique-aggregation`
#[proc_macro_attribute]
pub fn aggregate(attr: TokenStream, input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let attr_str = attr.to_string();
    let entry_mode = attr.is_empty() || attr_str.trim() != "direct";
    let enable_merge_ref = attr_str.contains("ref");

    let mut output = Ts2::new();

    // Try to generate struct, impl, MergeRef, and merge methods
    let struct_result = aggregate::generate_aggregated_struct(&input, entry_mode);
    let impl_result = aggregate::generate_aggregate_strategy_impl(&input, entry_mode);
    let merge_ref_result = aggregate::generate_merge_ref_impl(&input, entry_mode, enable_merge_ref);
    let merge_methods_result = aggregate::generate_merge_on_drop_methods(&input, entry_mode);

    match (
        struct_result,
        impl_result,
        merge_ref_result,
        merge_methods_result,
    ) {
        (Ok(aggregated_struct), Ok(aggregate_impl), Ok(merge_ref_impl), Ok(merge_methods)) => {
            aggregated_struct.to_tokens(&mut output);
            aggregate_impl.to_tokens(&mut output);
            if let Some(merge_ref) = merge_ref_impl {
                merge_ref.to_tokens(&mut output);
            }
            merge_methods.to_tokens(&mut output);
            aggregate::clean_aggregate_adt(&input).to_tokens(&mut output);
        }
        (Err(e), _, _, _) | (_, Err(e), _, _) | (_, _, Err(e), _) | (_, _, _, Err(e)) => {
            // On error, generate the base struct without aggregate attributes and include the error
            aggregate::clean_aggregate_adt(&input).to_tokens(&mut output);
            e.to_compile_error().to_tokens(&mut output);
        }
    }

    output.into()
}

#[derive(Copy, Clone, Debug)]
enum OwnershipKind {
    ByRef,
    ByValue,
}

#[derive(Debug, Default, FromMeta)]
// allow both `#[metric(value)]` and `#[metric(value(string))]` to be parsed
#[darling(from_word = Self::from_word)]
struct ValueAttributes {
    string: Flag,
}

impl ValueAttributes {
    /// constructor used in case of the `#[metric(value)]` form
    fn from_word() -> darling::Result<Self> {
        Ok(Self::default())
    }
}

/// Synthetic field using variant name.
#[derive(Debug, Clone)]
pub(crate) enum Tag {
    Inflectable { name: String, sample_group: bool },
    Exact { name: String, sample_group: bool },
}

impl Tag {
    /// Get the tag field name, applying inflection if using inflectable variant
    pub(crate) fn field_name(&self, root_attrs: &RootAttributes) -> String {
        match self {
            Tag::Inflectable { name, .. } => root_attrs
                .prefix
                .as_ref()
                .map(|p| p.apply(name, root_attrs.rename_all))
                .unwrap_or_else(|| root_attrs.rename_all.apply(name)),
            Tag::Exact { name, .. } => name.clone(),
        }
    }

    pub(crate) fn sample_group(&self) -> bool {
        match self {
            Tag::Inflectable { sample_group, .. } => *sample_group,
            Tag::Exact { sample_group, .. } => *sample_group,
        }
    }
}

#[derive(Debug, FromMeta)]
#[darling(and_then = Self::validate, from_word = Self::from_word)]
struct RawTag {
    #[darling(default)]
    name: Option<SpannedKv<String>>,
    #[darling(default)]
    name_exact: Option<SpannedKv<String>>,
    #[darling(default)]
    sample_group: Flag,
}

impl RawTag {
    fn from_word() -> darling::Result<Self> {
        Err(darling::Error::custom(
            "tag requires either name or name_exact parameter: #[metrics(tag(name = \"...\"))] or #[metrics(tag(name_exact = \"...\"))]",
        ))
    }

    fn validate(self) -> darling::Result<Self> {
        match (self.name, self.name_exact) {
            (None, None) => Err(darling::Error::custom(
                "tag requires either name or name_exact parameter: #[metrics(tag(name = \"...\"))] or #[metrics(tag(name_exact = \"...\"))]",
            )),
            (Some(_), Some(_)) => Err(darling::Error::custom(
                "tag cannot have both name and name_exact parameters",
            )),
            (Some(name), None) => Ok(Self {
                name: Some(validate_name(name)?),
                name_exact: None,
                sample_group: self.sample_group,
            }),
            (None, Some(name_exact)) => Ok(Self {
                name: None,
                name_exact: Some(validate_name(name_exact)?),
                sample_group: self.sample_group,
            }),
        }
    }
}

impl From<RawTag> for Tag {
    fn from(raw: RawTag) -> Self {
        let sample_group = raw.sample_group.is_present();
        match (raw.name, raw.name_exact) {
            (Some(name), None) => Tag::Inflectable {
                name: name.value,
                sample_group,
            },
            (None, Some(name)) => Tag::Exact {
                name: name.value,
                sample_group,
            },
            _ => unreachable!("validated in RawTag::validate"),
        }
    }
}

#[derive(Debug, Default, FromMeta)]
struct RawRootAttributes {
    prefix: Option<SpannedKv<String>>,
    exact_prefix: Option<SpannedKv<String>>,

    #[darling(default)]
    rename_all: NameStyle,

    #[darling(rename = "emf::dimension_sets")]
    emf_dimensions: Option<DimensionSets>,

    tag: Option<SpannedValue<RawTag>>,

    subfield: Flag,
    #[darling(rename = "subfield_owned")]
    subfield_owned: Flag,
    #[darling(rename = "sample_group")]
    sample_group: Flag,
    value: Option<ValueAttributes>,
}

#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
enum MetricMode {
    #[default]
    RootEntry,
    Subfield,
    SubfieldOwned,
    Value,
    ValueString,
}

#[derive(Debug, Default)]
struct RootAttributes {
    prefix: Option<Prefix>,

    rename_all: NameStyle,

    emf_dimensions: Option<DimensionSets>,

    tag: Option<Tag>,

    sample_group: bool,

    mode: MetricMode,
}

impl RawRootAttributes {
    fn validate(self) -> darling::Result<RootAttributes> {
        let mut out: Option<(MetricMode, &'static str)> = None;
        if let Some(value_attrs) = self.value {
            if value_attrs.string.is_present() {
                out = set_exclusive(
                    |_| MetricMode::ValueString,
                    "value",
                    out,
                    &value_attrs.string,
                )?
            } else {
                out = Some((MetricMode::Value, "value"));
            }
        }
        out = set_exclusive(|_| MetricMode::Subfield, "subfield", out, &self.subfield)?;
        out = set_exclusive(
            |_| MetricMode::SubfieldOwned,
            "subfield_owned",
            out,
            &self.subfield_owned,
        )?;
        let mut mode = out.map(|(s, _)| s).unwrap_or_default();
        let sample_group = if self.sample_group.is_present() {
            if let MetricMode::Value = &mut mode {
                true
            } else {
                return Err(darling::Error::custom(
                    "`sample_group` as a top-level attribute can only be used with #[metrics(value)]",
                )
                .with_span(&self.sample_group.span()));
            }
        } else {
            false
        };
        if let (MetricMode::ValueString, Some(ds)) = (mode, &self.emf_dimensions) {
            return Err(
                darling::Error::custom("value does not make sense with dimension-sets")
                    .with_span(&ds.span()),
            );
        }
        let tag = self
            .tag
            .map(|tag| match &mode {
                MetricMode::RootEntry | MetricMode::Subfield | MetricMode::SubfieldOwned => {
                    Ok(tag.into_inner().into())
                }
                MetricMode::Value | MetricMode::ValueString => Err(darling::Error::custom(
                    "value and value(string) do not support tag",
                )
                .with_span(&tag.span())),
            })
            .transpose()?;

        Ok(RootAttributes {
            prefix: Prefix::from_inflectable_and_exact(
                &self.prefix,
                &self.exact_prefix,
                PrefixLevel::Root,
            )?
            .map(SpannedValue::into_inner),
            rename_all: self.rename_all,
            emf_dimensions: self.emf_dimensions,
            tag,
            sample_group,
            mode,
        })
    }
}

impl RootAttributes {
    fn configuration_field_names(&self) -> Vec<Ts2> {
        if let Some(_dims) = &self.emf_dimensions {
            vec![quote! { __config__ }]
        } else {
            vec![]
        }
    }

    fn configuration_fields(&self) -> Vec<Ts2> {
        let mut fields = vec![];
        if let Some(_dims) = &self.emf_dimensions {
            fields.push(quote! {
                __config__: ::metrique::emf::SetEntryDimensions
            })
        }
        fields
    }

    fn create_configuration(&self) -> Vec<Ts2> {
        let mut fields = vec![];
        if let Some(dims) = &self.emf_dimensions {
            fields
                .push(quote! { __config__: ::metrique::__plumbing_entry_dimensions!(dims: #dims) })
        }
        fields
    }

    fn ownership_kind(&self) -> OwnershipKind {
        match self.mode {
            MetricMode::RootEntry | MetricMode::SubfieldOwned => OwnershipKind::ByValue,
            MetricMode::Subfield | MetricMode::ValueString | MetricMode::Value => {
                OwnershipKind::ByRef
            }
        }
    }

    fn warnings(&self) -> Ts2 {
        quote! {}
    }
}

#[derive(Debug, FromField)]
#[darling(attributes(metrics))]
struct RawMetricsFieldAttrs {
    flatten: Flag,

    flatten_entry: Flag,

    no_close: Flag,

    timestamp: Flag,

    sample_group: Flag,

    ignore: Flag,

    #[darling(default)]
    unit: Option<SpannedKv<syn::Path>>,

    #[darling(default)]
    format: Option<SpannedKv<syn::Path>>,

    #[darling(default)]
    name: Option<SpannedKv<String>>,

    #[darling(default)]
    prefix: Option<SpannedKv<String>>,

    #[darling(default)]
    exact_prefix: Option<SpannedKv<String>>,
}

/// Wrapper type to allow recovering both the key and value span when parsing an attribute
#[derive(Debug)]
pub(crate) struct SpannedKv<T> {
    pub(crate) key_span: Span,
    #[allow(dead_code)]
    pub(crate) value_span: Span,
    pub(crate) value: T,
}

impl<T: FromMeta> FromMeta for SpannedKv<T> {
    fn from_meta(item: &syn::Meta) -> darling::Result<Self> {
        let value = T::from_meta(item).map_err(|e| e.with_span(item))?;
        let (key_span, value_span) = match item {
            syn::Meta::NameValue(nv) => (nv.path.span(), nv.value.span()),
            _ => return Err(darling::Error::custom("expected a key value pair").with_span(item)),
        };

        Ok(SpannedKv {
            key_span,
            value_span,
            value,
        })
    }
}

pub(crate) fn parse_metric_fields(
    fields: &syn::punctuated::Punctuated<syn::Field, syn::token::Comma>,
) -> Result<Vec<MetricsField>> {
    let mut parsed_fields = vec![];
    let mut errors = darling::Error::accumulator();

    for (i, field) in fields.iter().enumerate() {
        let i = syn::Index::from(i);
        let (ident, name, span) = match &field.ident {
            Some(ident) => (quote! { #ident }, Some(ident.to_string()), ident.span()),
            None => (quote! { #i }, None, field.ty.span()),
        };

        let attrs = match errors
            .handle(RawMetricsFieldAttrs::from_field(field).and_then(|attr| attr.validate()))
        {
            Some(attrs) => attrs,
            None => {
                continue;
            }
        };

        parsed_fields.push(MetricsField {
            ident,
            name,
            span,
            ty: field.ty.clone(),
            vis: field.vis.clone(),
            external_attrs: clean_attrs(&field.attrs),
            attrs,
        });
    }

    errors.finish()?;

    Ok(parsed_fields)
}

fn cannot_combine_error(existing: &str, new: &str, new_span: Span) -> darling::Error {
    darling::Error::custom(format!("Cannot combine `{existing}` with `{new}`")).with_span(&new_span)
}

// Set metrics to `new`, enforcing the fact that this field is exclusive and cannot be combined
fn set_exclusive<T>(
    new: impl Fn(Span) -> T,
    name: &'static str,
    existing: Option<(T, &'static str)>,
    flag: &Flag,
) -> darling::Result<Option<(T, &'static str)>> {
    match (flag.is_present(), &existing) {
        (true, Some((_, other))) => Err(cannot_combine_error(other, name, flag.span())),
        (true, None) => Ok(Some((new(flag.span()), name))),
        _ => Ok(existing),
    }
}

// retrieve the value for a field, enforcing the fact that unit/name cannot be combined with other options
fn get_field_option<'a, T>(
    field_name: &'static str,
    existing: &Option<(MetricsFieldKind, &'static str)>,
    span: &'a Option<SpannedKv<T>>,
) -> darling::Result<Option<&'a T>> {
    match (span, &existing) {
        (Some(input), Some((_, other))) => {
            Err(cannot_combine_error(other, field_name, input.key_span))
        }
        (Some(v), None) => Ok(Some(&v.value)),
        _ => Ok(None),
    }
}

// retrieve the value for a flag that requires a value to be a field
fn get_field_flag(
    field_name: &'static str,
    existing: &Option<(MetricsFieldKind, &'static str)>,
    flag: &Flag,
) -> darling::Result<Option<Span>> {
    match (flag.is_present(), &existing) {
        (true, Some((_, other))) => Err(cannot_combine_error(other, field_name, flag.span())),
        (true, None) => Ok(Some(flag.span())),
        _ => Ok(None),
    }
}

impl RawMetricsFieldAttrs {
    fn validate(self) -> darling::Result<MetricsFieldAttrs> {
        let mut out: Option<(MetricsFieldKind, &'static str)> = None;
        out = set_exclusive(
            |span| MetricsFieldKind::Flatten { span, prefix: None },
            "flatten",
            out,
            &self.flatten,
        )?;
        out = set_exclusive(
            MetricsFieldKind::FlattenEntry,
            "flatten_entry",
            out,
            &self.flatten_entry,
        )?;
        out = set_exclusive(
            MetricsFieldKind::Timestamp,
            "timestamp",
            out,
            &self.timestamp,
        )?;
        out = set_exclusive(MetricsFieldKind::Ignore, "ignore", out, &self.ignore)?;

        let name = self.name.map(validate_name).transpose()?;
        let name = get_field_option("name", &out, &name)?;
        let unit = get_field_option("unit", &out, &self.unit)?;
        let format = get_field_option("format", &out, &self.format)?;
        let sample_group = get_field_flag("sample_group", &out, &self.sample_group)?;
        let close = !self.no_close.is_present();
        if let (false, Some((MetricsFieldKind::Ignore(span), _))) = (close, &out) {
            return Err(cannot_combine_error("no_close", "ignore", *span));
        }

        let prefix = Prefix::from_inflectable_and_exact(
            &self.prefix,
            &self.exact_prefix,
            PrefixLevel::Field,
        )?;
        if let Some(prefix_) = prefix {
            match &mut out {
                Some((MetricsFieldKind::Flatten { prefix, .. }, _)) => {
                    *prefix = Some(prefix_.into_inner());
                }
                _ => {
                    return Err(
                        darling::Error::custom("prefix can only be used with `flatten`")
                            .with_span(&prefix_.span()),
                    );
                }
            }
        }

        Ok(MetricsFieldAttrs {
            close,
            kind: match out {
                Some((out, _)) => out,
                None => MetricsFieldKind::Field {
                    sample_group,
                    name: name.cloned(),
                    unit: unit.cloned(),
                    format: format.cloned(),
                },
            },
        })
    }
}

fn validate_name(name: SpannedKv<String>) -> darling::Result<SpannedKv<String>> {
    match validate_name_inner(&name.value) {
        Ok(_) => Ok(name),
        Err(msg) => Err(darling::Error::custom(msg).with_span(&name.value_span)),
    }
}

fn validate_name_inner(name: &str) -> std::result::Result<(), &'static str> {
    if name.is_empty() {
        return Err("invalid name: name field must not be empty");
    }

    if name.contains(' ') {
        return Err("invalid name: name must not contain spaces");
    }
    Ok(())
}

#[derive(Debug, Clone)]
struct MetricsFieldAttrs {
    close: bool,
    kind: MetricsFieldKind,
}

pub(crate) struct MetricsField {
    pub(crate) vis: Visibility,
    pub(crate) ident: Ts2,
    pub(crate) name: Option<String>,
    pub(crate) span: Span,
    pub(crate) ty: Type,
    pub(crate) external_attrs: Vec<Attribute>,
    pub(crate) attrs: MetricsFieldAttrs,
}

impl MetricsField {
    fn core_field(&self, is_named: bool) -> Ts2 {
        let MetricsField {
            ref external_attrs,
            ref ident,
            ref ty,
            ref vis,
            ..
        } = *self;
        let field = if is_named {
            quote! { #ident: #ty }
        } else {
            quote! { #ty }
        };
        quote! { #(#external_attrs)* #vis #field }
    }

    fn entry_field(&self, named: bool) -> Option<Ts2> {
        if let MetricsFieldKind::Ignore(_span) = self.attrs.kind {
            return None;
        }
        let MetricsField {
            ident, ty, span, ..
        } = self;
        let mut base_type = if self.attrs.close {
            quote_spanned! { *span=> <#ty as metrique::CloseValue>::Closed }
        } else {
            quote_spanned! { *span=>#ty }
        };
        if let Some(expr) = self.unit() {
            base_type = quote_spanned! { expr.span()=>
                <#base_type as ::metrique::unit::AttachUnit>::Output<#expr>
            }
        }
        let inner = if named {
            quote! { #ident: #base_type }
        } else {
            quote! { #base_type }
        };
        Some(quote_spanned! { *span=>
                #[deprecated(note = "these fields will become private in a future release. To introspect an entry, use `metrique::writer::test_util::test_entry`")]
                #[doc(hidden)]
                #inner
        })
    }

    fn unit(&self) -> Option<&syn::Path> {
        match &self.attrs.kind {
            MetricsFieldKind::Field { unit, .. } => unit.as_ref(),
            _ => None,
        }
    }

    pub(crate) fn close_value(&self, ownership_kind: OwnershipKind) -> Ts2 {
        let ident = &self.ident;
        let span = self.span;
        let field_expr = match ownership_kind {
            OwnershipKind::ByValue => quote_spanned! {span=> self.#ident },
            OwnershipKind::ByRef => quote_spanned! {span=> &self.#ident },
        };
        self.close_field_expr(field_expr)
    }

    pub(crate) fn close_field_expr(&self, field_expr: Ts2) -> Ts2 {
        let ident = &self.ident;
        let span = self.span;
        let base = if self.attrs.close {
            quote_spanned! {span=> metrique::CloseValue::close(#field_expr) }
        } else {
            field_expr
        };

        let base = if let Some(unit) = self.unit() {
            quote_spanned! { unit.span() =>
                #base.into()
            }
        } else {
            base
        };

        quote! { #ident: #base }
    }
}

pub(crate) struct TupleData {
    pub(crate) ty: syn::Type,
    pub(crate) kind: MetricsFieldKind,
    pub(crate) close: bool,
}

/// Generate the entry type for a field/variant, optionally closing it
pub(crate) fn entry_type(ty: &syn::Type, close: bool, span: proc_macro2::Span) -> Ts2 {
    if close {
        quote::quote_spanned! { span=> <#ty as metrique::CloseValue>::Closed }
    } else {
        quote::quote_spanned! { span=> #ty }
    }
}

pub(crate) enum PrefixLevel {
    Root,
    Field,
}

#[derive(Debug, Clone)]
pub(crate) enum Prefix {
    Inflectable { prefix: String },
    Exact(String),
}

impl Prefix {
    /// Apply prefix to base name and inflect according to name_style
    pub(crate) fn apply(&self, base: &str, name_style: NameStyle) -> String {
        match self {
            Prefix::Exact(exact_prefix) => {
                format!("{}{}", exact_prefix, name_style.apply(base))
            }
            Prefix::Inflectable { prefix } => {
                let prefixed = format!("{}{}", prefix, base);
                name_style.apply(&prefixed)
            }
        }
    }

    fn inflected_prefix_message(prefix: &str, c: char) -> String {
        let warning_text = if name_contains_dot(prefix) {
            " '.' used to be allowed in `prefix` but is now forbidden."
        } else {
            ""
        };
        let prefix_fixed: String = prefix
            .chars()
            .map(|c| if !c.is_alphanumeric() { '-' } else { c })
            .collect();
        format!(
            "You cannot use the character {c:?} with `prefix`. `prefix` will \"inflect\" to match the name scheme specified by `rename_all`. For example, \
            it will change all delimiters to `-` for kebab case). If you want to match namestyle, use `prefix = {prefix_fixed:?}`. If you want to preserve {c:?} \
            in the final metric name use `exact_prefix = {prefix:?}.{warning_text}"
        )
    }

    fn prefix_should_end_with_delimiter_message(prefix: &str) -> String {
        let delimiter = if prefix.contains('-') { '-' } else { '_' };
        let prefix_fixed = format!("{prefix}{delimiter}");
        format!(
            "The root-level prefix `{prefix:?}` must end with a delimiter. Use `prefix = {prefix_fixed:?}`, which inflects \
            correctly in all inflections"
        )
    }

    fn from_inflectable_and_exact(
        inflectable: &Option<SpannedKv<String>>,
        exact: &Option<SpannedKv<String>>,
        level: PrefixLevel,
    ) -> darling::Result<Option<SpannedValue<Self>>> {
        match (inflectable, exact) {
            (Some(prefix), None) => {
                if let Some(c) = name_contains_uninflectables(&prefix.value) {
                    Err(
                        darling::Error::custom(Self::inflected_prefix_message(&prefix.value, c))
                            .with_span(&prefix.key_span),
                    )
                } else if let PrefixLevel::Root = level
                    && !name_ends_with_delimiter(&prefix.value)
                {
                    Err(
                        darling::Error::custom(Self::prefix_should_end_with_delimiter_message(
                            &prefix.value,
                        ))
                        .with_span(&prefix.key_span),
                    )
                } else {
                    Ok(Some(SpannedValue::new(
                        Self::Inflectable {
                            prefix: prefix.value.clone(),
                        },
                        prefix.key_span,
                    )))
                }
            }
            (None, Some(p)) => Ok(Some(SpannedValue::new(
                Prefix::Exact(p.value.clone()),
                p.key_span,
            ))),
            (None, None) => Ok(None),
            (Some(inflectable), Some(_)) => Err(cannot_combine_error(
                "prefix",
                "exact_prefix",
                inflectable.key_span,
            )),
        }
    }

    /// Append this prefix to the namespace's prefix chain.
    /// The prefix will be prepended to metric names when they are written.
    /// Returns (extra, namespace_with_prefix).
    pub(crate) fn append_to(
        &self,
        ns: &proc_macro2::TokenStream,
        span: proc_macro2::Span,
    ) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
        match self {
            Prefix::Inflectable { prefix } => {
                crate::entry_impl::make_inflect_prefix(ns, prefix, span)
            }
            Prefix::Exact(exact_prefix) => {
                crate::entry_impl::make_exact_prefix(ns, exact_prefix, span)
            }
        }
    }
}

#[derive(Debug, Clone)]
enum MetricsFieldKind {
    Ignore(Span),
    Flatten {
        span: Span,
        prefix: Option<Prefix>,
    },
    FlattenEntry(Span),
    Timestamp(Span),
    Field {
        unit: Option<syn::Path>,
        name: Option<String>,
        format: Option<syn::Path>,
        sample_group: Option<Span>,
    },
}

// produce a warning that the user can see
//
// currently, we do not have any logic that produces warnings, but leave this
// in for the next time
#[allow(unused)]
fn proc_macro_warning(span: Span, warning: &str) -> Ts2 {
    quote_spanned! {span=>
        const _: () = {
            #[deprecated(note=#warning)]
            const _W: () = ();
            _W
        };
    }
}

fn parse_root_attrs(attr: TokenStream) -> Result<RootAttributes> {
    let nested_meta = NestedMeta::parse_meta_list(attr.into())?;
    Ok(RawRootAttributes::from_list(&nested_meta)?.validate()?)
}

fn generate_metrics(root_attributes: RootAttributes, input: DeriveInput) -> Result<Ts2> {
    // Check if #[aggregate] attribute is present
    if input
        .attrs
        .iter()
        .any(|attr| attr.path().is_ident("aggregate"))
    {
        return Err(Error::new_spanned(
            &input,
            "#[aggregate] must be placed before #[metrics], not after",
        ));
    }

    let output = match root_attributes.mode {
        MetricMode::RootEntry | MetricMode::Subfield | MetricMode::SubfieldOwned => {
            match &input.data {
                Data::Struct(data_struct) => {
                    if root_attributes.tag.is_some() {
                        return Err(Error::new_spanned(
                            &input,
                            "`tag` attribute is only supported on entry enums",
                        ));
                    }
                    let fields = match &data_struct.fields {
                        Fields::Named(fields_named) => &fields_named.named,
                        _ => {
                            return Err(Error::new_spanned(
                                &input,
                                "Only named fields are supported",
                            ));
                        }
                    };
                    structs::generate_metrics_for_struct(root_attributes, &input, fields)?
                }
                Data::Enum(data_enum) => {
                    let variants =
                        enums::parse_enum_variants(&data_enum.variants, enums::VariantMode::Entry)?;
                    enums::generate_metrics_for_enum(root_attributes, &input, &variants)?
                }
                Data::Union(_) => {
                    return Err(Error::new_spanned(
                        &input,
                        "Only structs and enums are supported for entries",
                    ));
                }
            }
        }
        MetricMode::Value => match &input.data {
            Data::Struct(data_struct) => {
                let fields = match &data_struct.fields {
                    Fields::Named(fields_named) => &fields_named.named,
                    Fields::Unnamed(fields_unnamed) => &fields_unnamed.unnamed,
                    _ => {
                        return Err(Error::new_spanned(
                            &input,
                            "Only named fields are supported",
                        ));
                    }
                };
                structs::generate_metrics_for_struct(root_attributes, &input, fields)?
            }
            _ => {
                return Err(Error::new_spanned(
                    &input,
                    "Only structs are supported with value, use value(string) with enums",
                ));
            }
        },
        MetricMode::ValueString => {
            let variants = match &input.data {
                Data::Enum(data_enum) => &data_enum.variants,
                _ => {
                    return Err(Error::new_spanned(
                        &input,
                        "Only enums are supported with value(string)",
                    ));
                }
            };
            let variants = enums::parse_enum_variants(variants, enums::VariantMode::ValueString)?;
            enums::generate_metrics_for_enum(root_attributes, &input, &variants)?
        }
    };

    if std::env::var("MACRO_DEBUG").is_ok() {
        eprintln!("{}", &output);
    }

    Ok(output)
}

/// Generates `Ident<'static, 'static, T, N, ...>` with all lifetimes replaced by 'static
fn with_static_lifetimes(ident: &Ident, generics: &Generics) -> Ts2 {
    if generics.params.is_empty() {
        return quote! { #ident };
    }

    let args = generics.params.iter().map(|param| match param {
        GenericParam::Lifetime(_) => quote! { 'static },
        GenericParam::Type(ty) => {
            let ident = &ty.ident;
            quote! { #ident }
        }
        GenericParam::Const(c) => {
            let ident = &c.ident;
            quote! { #ident }
        }
    });

    quote! { #ident<#(#args),*> }
}

/// Generate the on_drop_wrapper implementation
pub(crate) fn generate_on_drop_wrapper(
    vis: &Visibility,
    guard: &Ident,
    inner: &Ident,
    target: &Ident,
    handle: &Ident,
    generics: &Generics,
) -> Ts2 {
    let inner_str = inner.to_string();
    let guard_str = guard.to_string();

    let (_impl_generics, _, where_clause) = generics.split_for_impl();
    let inner_static = with_static_lifetimes(inner, generics);
    let target_static = with_static_lifetimes(target, generics);

    quote! {
        #[doc = concat!("Metrics guard returned from [`", #inner_str, "::append_on_drop`], closes the entry and appends the metrics to a sink when dropped.")]
        #vis type #guard<Q = ::metrique::DefaultSink> = ::metrique::AppendAndCloseOnDrop<#inner_static, Q>;

        #[doc = concat!("Metrics handle returned from [`", #guard_str, "::handle`], similar to an `Arc<", #guard_str, ">`.")]
        #vis type #handle<Q = ::metrique::DefaultSink> = ::metrique::AppendAndCloseOnDropHandle<#inner_static, Q>;

        impl #inner_static #where_clause {
            #[doc = "Creates an AppendAndCloseOnDrop that will be automatically appended to `sink` on drop."]
            #vis fn append_on_drop<Q: ::metrique::writer::EntrySink<::metrique::RootEntry<#target_static>> + Send + Sync + 'static>(self, sink: Q) -> #guard<Q> {
                ::metrique::append_and_close(self, sink)
            }
        }
    }
}

fn generate_close_value_impls(
    root_attrs: &RootAttributes,
    base_ty: &Ident,
    closed_ty: &Ident,
    generics: &syn::Generics,
    impl_body: Ts2,
) -> Ts2 {
    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();

    let (metrics_struct_ty, proxy_impl) = match root_attrs.ownership_kind() {
        OwnershipKind::ByValue => (quote!(#base_ty #ty_generics), quote!()),
        OwnershipKind::ByRef => (
            quote!(&'_ #base_ty #ty_generics),
            // for a by-ref ownership, also add a proxy impl for by-value
            quote!(impl #impl_generics metrique::CloseValue for #base_ty #ty_generics #where_clause {
                type Closed = #closed_ty #ty_generics;
                fn close(self) -> Self::Closed {
                    <&Self>::close(&self)
                }
            }),
        ),
    };
    quote! {
        impl #impl_generics metrique::CloseValue for #metrics_struct_ty #where_clause {
            type Closed = #closed_ty #ty_generics;
            fn close(self) -> Self::Closed {
                #impl_body
            }
        }

        #proxy_impl
    }
}

pub(crate) fn clean_attrs(attr: &[Attribute]) -> Vec<Attribute> {
    attr.iter()
        .filter(|attr| !attr.path().is_ident("metrics"))
        .cloned()
        .collect()
}

/// Minimal passthrough that strips #[metrics] attributes from struct fields.
///
/// If the proc macro fails, then absent anything else, the struct provider by the user will
/// not exist in code. This ensures that even if the proc macro errors, the struct will still be present
/// making finding the actual cause of the compiler errors much easier.
///
/// This function is not used in the happy path case, but if we encounter errors in the
/// main pass, this is returned along with the compiler error to remove spurious compiler
/// failures.
fn clean_base_adt(input: &DeriveInput) -> Ts2 {
    let adt_name = &input.ident;
    let vis = &input.vis;
    let generics = &input.generics;

    // Filter out any #[metrics] attributes from the struct
    let filtered_attrs = clean_attrs(&input.attrs);
    match &input.data {
        Data::Struct(data_struct) => match &data_struct.fields {
            Fields::Named(fields_named) => {
                structs::clean_base_struct(vis, adt_name, generics, filtered_attrs, fields_named)
            }
            Fields::Unnamed(fields_unnamed) => structs::clean_base_unnamed_struct(
                vis,
                adt_name,
                generics,
                filtered_attrs,
                fields_unnamed,
            ),
            // In these cases, we can't strip attributes since we don't support this format.
            // Echo back exactly what was given.
            _ => input.to_token_stream(),
        },
        Data::Enum(data_enum) => {
            if let Ok(variants) = enums::parse_enum_variants(
                &data_enum.variants,
                enums::VariantMode::SkipAttributeParsing,
            ) {
                enums::generate_base_enum(adt_name, vis, generics, &filtered_attrs, &variants)
            } else {
                input.to_token_stream()
            }
        }
        _ => input.to_token_stream(),
    }
}

#[cfg(test)]
mod tests {
    use darling::FromMeta;
    use insta::assert_snapshot;
    use proc_macro2::TokenStream as Ts2;
    use quote::quote;
    use syn::{parse_quote, parse2};

    use crate::RawRootAttributes;

    // Helper function to convert proc_macro::TokenStream to proc_macro2::TokenStream
    // This allows us to test the macro without needing to use the proc_macro API directly
    fn metrics_impl(input: Ts2, attrs: Ts2) -> Ts2 {
        let input = syn::parse2(input).unwrap();
        let meta: syn::Meta = syn::parse2(attrs).unwrap();
        let root_attrs = RawRootAttributes::from_meta(&meta)
            .unwrap()
            .validate()
            .unwrap();
        super::generate_metrics(root_attrs, input).unwrap()
    }

    fn metrics_impl_string(input: Ts2, attrs: Ts2) -> String {
        let output = metrics_impl(input, attrs);

        // Parse the output back into a syn::File for pretty printing
        match parse2::<syn::File>(output.clone()) {
            Ok(file) => prettyplease::unparse(&file),
            Err(_) => {
                // If parsing fails, print the error and use the raw string output
                output.to_string()
            }
        }
    }

    #[test]
    fn test_darling_root_attrs() {
        use darling::FromMeta;
        RawRootAttributes::from_meta(&parse_quote! {
            metrics(
                rename_all = "PascalCase",
                emf::dimension_sets = [["bar"]]
            )
        })
        .unwrap()
        .validate()
        .unwrap();
    }

    #[test]
    fn test_simple_metrics_struct() {
        let input = quote! {
            struct RequestMetrics {
                operation: &'static str,
                number_of_ducks: usize
            }
        };

        let parsed_file = metrics_impl_string(input, quote!(metrics()));
        assert_snapshot!("simple_metrics_struct", parsed_file);
    }

    #[test]
    fn test_sample_group_metrics_struct() {
        let input = quote! {
            struct RequestMetrics {
                #[metrics(sample_group)]
                operation: &'static str,
                number_of_ducks: usize
            }
        };

        let parsed_file = metrics_impl_string(input, quote!(metrics()));
        assert_snapshot!("sample_group_metrics_struct", parsed_file);
    }

    #[test]
    fn test_simple_metrics_value_struct() {
        let input = quote! {
            struct RequestValue {
                #[metrics(ignore)]
                ignore: u32,
                value: u32,
            }
        };

        let parsed_file = metrics_impl_string(input, quote!(metrics(value)));
        assert_snapshot!("simple_metrics_value_struct", parsed_file);
    }

    #[test]
    fn test_sample_group_metrics_value_struct() {
        let input = quote! {
            struct RequestValue {
                #[metrics(ignore)]
                ignore: u32,
                value: &'static str,
            }
        };

        let parsed_file = metrics_impl_string(input, quote!(metrics(value, sample_group)));
        assert_snapshot!("sample_group_metrics_value_struct", parsed_file);
    }

    #[test]
    fn test_simple_metrics_value_unnamed_struct() {
        let input = quote! {
            struct RequestValue(
                #[metrics(ignore)]
                u32,
                u32);
        };

        let parsed_file = metrics_impl_string(input, quote!(metrics(value)));
        assert_snapshot!("simple_metrics_value_unnamed_struct", parsed_file);
    }

    #[test]
    fn test_simple_metrics_enum() {
        let input = quote! {
            enum Foo {
                Bar
            }
        };

        let parsed_file = metrics_impl_string(input, quote!(metrics(value(string))));
        assert_snapshot!("simple_metrics_enum", parsed_file);
    }

    #[test]
    fn test_exact_prefix_struct() {
        let input = quote! {
            struct RequestMetrics {
                operation: &'static str,
                number_of_ducks: usize
            }
        };

        let parsed_file = metrics_impl_string(input, quote!(metrics(exact_prefix = "API@")));
        assert_snapshot!("exact_prefix_struct", parsed_file);
    }

    #[test]
    fn test_field_exact_prefix_struct() {
        let input = quote! {
            struct RequestMetrics {
                #[metrics(flatten, exact_prefix = "API@")]
                nested: NestedMetrics,
                operation: &'static str
            }
        };

        let parsed_file = metrics_impl_string(input, quote!(metrics()));
        assert_snapshot!("field_exact_prefix_struct", parsed_file);
    }

    #[test]
    fn test_aggregate_after_metrics_error() {
        let input = quote! {
            #[metrics]
            #[aggregate]
            struct ApiCall {
                latency: Duration,
            }
        };

        let input = syn::parse2(input).unwrap();
        let root_attrs = RawRootAttributes::from_meta(&parse_quote!(metrics()))
            .unwrap()
            .validate()
            .unwrap();
        let result = super::generate_metrics(root_attrs, input);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.to_string()
                .contains("#[aggregate] must be placed before #[metrics]")
        );
    }

    #[test]
    fn test_metrics_with_lifetime() {
        let input = quote! {
            struct Foo<'a> {
                a: &'a str,
                b: usize
            }
        };

        let parsed_file = metrics_impl_string(input, quote!(metrics()));
        assert_snapshot!("metrics_with_lifetime", parsed_file);
    }

    #[test]
    fn test_metrics_with_cow_lifetime() {
        let input = quote! {
            struct Foo<'a> {
                a: Cow<'a, str>,
                b: usize
            }
        };

        let parsed_file = metrics_impl_string(input, quote!(metrics()));
        assert_snapshot!("metrics_with_cow_lifetime", parsed_file);
    }

    #[test]
    fn test_field_inflectable_prefix_struct() {
        let input = quote! {
            struct RequestMetrics {
                #[metrics(flatten, prefix = "api_")]
                nested: NestedMetrics,
                operation: &'static str
            }
        };

        let parsed_file = metrics_impl_string(input, quote!(metrics()));
        assert_snapshot!("field_inflectable_prefix_struct", parsed_file);
    }

    #[test]
    fn test_entry_enum() {
        let nested = metrics_impl_string(
            quote! {
                #[metrics(subfield)]
                struct Nested {
                    value: u32,
                }
            },
            quote!(metrics(subfield)),
        );
        let status = metrics_impl_string(
            quote! {
                #[metrics(subfield)]
                enum Status {
                    Active {
                        count: u32,
                        #[metrics(unit = metrique::writer::unit::Millisecond)]
                        latency: u64,
                    },
                    Pending(#[metrics(flatten)] Nested),
                    Multi(
                        #[metrics(flatten)] Nested,
                        #[metrics(ignore)] u32,
                    ),
                }
            },
            quote!(metrics(subfield)),
        );
        let root = metrics_impl_string(
            quote! {
                enum Operation {
                    Read { bytes: u64 },
                    Write(#[metrics(flatten)] Nested),
                }
            },
            quote!(metrics()),
        );

        let parsed_file = format!("{}\n{}\n{}", nested, status, root);
        assert_snapshot!("entry_enum", parsed_file);
    }

    #[test]
    fn test_subfield_struct() {
        let input = quote! {
            #[metrics(subfield)]
            struct NestedMetrics {
                counter: u32,
            }
        };

        let parsed_file = metrics_impl_string(input, quote!(metrics(subfield)));
        assert_snapshot!("subfield_struct", parsed_file);
    }

    #[test]
    fn test_sample_group_entry_enum() {
        let operation = metrics_impl_string(
            quote! {
                #[metrics(value(string))]
                enum Operation {
                    Read,
                    Write,
                }
            },
            quote!(metrics(value(string))),
        );
        let metadata = metrics_impl_string(
            quote! {
                #[metrics(subfield)]
                struct Metadata {
                    #[metrics(sample_group)]
                    operation: Operation,
                    request_id: String,
                }
            },
            quote!(metrics(subfield)),
        );
        let result = metrics_impl_string(
            quote! {
                enum RequestResult {
                    Success {
                        #[metrics(sample_group)]
                        operation: Operation,
                        bytes: usize,
                    },
                    Error {
                        #[metrics(sample_group)]
                        operation: Operation,
                        error_code: u32,
                    },
                    Timeout(#[metrics(flatten)] Metadata),
                    Cancelled(
                        #[metrics(flatten)] Metadata,
                        #[metrics(flatten_entry, no_close)] StatusEntry
                    ),
                }
            },
            quote!(metrics()),
        );

        let parsed_file = format!("{}\n{}\n{}", operation, metadata, result);
        assert_snapshot!("sample_group_entry_enum", parsed_file);
    }

    #[test]
    fn test_entry_enum_tag() {
        let nested = metrics_impl_string(
            quote! {
                #[metrics(subfield)]
                struct Nested {
                    value: u32,
                }
            },
            quote!(metrics(subfield)),
        );
        let root = metrics_impl_string(
            quote! {
                #[metrics(tag(name = "operation"))]
                enum Operation {
                    Read { bytes: usize },
                    Write(#[metrics(flatten)] Nested),
                }
            },
            quote!(metrics(tag(name = "operation"))),
        );

        let parsed_file = format!("{}\n{}", nested, root);
        assert_snapshot!("entry_enum_tag", parsed_file);
    }

    #[test]
    fn test_entry_enum_tag_with_sample_group() {
        let root = metrics_impl_string(
            quote! {
                #[metrics(tag(name = "operation", sample_group))]
                enum Operation {
                    Read { bytes: usize },
                }
            },
            quote!(metrics(tag(name = "operation", sample_group))),
        );

        assert_snapshot!("entry_enum_tag_sample_group", root);
    }

    #[test]
    fn test_debug_derive_passthrough_struct() {
        let input = quote! {
            #[derive(Debug, Clone)]
            struct Metrics {
                field: usize,
            }
        };

        let parsed_file = metrics_impl_string(input, quote!(metrics()));
        assert_snapshot!("debug_derive_passthrough_struct", parsed_file);
    }

    #[test]
    fn test_debug_derive_passthrough_enum() {
        let input = quote! {
            #[derive(Debug)]
            enum Operation {
                Read,
                Write,
            }
        };

        let parsed_file = metrics_impl_string(input, quote!(metrics(value(string))));
        assert_snapshot!("debug_derive_passthrough_enum", parsed_file);
    }
}