facet-xml 0.44.0

XML serialization for facet using the new format architecture - successor to facet-xml
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
//! Tests for format-specific proxy attributes in XML.
//!
//! This tests the `#[facet(xml::proxy = ...)]` syntax for format-specific proxy types.

use facet::Facet;
use facet_testhelpers::test;
use facet_xml::{from_str, to_string};

/// A proxy type that formats values as hex strings (for JSON).
#[derive(Facet, Clone, Debug)]
#[facet(transparent)]
pub struct HexString(pub String);

/// A proxy type that formats values as binary strings (for XML).
#[derive(Facet, Clone, Debug)]
#[facet(transparent)]
pub struct BinaryString(pub String);

/// A type that uses different proxies for different formats.
/// - For XML, the value is serialized as a binary string
/// - For JSON (or other formats), use the default hex proxy
#[derive(Facet, Debug, Clone, PartialEq)]
pub struct FormatAwareValue {
    pub name: String,
    #[facet(xml::proxy = BinaryString)]
    #[facet(proxy = HexString)]
    pub value: u32,
}

// JSON/default proxy conversion: u32 <-> hex string
impl TryFrom<HexString> for u32 {
    type Error = std::num::ParseIntError;
    fn try_from(proxy: HexString) -> Result<Self, Self::Error> {
        let s = proxy.0.trim_start_matches("0x").trim_start_matches("0X");
        u32::from_str_radix(s, 16)
    }
}

impl From<&u32> for HexString {
    fn from(v: &u32) -> Self {
        HexString(format!("0x{:x}", v))
    }
}

// XML proxy conversion: u32 <-> binary string
impl TryFrom<BinaryString> for u32 {
    type Error = std::num::ParseIntError;
    fn try_from(proxy: BinaryString) -> Result<Self, Self::Error> {
        u32::from_str_radix(proxy.0.trim_start_matches("0b"), 2)
    }
}

impl From<&u32> for BinaryString {
    fn from(v: &u32) -> Self {
        BinaryString(format!("0b{:b}", v))
    }
}

#[test]
fn test_xml_format_specific_proxy_serialization() {
    let data = FormatAwareValue {
        name: "test".to_string(),
        value: 255,
    };

    // XML should use the binary proxy (xml::proxy takes precedence)
    let xml = to_string(&data).unwrap();
    assert!(
        xml.contains("0b11111111"),
        "XML should use binary format, got: {xml}"
    );
}

#[test]
fn test_binary_string_conversion() {
    // Test that our TryFrom works correctly
    let bin = BinaryString("0b1010".to_string());
    let value: u32 = bin.try_into().unwrap();
    assert_eq!(value, 0b1010);
}

#[test]
fn test_xml_format_specific_proxy_deserialization() {
    let xml = r#"<formatAwareValue><name>test</name><value>0b11010</value></formatAwareValue>"#;
    let data: FormatAwareValue = from_str(xml).unwrap();

    assert_eq!(data.name, "test");
    assert_eq!(data.value, 0b11010);
}

/// A struct that only has an XML-specific proxy (no fallback).
#[derive(Facet, Debug, Clone, PartialEq)]
pub struct XmlOnlyProxy {
    pub label: String,
    #[facet(xml::proxy = BinaryString)]
    pub id: u32,
}

#[test]
fn test_xml_only_proxy_roundtrip() {
    let original = XmlOnlyProxy {
        label: "item".to_string(),
        id: 0b10101010,
    };

    let xml = to_string(&original).unwrap();
    assert!(
        xml.contains("0b10101010"),
        "XML should use binary format, got: {xml}"
    );

    let roundtripped: XmlOnlyProxy = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

/// Test that format-specific proxy shapes are correctly stored in the Field.
#[test]
fn test_xml_format_proxy_field_metadata() {
    use facet::Facet;
    use facet_core::{Type, UserType};

    let shape = <FormatAwareValue as Facet>::SHAPE;

    // Get the struct type
    let struct_type = match shape.ty {
        Type::User(UserType::Struct(s)) => s,
        _ => panic!("Expected struct type, got {:?}", shape.ty),
    };

    // Find the "value" field
    let value_field = struct_type
        .fields
        .iter()
        .find(|f| f.name == "value")
        .expect("Should have value field");

    // Should have format_proxies
    assert!(
        !value_field.format_proxies.is_empty(),
        "Should have format-specific proxies"
    );

    // Should have one for "xml"
    let xml_proxy = value_field.format_proxy("xml");
    assert!(xml_proxy.is_some(), "Should have xml proxy");

    // Should also have the default proxy
    assert!(value_field.proxy.is_some(), "Should have default proxy");

    // effective_proxy with "xml" should return the xml-specific one
    let effective_xml = value_field.effective_proxy(Some("xml"));
    assert!(effective_xml.is_some());

    // effective_proxy with "json" (no specific proxy) should fall back to default
    let effective_json = value_field.effective_proxy(Some("json"));
    assert!(
        effective_json.is_some(),
        "Should fall back to default proxy"
    );

    // They should be different (xml-specific vs default)
    assert_ne!(
        effective_xml.map(|p| p.shape.id),
        effective_json.map(|p| p.shape.id),
        "XML and JSON should use different proxies"
    );
}

/// A proxy type that wraps strings (uses FromStr/Display).
#[derive(Facet, Clone, Debug)]
#[facet(transparent)]
pub struct StringRepr(pub String);

impl TryFrom<StringRepr> for XmlScaleRangeName {
    type Error = &'static str;
    fn try_from(value: StringRepr) -> Result<Self, Self::Error> {
        value.0.parse()
    }
}

impl From<&XmlScaleRangeName> for StringRepr {
    fn from(_value: &XmlScaleRangeName) -> Self {
        StringRepr("Scale_Range".to_string())
    }
}

/// A zero-sized type that always serializes as a specific constant string.
/// The proxy is defined at the container level, not on the field.
#[derive(Debug, Default, Clone, Copy, Facet, PartialEq)]
#[facet(xml::proxy = StringRepr)]
pub struct XmlScaleRangeName;

impl core::fmt::Display for XmlScaleRangeName {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "Scale_Range")
    }
}

impl core::str::FromStr for XmlScaleRangeName {
    type Err = &'static str;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s == "Scale_Range" {
            Ok(Self)
        } else {
            Err("expected `Scale_Range`")
        }
    }
}

/// A struct that uses the XmlScaleRangeName type as a field.
/// The proxy is defined on XmlScaleRangeName (container level), not on this field.
#[derive(Facet, Debug, PartialEq)]
#[facet(rename = "Array")]
struct ArrayWithContainerProxy {
    #[facet(facet_xml::attribute)]
    name: XmlScaleRangeName,
}

/// Test that container-level proxies work when the type is used as a field.
/// This is a regression test for <https://github.com/facet-rs/facet/issues/1825>.
#[test]
fn test_container_level_proxy_in_field_deserialization() {
    let xml = r#"<Array name="Scale_Range" />"#;
    let data: ArrayWithContainerProxy = from_str(xml).unwrap();
    assert_eq!(data.name, XmlScaleRangeName);
}

/// Test serialization also works with container-level proxies.
#[test]
fn test_container_level_proxy_in_field_serialization() {
    let data = ArrayWithContainerProxy {
        name: XmlScaleRangeName,
    };
    let xml = to_string(&data).unwrap();
    assert!(
        xml.contains("Scale_Range"),
        "XML should contain 'Scale_Range', got: {xml}"
    );
}

/// Test round-trip with container-level proxy.
#[test]
fn test_container_level_proxy_roundtrip() {
    let original = ArrayWithContainerProxy {
        name: XmlScaleRangeName,
    };
    let xml = to_string(&original).unwrap();
    let roundtripped: ArrayWithContainerProxy = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

// ============================================================================
// Additional proxy coverage tests
// ============================================================================

/// A struct proxy for testing container-level proxies on struct types.
#[derive(Facet, Debug, Clone, PartialEq)]
pub struct PointProxy {
    pub x: i32,
    pub y: i32,
}

/// A point type that uses a proxy for XML serialization.
/// The proxy has different field names to verify the proxy shape is used.
#[derive(Facet, Debug, Clone, PartialEq)]
#[facet(xml::proxy = PointProxy)]
pub struct Point {
    pub x: i32,
    pub y: i32,
}

impl From<PointProxy> for Point {
    fn from(proxy: PointProxy) -> Self {
        Point {
            x: proxy.x,
            y: proxy.y,
        }
    }
}

impl From<&Point> for PointProxy {
    fn from(p: &Point) -> Self {
        PointProxy { x: p.x, y: p.y }
    }
}

/// Test container-level proxy as an element field (not attribute).
#[derive(Facet, Debug, PartialEq)]
struct ContainerWithPointElement {
    #[facet(rename = "location")]
    point: Point,
}

#[test]
fn test_container_level_proxy_as_element_field_roundtrip() {
    let original = ContainerWithPointElement {
        point: Point { x: 10, y: 20 },
    };
    let xml = to_string(&original).unwrap();
    eprintln!("XML: {xml}");
    assert!(xml.contains("<location>"), "Should have location element");
    assert!(xml.contains("<x>10</x>"), "Should have x element");
    assert!(xml.contains("<y>20</y>"), "Should have y element");

    let roundtripped: ContainerWithPointElement = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

/// Test container-level proxy in Option<T>.
#[derive(Facet, Debug, PartialEq)]
struct ContainerWithOptionalPoint {
    #[facet(rename = "location")]
    point: Option<Point>,
}

#[test]
fn test_container_level_proxy_in_option_some_roundtrip() {
    let original = ContainerWithOptionalPoint {
        point: Some(Point { x: 5, y: 15 }),
    };
    let xml = to_string(&original).unwrap();
    eprintln!("XML: {xml}");

    let roundtripped: ContainerWithOptionalPoint = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

#[test]
fn test_container_level_proxy_in_option_none_roundtrip() {
    let original = ContainerWithOptionalPoint { point: None };
    let xml = to_string(&original).unwrap();
    eprintln!("XML: {xml}");

    let roundtripped: ContainerWithOptionalPoint = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

/// Test container-level proxy in Vec<T>.
#[derive(Facet, Debug, PartialEq)]
struct ContainerWithPointList {
    #[facet(rename = "point")]
    points: Vec<Point>,
}

#[test]
fn test_container_level_proxy_in_vec_roundtrip() {
    let original = ContainerWithPointList {
        points: vec![
            Point { x: 1, y: 2 },
            Point { x: 3, y: 4 },
            Point { x: 5, y: 6 },
        ],
    };
    let xml = to_string(&original).unwrap();
    eprintln!("XML: {xml}");

    let roundtripped: ContainerWithPointList = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

#[test]
fn test_container_level_proxy_in_vec_empty_roundtrip() {
    let original = ContainerWithPointList { points: vec![] };
    let xml = to_string(&original).unwrap();
    eprintln!("XML: {xml}");

    let roundtripped: ContainerWithPointList = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

/// Test container-level proxy as the root type.
#[test]
fn test_container_level_proxy_as_root_type_roundtrip() {
    let original = Point { x: 100, y: 200 };
    let xml = to_string(&original).unwrap();
    eprintln!("XML: {xml}");
    // The element name should come from PointProxy's shape
    assert!(
        xml.contains("<pointProxy>") || xml.contains("<point>"),
        "Should serialize as pointProxy or point element"
    );

    let roundtripped: Point = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

/// Test proxy in nested struct.
#[derive(Facet, Debug, PartialEq)]
struct OuterContainer {
    name: String,
    inner: InnerWithProxy,
}

#[derive(Facet, Debug, PartialEq)]
struct InnerWithProxy {
    #[facet(rename = "pos")]
    position: Point,
}

#[test]
fn test_proxy_in_nested_struct_roundtrip() {
    let original = OuterContainer {
        name: "test".to_string(),
        inner: InnerWithProxy {
            position: Point { x: 42, y: 84 },
        },
    };
    let xml = to_string(&original).unwrap();
    eprintln!("XML: {xml}");

    let roundtripped: OuterContainer = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

/// A u32 wrapper that uses binary string proxy at container level.
#[derive(Facet, Debug, Clone, PartialEq)]
#[facet(xml::proxy = BinaryString)]
pub struct BinaryU32(pub u32);

impl TryFrom<BinaryString> for BinaryU32 {
    type Error = std::num::ParseIntError;
    fn try_from(proxy: BinaryString) -> Result<Self, Self::Error> {
        let s = proxy.0.trim_start_matches("0b");
        Ok(BinaryU32(u32::from_str_radix(s, 2)?))
    }
}

impl From<&BinaryU32> for BinaryString {
    fn from(v: &BinaryU32) -> Self {
        BinaryString(format!("0b{:b}", v.0))
    }
}

/// Test container-level proxy on item type in Vec<T>.
#[derive(Facet, Debug, PartialEq)]
struct ContainerWithProxiedItemList {
    #[facet(rename = "value")]
    values: Vec<BinaryU32>,
}

#[test]
fn test_container_level_proxy_on_vec_items_roundtrip() {
    let original = ContainerWithProxiedItemList {
        values: vec![BinaryU32(0b1010), BinaryU32(0b1100), BinaryU32(0b1111)],
    };
    let xml = to_string(&original).unwrap();
    eprintln!("XML: {xml}");
    assert!(xml.contains("0b1010"), "Should use binary format");
    assert!(xml.contains("0b1100"), "Should use binary format");
    assert!(xml.contains("0b1111"), "Should use binary format");

    let roundtripped: ContainerWithProxiedItemList = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

/// A proxy that represents a Vec<u32> as a comma-separated string.
#[derive(Facet, Clone, Debug)]
#[facet(transparent)]
pub struct CommaSeparatedU32s(pub String);

impl TryFrom<CommaSeparatedU32s> for Vec<u32> {
    type Error = std::num::ParseIntError;
    fn try_from(proxy: CommaSeparatedU32s) -> Result<Self, Self::Error> {
        if proxy.0.is_empty() {
            return Ok(vec![]);
        }
        proxy.0.split(',').map(|s| s.trim().parse()).collect()
    }
}

impl From<&Vec<u32>> for CommaSeparatedU32s {
    fn from(v: &Vec<u32>) -> Self {
        CommaSeparatedU32s(
            v.iter()
                .map(|n| n.to_string())
                .collect::<Vec<_>>()
                .join(","),
        )
    }
}

/// Test field-level proxy that converts entire Vec to a single string.
#[derive(Facet, Debug, PartialEq)]
struct ContainerWithCommaSeparatedField {
    name: String,
    #[facet(xml::proxy = CommaSeparatedU32s)]
    numbers: Vec<u32>,
}

#[test]
fn test_field_level_proxy_vec_as_comma_separated_string_roundtrip() {
    let original = ContainerWithCommaSeparatedField {
        name: "test".to_string(),
        numbers: vec![1, 2, 3, 4, 5],
    };
    let xml = to_string(&original).unwrap();
    eprintln!("XML: {xml}");
    assert!(
        xml.contains("1,2,3,4,5"),
        "Should serialize as comma-separated string, got: {xml}"
    );

    let roundtripped: ContainerWithCommaSeparatedField = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

#[test]
fn test_field_level_proxy_vec_as_comma_separated_string_empty_roundtrip() {
    let original = ContainerWithCommaSeparatedField {
        name: "empty".to_string(),
        numbers: vec![],
    };
    let xml = to_string(&original).unwrap();
    eprintln!("XML: {xml}");

    let roundtripped: ContainerWithCommaSeparatedField = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

// ============================================================================
// Edge case tests for proxy handling
// ============================================================================

/// Edge case 1: Field-level proxy on an attribute field.
/// Tests that `#[facet(xml::attribute, xml::proxy = P)]` works correctly.
#[derive(Facet, Debug, PartialEq)]
struct StructWithProxiedAttribute {
    name: String,
    #[facet(facet_xml::attribute, xml::proxy = BinaryString)]
    flags: u32,
}

#[test]
fn test_field_level_proxy_on_attribute_roundtrip() {
    let original = StructWithProxiedAttribute {
        name: "test".to_string(),
        flags: 0b10101010,
    };
    let xml = to_string(&original).unwrap();
    eprintln!("XML: {xml}");
    assert!(
        xml.contains(r#"flags="0b10101010""#),
        "Attribute should use binary proxy, got: {xml}"
    );

    let roundtripped: StructWithProxiedAttribute = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

/// Edge case 2: Field-level proxy combined with rename.
/// Tests that `#[facet(rename = "foo", xml::proxy = P)]` works correctly.
#[derive(Facet, Debug, PartialEq)]
struct StructWithRenamedProxiedField {
    name: String,
    #[facet(rename = "binaryValue", xml::proxy = BinaryString)]
    value: u32,
}

#[test]
fn test_field_level_proxy_with_rename_roundtrip() {
    let original = StructWithRenamedProxiedField {
        name: "test".to_string(),
        value: 0b11110000,
    };
    let xml = to_string(&original).unwrap();
    eprintln!("XML: {xml}");
    assert!(
        xml.contains("<binaryValue>0b11110000</binaryValue>"),
        "Should use renamed element with binary proxy, got: {xml}"
    );

    let roundtripped: StructWithRenamedProxiedField = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

/// A proxy for Option<String> that uses "N/A" for None.
#[derive(Facet, Clone, Debug)]
#[facet(transparent)]
pub struct OptionalStringProxy(pub String);

impl From<OptionalStringProxy> for Option<String> {
    fn from(proxy: OptionalStringProxy) -> Self {
        if proxy.0 == "N/A" {
            None
        } else {
            Some(proxy.0)
        }
    }
}

impl From<&Option<String>> for OptionalStringProxy {
    fn from(opt: &Option<String>) -> Self {
        match opt {
            Some(s) => OptionalStringProxy(s.clone()),
            None => OptionalStringProxy("N/A".to_string()),
        }
    }
}

/// Edge case 3: Field-level proxy on Option<T> where the proxy handles the whole Option.
/// This is different from Option<T> where T has a proxy - here we proxy the Option itself.
#[derive(Facet, Debug, PartialEq)]
struct StructWithProxiedOption {
    name: String,
    #[facet(xml::proxy = OptionalStringProxy)]
    description: Option<String>,
}

#[test]
fn test_field_level_proxy_on_option_some_roundtrip() {
    let original = StructWithProxiedOption {
        name: "test".to_string(),
        description: Some("hello world".to_string()),
    };
    let xml = to_string(&original).unwrap();
    eprintln!("XML: {xml}");
    assert!(
        xml.contains("<description>hello world</description>"),
        "Should serialize Some value, got: {xml}"
    );

    let roundtripped: StructWithProxiedOption = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

#[test]
fn test_field_level_proxy_on_option_none_roundtrip() {
    let original = StructWithProxiedOption {
        name: "test".to_string(),
        description: None,
    };
    let xml = to_string(&original).unwrap();
    eprintln!("XML: {xml}");
    assert!(
        xml.contains("<description>N/A</description>"),
        "Should serialize None as 'N/A', got: {xml}"
    );

    let roundtripped: StructWithProxiedOption = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

/// Edge case 4: Multiple fields with different proxies in the same struct.
#[derive(Facet, Debug, PartialEq)]
struct StructWithMultipleProxies {
    name: String,
    #[facet(xml::proxy = BinaryString)]
    binary_value: u32,
    #[facet(xml::proxy = HexString)]
    hex_value: u32,
    #[facet(xml::proxy = CommaSeparatedU32s)]
    list_value: Vec<u32>,
}

#[test]
fn test_multiple_fields_with_different_proxies_roundtrip() {
    let original = StructWithMultipleProxies {
        name: "test".to_string(),
        binary_value: 0b1111,
        hex_value: 0xFF,
        list_value: vec![1, 2, 3],
    };
    let xml = to_string(&original).unwrap();
    eprintln!("XML: {xml}");
    assert!(
        xml.contains("0b1111"),
        "binary_value should use binary proxy, got: {xml}"
    );
    assert!(
        xml.contains("0xff"),
        "hex_value should use hex proxy, got: {xml}"
    );
    assert!(
        xml.contains("1,2,3"),
        "list_value should use comma-separated proxy, got: {xml}"
    );

    let roundtripped: StructWithMultipleProxies = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

/// Edge case 5: Enum with variant containing a field that has container-level proxy.
#[derive(Facet, Debug, PartialEq)]
#[repr(C)]
enum ShapeEnum {
    Circle { radius: u32 },
    Rectangle { width: u32, height: u32 },
    Point(Point), // Point has container-level proxy
}

#[test]
fn test_enum_variant_with_container_proxy_roundtrip() {
    let original = ShapeEnum::Point(Point { x: 10, y: 20 });
    let xml = to_string(&original).unwrap();
    eprintln!("XML: {xml}");

    let roundtripped: ShapeEnum = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

#[test]
fn test_enum_variant_without_proxy_still_works() {
    let original = ShapeEnum::Rectangle {
        width: 100,
        height: 50,
    };
    let xml = to_string(&original).unwrap();
    eprintln!("XML: {xml}");

    let roundtripped: ShapeEnum = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

// ============================================================================
// Proxies inside enum variants - comprehensive tests
// ============================================================================

/// Enum with struct variant that has a field with field-level proxy.
#[derive(Facet, Debug, PartialEq)]
#[repr(C)]
enum EnumWithFieldProxyInStructVariant {
    Named {
        name: String,
        #[facet(xml::proxy = BinaryString)]
        flags: u32,
    },
    Other {
        value: i32,
    },
}

#[test]
fn test_enum_struct_variant_with_field_level_proxy_roundtrip() {
    let original = EnumWithFieldProxyInStructVariant::Named {
        name: "test".to_string(),
        flags: 0b10101010,
    };
    let xml = to_string(&original).unwrap();
    eprintln!("XML: {xml}");
    assert!(
        xml.contains("0b10101010"),
        "Should use binary proxy in struct variant field, got: {xml}"
    );

    let roundtripped: EnumWithFieldProxyInStructVariant = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

/// Enum with struct variant where a field's type has container-level proxy.
#[derive(Facet, Debug, PartialEq)]
#[repr(C)]
enum EnumWithContainerProxyInStructVariant {
    WithPoint {
        name: String,
        location: Point, // Point has container-level proxy
    },
    WithBinary {
        label: String,
        value: BinaryU32, // BinaryU32 has container-level proxy
    },
}

#[test]
fn test_enum_struct_variant_with_container_proxy_point_roundtrip() {
    let original = EnumWithContainerProxyInStructVariant::WithPoint {
        name: "origin".to_string(),
        location: Point { x: 0, y: 0 },
    };
    let xml = to_string(&original).unwrap();
    eprintln!("XML: {xml}");

    let roundtripped: EnumWithContainerProxyInStructVariant = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

#[test]
fn test_enum_struct_variant_with_container_proxy_binary_roundtrip() {
    let original = EnumWithContainerProxyInStructVariant::WithBinary {
        label: "flags".to_string(),
        value: BinaryU32(0b11110000),
    };
    let xml = to_string(&original).unwrap();
    eprintln!("XML: {xml}");
    assert!(
        xml.contains("0b11110000"),
        "Should use binary proxy, got: {xml}"
    );

    let roundtripped: EnumWithContainerProxyInStructVariant = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

/// Enum with newtype variant where the inner type has container-level proxy.
#[derive(Facet, Debug, PartialEq)]
#[repr(C)]
enum EnumWithNewtypeProxy {
    Point(Point),         // Point has container-level proxy
    Binary(BinaryU32),    // BinaryU32 has container-level proxy
    Plain(String),
}

#[test]
fn test_enum_newtype_variant_with_container_proxy_point_roundtrip() {
    let original = EnumWithNewtypeProxy::Point(Point { x: 42, y: 84 });
    let xml = to_string(&original).unwrap();
    eprintln!("XML: {xml}");

    let roundtripped: EnumWithNewtypeProxy = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

#[test]
fn test_enum_newtype_variant_with_container_proxy_binary_roundtrip() {
    let original = EnumWithNewtypeProxy::Binary(BinaryU32(0b1111));
    let xml = to_string(&original).unwrap();
    eprintln!("XML: {xml}");
    assert!(
        xml.contains("0b1111"),
        "Should use binary proxy in newtype variant, got: {xml}"
    );

    let roundtripped: EnumWithNewtypeProxy = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

#[test]
fn test_enum_newtype_variant_plain_still_works() {
    let original = EnumWithNewtypeProxy::Plain("hello".to_string());
    let xml = to_string(&original).unwrap();
    eprintln!("XML: {xml}");

    let roundtripped: EnumWithNewtypeProxy = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

/// Enum with tuple variant where one element has container-level proxy.
#[derive(Facet, Debug, PartialEq)]
#[repr(C)]
enum EnumWithTupleProxyVariant {
    NamedPoint(String, Point),        // Point has proxy
    NamedBinary(String, BinaryU32),   // BinaryU32 has proxy
    TwoPoints(Point, Point),          // Both have proxy
}

#[test]
fn test_enum_tuple_variant_with_container_proxy_roundtrip() {
    let original = EnumWithTupleProxyVariant::NamedPoint(
        "origin".to_string(),
        Point { x: 0, y: 0 },
    );
    let xml = to_string(&original).unwrap();
    eprintln!("XML: {xml}");

    let roundtripped: EnumWithTupleProxyVariant = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

#[test]
fn test_enum_tuple_variant_with_binary_proxy_roundtrip() {
    let original = EnumWithTupleProxyVariant::NamedBinary(
        "flags".to_string(),
        BinaryU32(0b10101010),
    );
    let xml = to_string(&original).unwrap();
    eprintln!("XML: {xml}");
    assert!(
        xml.contains("0b10101010"),
        "Should use binary proxy in tuple variant, got: {xml}"
    );

    let roundtripped: EnumWithTupleProxyVariant = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

#[test]
fn test_enum_tuple_variant_with_two_proxied_types_roundtrip() {
    let original = EnumWithTupleProxyVariant::TwoPoints(
        Point { x: 1, y: 2 },
        Point { x: 3, y: 4 },
    );
    let xml = to_string(&original).unwrap();
    eprintln!("XML: {xml}");

    let roundtripped: EnumWithTupleProxyVariant = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

/// Enum with struct variant containing Vec field with field-level proxy.
#[derive(Facet, Debug, PartialEq)]
#[repr(C)]
enum EnumWithVecProxyInVariant {
    WithNumbers {
        name: String,
        #[facet(xml::proxy = CommaSeparatedU32s)]
        values: Vec<u32>,
    },
    Simple {
        name: String,
    },
}

#[test]
fn test_enum_struct_variant_with_vec_field_proxy_roundtrip() {
    let original = EnumWithVecProxyInVariant::WithNumbers {
        name: "test".to_string(),
        values: vec![1, 2, 3, 4, 5],
    };
    let xml = to_string(&original).unwrap();
    eprintln!("XML: {xml}");
    assert!(
        xml.contains("1,2,3,4,5"),
        "Should use comma-separated proxy in enum variant, got: {xml}"
    );

    let roundtripped: EnumWithVecProxyInVariant = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

/// Enum with struct variant containing Option field with field-level proxy.
#[derive(Facet, Debug, PartialEq)]
#[repr(C)]
enum EnumWithOptionProxyInVariant {
    WithDescription {
        name: String,
        #[facet(xml::proxy = OptionalStringProxy)]
        description: Option<String>,
    },
}

#[test]
fn test_enum_struct_variant_with_option_proxy_some_roundtrip() {
    let original = EnumWithOptionProxyInVariant::WithDescription {
        name: "test".to_string(),
        description: Some("hello".to_string()),
    };
    let xml = to_string(&original).unwrap();
    eprintln!("XML: {xml}");

    let roundtripped: EnumWithOptionProxyInVariant = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

#[test]
fn test_enum_struct_variant_with_option_proxy_none_roundtrip() {
    let original = EnumWithOptionProxyInVariant::WithDescription {
        name: "test".to_string(),
        description: None,
    };
    let xml = to_string(&original).unwrap();
    eprintln!("XML: {xml}");
    assert!(
        xml.contains("N/A"),
        "Should use 'N/A' for None in enum variant, got: {xml}"
    );

    let roundtripped: EnumWithOptionProxyInVariant = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

// ============================================================================
// Additional edge cases to round out to 40 tests
// ============================================================================

/// Edge case: Tuple struct (not enum variant) with a proxied inner type.
#[derive(Facet, Debug, PartialEq)]
struct TupleStructWithProxy(Point, String);

#[test]
fn test_tuple_struct_with_proxied_field_roundtrip() {
    let original = TupleStructWithProxy(Point { x: 10, y: 20 }, "label".to_string());
    let xml = to_string(&original).unwrap();
    eprintln!("XML: {xml}");
    // Should have wrapper element with _0 and _1 children
    assert!(
        xml.contains("<_0>") && xml.contains("<_1>"),
        "Should have _0 and _1 elements for tuple fields, got: {xml}"
    );

    let roundtripped: TupleStructWithProxy = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

/// Edge case: Box<T> where T has a container-level proxy.
#[derive(Facet, Debug, PartialEq)]
struct ContainerWithBoxedProxy {
    name: String,
    point: Box<Point>,
}

#[test]
fn test_boxed_type_with_container_proxy_roundtrip() {
    let original = ContainerWithBoxedProxy {
        name: "boxed".to_string(),
        point: Box::new(Point { x: 100, y: 200 }),
    };
    let xml = to_string(&original).unwrap();
    eprintln!("XML: {xml}");

    let roundtripped: ContainerWithBoxedProxy = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

/// Edge case: Deeply nested proxy - struct containing struct containing proxied type.
#[derive(Facet, Debug, PartialEq)]
struct Level1 {
    name: String,
    level2: Level2,
}

#[derive(Facet, Debug, PartialEq)]
struct Level2 {
    id: u32,
    level3: Level3,
}

#[derive(Facet, Debug, PartialEq)]
struct Level3 {
    #[facet(xml::proxy = BinaryString)]
    flags: u32,
    point: Point, // container-level proxy
}

#[test]
fn test_deeply_nested_proxies_roundtrip() {
    let original = Level1 {
        name: "root".to_string(),
        level2: Level2 {
            id: 42,
            level3: Level3 {
                flags: 0b11001100,
                point: Point { x: 5, y: 10 },
            },
        },
    };
    let xml = to_string(&original).unwrap();
    eprintln!("XML: {xml}");
    assert!(
        xml.contains("0b11001100"),
        "Should use binary proxy at level 3, got: {xml}"
    );

    let roundtripped: Level1 = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

// ============================================================================
// Devious proxy edge cases (10 more tests)
// ============================================================================

/// Devious case 1: Field-level proxy OVERRIDING container-level proxy.
/// Point has container-level proxy (PointProxy), but field uses HexPoint instead.
#[derive(Facet, Clone, Debug)]
#[facet(transparent)]
pub struct HexPointProxy(pub String);

impl TryFrom<HexPointProxy> for Point {
    type Error = &'static str;
    fn try_from(proxy: HexPointProxy) -> Result<Self, Self::Error> {
        // Format: "x:hex,y:hex" e.g., "a:14" for x=10, y=20
        let parts: Vec<&str> = proxy.0.split(',').collect();
        if parts.len() != 2 {
            return Err("invalid hex point format");
        }
        let x = i32::from_str_radix(parts[0], 16).map_err(|_| "invalid hex x")?;
        let y = i32::from_str_radix(parts[1], 16).map_err(|_| "invalid hex y")?;
        Ok(Point { x, y })
    }
}

impl From<&Point> for HexPointProxy {
    fn from(p: &Point) -> Self {
        HexPointProxy(format!("{:x},{:x}", p.x, p.y))
    }
}

#[derive(Facet, Debug, PartialEq)]
struct FieldProxyOverridesContainer {
    /// Uses Point's container-level proxy (PointProxy - struct with x, y elements)
    normal_point: Point,
    /// Field-level proxy overrides to use hex string format
    #[facet(xml::proxy = HexPointProxy)]
    hex_point: Point,
}

#[test]
fn test_field_proxy_overrides_container_proxy() {
    let original = FieldProxyOverridesContainer {
        normal_point: Point { x: 10, y: 20 },
        hex_point: Point { x: 255, y: 256 },
    };
    let xml = to_string(&original).unwrap();
    eprintln!("XML: {xml}");
    // normal_point should use PointProxy (struct elements)
    assert!(
        xml.contains("<x>10</x>"),
        "normal_point should use container proxy, got: {xml}"
    );
    // hex_point should use HexPointProxy (single hex string)
    assert!(
        xml.contains("ff,100"),
        "hex_point should use field proxy override, got: {xml}"
    );

    let roundtripped: FieldProxyOverridesContainer = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

/// Devious case 2: Same underlying type with DIFFERENT field-level proxies.
#[derive(Facet, Debug, PartialEq)]
struct SameTypeDifferentProxies {
    #[facet(xml::proxy = BinaryString)]
    as_binary: u32,
    #[facet(xml::proxy = HexString)]
    as_hex: u32,
    /// No proxy - uses default decimal representation
    as_decimal: u32,
}

#[test]
fn test_same_type_different_field_proxies() {
    let original = SameTypeDifferentProxies {
        as_binary: 255,
        as_hex: 255,
        as_decimal: 255,
    };
    let xml = to_string(&original).unwrap();
    eprintln!("XML: {xml}");
    assert!(xml.contains("0b11111111"), "Should have binary, got: {xml}");
    assert!(xml.contains("0xff"), "Should have hex, got: {xml}");
    assert!(xml.contains(">255<"), "Should have decimal, got: {xml}");

    let roundtripped: SameTypeDifferentProxies = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

/// Devious case 3: Boolean serialized as "yes"/"no" string.
#[derive(Facet, Clone, Debug)]
#[facet(transparent)]
pub struct YesNoProxy(pub String);

impl TryFrom<YesNoProxy> for bool {
    type Error = &'static str;
    fn try_from(proxy: YesNoProxy) -> Result<Self, Self::Error> {
        match proxy.0.to_lowercase().as_str() {
            "yes" | "true" | "1" => Ok(true),
            "no" | "false" | "0" => Ok(false),
            _ => Err("expected yes/no"),
        }
    }
}

impl From<&bool> for YesNoProxy {
    fn from(b: &bool) -> Self {
        YesNoProxy(if *b { "yes" } else { "no" }.to_string())
    }
}

#[derive(Facet, Debug, PartialEq)]
struct BoolAsYesNo {
    name: String,
    #[facet(xml::proxy = YesNoProxy)]
    enabled: bool,
    #[facet(xml::proxy = YesNoProxy)]
    visible: bool,
}

#[test]
fn test_bool_as_yes_no_proxy() {
    let original = BoolAsYesNo {
        name: "feature".to_string(),
        enabled: true,
        visible: false,
    };
    let xml = to_string(&original).unwrap();
    eprintln!("XML: {xml}");
    assert!(
        xml.contains("<enabled>yes</enabled>"),
        "true should be 'yes', got: {xml}"
    );
    assert!(
        xml.contains("<visible>no</visible>"),
        "false should be 'no', got: {xml}"
    );

    let roundtripped: BoolAsYesNo = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

/// Devious case 4: Nested Vec - Vec<Vec<T>> where T has proxy.
#[derive(Facet, Debug, PartialEq)]
struct GridOfColors {
    name: String,
    #[facet(rename = "row")]
    rows: Vec<ColorRow>,
}

#[derive(Facet, Debug, Clone, PartialEq)]
struct ColorRow {
    #[facet(rename = "cell")]
    cells: Vec<Color>,
}

#[test]
fn test_nested_vec_with_proxied_items() {
    let original = GridOfColors {
        name: "checkerboard".to_string(),
        rows: vec![
            ColorRow {
                cells: vec![
                    Color { r: 0, g: 0, b: 0 },
                    Color {
                        r: 255,
                        g: 255,
                        b: 255,
                    },
                ],
            },
            ColorRow {
                cells: vec![
                    Color {
                        r: 255,
                        g: 255,
                        b: 255,
                    },
                    Color { r: 0, g: 0, b: 0 },
                ],
            },
        ],
    };
    let xml = to_string(&original).unwrap();
    eprintln!("XML: {xml}");
    // Each color should use the hex string proxy
    assert!(
        xml.contains("#000000"),
        "Should have black cells, got: {xml}"
    );
    assert!(
        xml.contains("#ffffff"),
        "Should have white cells, got: {xml}"
    );

    let roundtripped: GridOfColors = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

/// Devious case 5: Option<Vec<T>> where T has container-level proxy.
#[derive(Facet, Debug, PartialEq)]
struct OptionalVecOfProxied {
    name: String,
    #[facet(rename = "point")]
    points: Option<Vec<Point>>,
}

#[test]
fn test_option_vec_of_proxied_some() {
    let original = OptionalVecOfProxied {
        name: "path".to_string(),
        points: Some(vec![Point { x: 1, y: 2 }, Point { x: 3, y: 4 }]),
    };
    let xml = to_string(&original).unwrap();
    eprintln!("XML: {xml}");

    let roundtripped: OptionalVecOfProxied = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

#[test]
fn test_option_vec_of_proxied_none() {
    let original = OptionalVecOfProxied {
        name: "empty".to_string(),
        points: None,
    };
    let xml = to_string(&original).unwrap();
    eprintln!("XML: {xml}");

    let roundtripped: OptionalVecOfProxied = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

/// Devious case 6: Proxy that collapses a struct into a single delimited string.
#[derive(Facet, Clone, Debug)]
#[facet(transparent)]
pub struct RgbString(pub String);

#[derive(Facet, Debug, Clone, PartialEq)]
#[facet(xml::proxy = RgbString)]
pub struct Color {
    pub r: u8,
    pub g: u8,
    pub b: u8,
}

impl TryFrom<RgbString> for Color {
    type Error = &'static str;
    fn try_from(proxy: RgbString) -> Result<Self, Self::Error> {
        // Format: "r,g,b" or "#RRGGBB"
        let s = proxy.0.trim();
        if s.starts_with('#') && s.len() == 7 {
            let r = u8::from_str_radix(&s[1..3], 16).map_err(|_| "invalid r")?;
            let g = u8::from_str_radix(&s[3..5], 16).map_err(|_| "invalid g")?;
            let b = u8::from_str_radix(&s[5..7], 16).map_err(|_| "invalid b")?;
            Ok(Color { r, g, b })
        } else {
            let parts: Vec<&str> = s.split(',').collect();
            if parts.len() != 3 {
                return Err("expected r,g,b or #RRGGBB");
            }
            let r: u8 = parts[0].trim().parse().map_err(|_| "invalid r")?;
            let g: u8 = parts[1].trim().parse().map_err(|_| "invalid g")?;
            let b: u8 = parts[2].trim().parse().map_err(|_| "invalid b")?;
            Ok(Color { r, g, b })
        }
    }
}

impl From<&Color> for RgbString {
    fn from(c: &Color) -> Self {
        RgbString(format!("#{:02x}{:02x}{:02x}", c.r, c.g, c.b))
    }
}

#[derive(Facet, Debug, PartialEq)]
struct PaletteEntry {
    name: String,
    color: Color,
}

#[test]
fn test_struct_collapsed_to_string_proxy() {
    let original = PaletteEntry {
        name: "red".to_string(),
        color: Color {
            r: 255,
            g: 0,
            b: 128,
        },
    };
    let xml = to_string(&original).unwrap();
    eprintln!("XML: {xml}");
    // Color should be serialized as hex string, not struct
    assert!(
        xml.contains("#ff0080"),
        "Color should be hex string, got: {xml}"
    );
    assert!(
        !xml.contains("<r>"),
        "Should NOT have <r> element, got: {xml}"
    );

    let roundtripped: PaletteEntry = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

/// Devious case 7: Vec of colors (each color uses its container proxy).
#[derive(Facet, Debug, PartialEq)]
struct Palette {
    name: String,
    #[facet(rename = "color")]
    colors: Vec<Color>,
}

#[test]
fn test_vec_of_struct_with_string_proxy() {
    let original = Palette {
        name: "primary".to_string(),
        colors: vec![
            Color { r: 255, g: 0, b: 0 },
            Color { r: 0, g: 255, b: 0 },
            Color { r: 0, g: 0, b: 255 },
        ],
    };
    let xml = to_string(&original).unwrap();
    eprintln!("XML: {xml}");
    assert!(xml.contains("#ff0000"), "Should have red");
    assert!(xml.contains("#00ff00"), "Should have green");
    assert!(xml.contains("#0000ff"), "Should have blue");

    let roundtripped: Palette = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

/// Devious case 8: Enum variants with different proxy behaviors.
#[derive(Facet, Debug, PartialEq)]
#[repr(C)]
enum ShapeWithMixedProxies {
    /// Point uses its container-level proxy
    Point(Point),
    /// Color uses its container-level proxy (string)
    ColoredDot { location: Point, color: Color },
    /// Raw coordinates (no proxy involvement)
    RawCoords { x: i32, y: i32 },
}

#[test]
fn test_enum_variants_with_mixed_proxy_behaviors() {
    let point = ShapeWithMixedProxies::Point(Point { x: 5, y: 10 });
    let xml = to_string(&point).unwrap();
    eprintln!("Point XML: {xml}");
    let rt: ShapeWithMixedProxies = from_str(&xml).unwrap();
    assert_eq!(point, rt);

    let colored = ShapeWithMixedProxies::ColoredDot {
        location: Point { x: 100, y: 200 },
        color: Color {
            r: 128,
            g: 64,
            b: 32,
        },
    };
    let xml = to_string(&colored).unwrap();
    eprintln!("ColoredDot XML: {xml}");
    assert!(xml.contains("#804020"), "Color should be hex string");
    let rt: ShapeWithMixedProxies = from_str(&xml).unwrap();
    assert_eq!(colored, rt);

    let raw = ShapeWithMixedProxies::RawCoords { x: 42, y: 84 };
    let xml = to_string(&raw).unwrap();
    eprintln!("RawCoords XML: {xml}");
    let rt: ShapeWithMixedProxies = from_str(&xml).unwrap();
    assert_eq!(raw, rt);
}

/// Devious case 9: Proxy combined with xml::attribute.
#[derive(Facet, Debug, PartialEq)]
#[facet(rename = "rect")]
struct RectWithProxiedAttributes {
    #[facet(facet_xml::attribute, xml::proxy = HexString)]
    width: u32,
    #[facet(facet_xml::attribute, xml::proxy = HexString)]
    height: u32,
    #[facet(facet_xml::attribute)]
    fill: Color,
}

#[test]
fn test_multiple_proxied_attributes() {
    let original = RectWithProxiedAttributes {
        width: 256,
        height: 128,
        fill: Color {
            r: 255,
            g: 128,
            b: 0,
        },
    };
    let xml = to_string(&original).unwrap();
    eprintln!("XML: {xml}");
    // Attributes should use proxies
    assert!(
        xml.contains(r#"width="0x100""#),
        "width should be hex, got: {xml}"
    );
    assert!(
        xml.contains(r#"height="0x80""#),
        "height should be hex, got: {xml}"
    );
    assert!(
        xml.contains(r##"fill="#ff8000""##),
        "fill should be color hex, got: {xml}"
    );

    let roundtripped: RectWithProxiedAttributes = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

/// Devious case 10: Recursive structure where proxy is used at each level.
#[derive(Facet, Debug, Clone, PartialEq)]
struct TreeNode {
    value: Color,
    #[facet(rename = "child")]
    children: Vec<TreeNode>,
}

#[test]
fn test_recursive_structure_with_proxy() {
    let original = TreeNode {
        value: Color { r: 255, g: 0, b: 0 },
        children: vec![
            TreeNode {
                value: Color { r: 0, g: 255, b: 0 },
                children: vec![TreeNode {
                    value: Color { r: 0, g: 0, b: 255 },
                    children: vec![],
                }],
            },
            TreeNode {
                value: Color {
                    r: 255,
                    g: 255,
                    b: 0,
                },
                children: vec![],
            },
        ],
    };
    let xml = to_string(&original).unwrap();
    eprintln!("XML: {xml}");
    // All colors at all levels should use the proxy
    assert!(xml.contains("#ff0000"), "Root should be red");
    assert!(xml.contains("#00ff00"), "Child should be green");
    assert!(xml.contains("#0000ff"), "Grandchild should be blue");
    assert!(xml.contains("#ffff00"), "Second child should be yellow");

    let roundtripped: TreeNode = from_str(&xml).unwrap();
    assert_eq!(original, roundtripped);
}

// ============================================================================
// xml::elements should use item type's rename
// ============================================================================

// Import to make xml:: prefix work in attributes
use facet_xml as xml;

#[derive(Debug, Facet, PartialEq)]
#[repr(C)]
enum XmlTag {
    #[facet(rename = "TagFoo")]
    Foo {
        #[facet(facet_xml::attribute)]
        name: String,
        #[facet(facet_xml::attribute)]
        value: u32,
    },
    #[facet(rename = "TagBar")]
    Bar {
        #[facet(facet_xml::attribute)]
        name: String,
        #[facet(facet_xml::attribute)]
        bar_value: String,
    },
    #[facet(rename = "TagBaz")]
    Baz {
        #[facet(facet_xml::attribute)]
        name: String,
        #[facet(facet_xml::attribute)]
        baz: Option<String>,
    },
}

#[derive(Debug, Facet, PartialEq)]
#[facet(rename = "Object")]
struct XmlObject {
    #[facet(xml::attribute)]
    id: String,
    #[facet(xml::elements)]
    elements: Vec<XmlTag>,
}

#[derive(Debug, Facet, PartialEq)]
#[facet(rename = "Outer")]
struct XmlOuter {
    #[facet(xml::elements)]
    // Should automatically use "Object" from XmlObject's rename
    objects: Vec<XmlObject>,
}

#[test]
fn test_xml_elements_uses_item_type_rename() {
    let xml = r#"
<Outer>
    <Object id="first">
        <TagFoo name="Foo" value="420" />
        <TagBar name="Bar" barValue="Bar Value" />
        <TagBaz name="BazNotUsableAsAtag" />
        <TagBaz name="BazWithValue" baz="bazbazbaz" />
    </Object>
    <Object id="second">
    </Object>
</Outer>
"#;
    let parsed: XmlOuter = from_str(xml).unwrap();
    assert_eq!(parsed.objects.len(), 2);
    assert_eq!(parsed.objects[0].id, "first");
    assert_eq!(parsed.objects[0].elements.len(), 4);
    assert_eq!(parsed.objects[1].id, "second");
    assert_eq!(parsed.objects[1].elements.len(), 0);

    // Roundtrip
    let serialized = to_string(&parsed).unwrap();
    let roundtripped: XmlOuter = from_str(&serialized).unwrap();
    assert_eq!(parsed, roundtripped);
}

// ============================================================================
// Issue #7: rename_all should affect root element name (NOT YET FIXED)
// https://github.com/facet-rs/facet-xml/issues/7
// ============================================================================

#[derive(Debug, Facet, PartialEq)]
#[facet(rename_all = "PascalCase")]
struct Issue7Root {
    value: String,
}

#[test]
fn test_issue7_rename_all_affects_root_element() {
    // Issue #7: rename_all should affect the root element name
    // With rename_all = "PascalCase", Issue7Root becomes <Issue7Root>
    let xml = r#"<Issue7Root><Value>foo</Value></Issue7Root>"#;
    let parsed: Issue7Root = from_str(xml).unwrap();
    assert_eq!(parsed.value, "foo");

    // Serialization should also use PascalCase for root
    let serialized = to_string(&parsed).unwrap();
    assert!(
        serialized.contains("<Issue7Root>"),
        "Expected <Issue7Root> but got: {}",
        serialized
    );

    // Roundtrip
    let roundtripped: Issue7Root = from_str(&serialized).unwrap();
    assert_eq!(parsed, roundtripped);
}

#[test]
fn test_issue7_wrong_case_rejected() {
    // With rename_all = "PascalCase", lowerCamelCase root should be rejected
    let xml = r#"<issue7Root><Value>foo</Value></issue7Root>"#;
    let result: Result<Issue7Root, _> = from_str(xml);
    assert!(result.is_err(), "Should reject lowerCamelCase root");
}

// ============================================================================
// More xml::elements edge cases with rename/flatten
// ============================================================================

#[derive(Debug, Facet, PartialEq)]
#[repr(C)]
enum MixedRenameEnum {
    // No rename - uses lowerCamelCase default
    DefaultCase {
        #[facet(xml::attribute)]
        id: String,
    },
    // Explicit rename overrides rename_all
    #[facet(rename = "CustomName")]
    ExplicitRename {
        #[facet(xml::attribute)]
        id: String,
    },
}

#[derive(Debug, Facet, PartialEq)]
#[facet(rename = "Container")]
struct MixedRenameContainer {
    #[facet(xml::elements)]
    items: Vec<MixedRenameEnum>,
}

#[test]
fn test_xml_elements_with_mixed_variant_renames() {
    // DefaultCase has no rename -> uses lowerCamelCase: defaultCase
    // ExplicitRename has #[facet(rename = "CustomName")] -> uses CustomName
    let xml = r#"<Container><defaultCase id="a"/><CustomName id="b"/></Container>"#;
    let parsed: MixedRenameContainer = from_str(xml).unwrap();
    assert_eq!(parsed.items.len(), 2);

    // Roundtrip
    let serialized = to_string(&parsed).unwrap();
    let roundtripped: MixedRenameContainer = from_str(&serialized).unwrap();
    assert_eq!(parsed, roundtripped);
}