genson-core 0.2.4

Core library for JSON schema inference using genson-rs
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
#[cfg_attr(feature = "trace", crustrace::omni)]
mod innermod {
    use crate::genson_rs::{build_json_schema, get_builder, BuildConfig};
    use serde::de::Error as DeError;
    use serde::{Deserialize, Serialize};
    use serde_json::Value;
    use std::borrow::Cow;
    use std::panic::{self, AssertUnwindSafe};

    /// Maximum length of JSON string to include in error messages before truncating
    const MAX_JSON_ERROR_LENGTH: usize = 100;

    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct SchemaInferenceConfig {
        /// Whether to treat top-level arrays as streams of objects
        pub ignore_outer_array: bool,
        /// Delimiter for NDJSON format (None for regular JSON)
        pub delimiter: Option<u8>,
        /// Schema URI to use ("AUTO" for auto-detection)
        pub schema_uri: Option<String>,
        /// Threshold above which non-fixed keys are treated as a map
        pub map_threshold: usize,
        /// Maximum number of required keys a Map can have. If None, no gating based on required keys.
        /// If Some(n), objects with more than n required keys will be forced to Record type.
        pub map_max_required_keys: Option<usize>,
        /// Enable unification of compatible but non-homogeneous record schemas into maps
        pub unify_maps: bool,
        /// Force override of field treatment, e.g. {"labels": "map"}
        pub force_field_types: std::collections::HashMap<String, String>,
        /// Whether to promote scalar values to wrapped objects when they collide with record values
        /// during unification. If `true`, scalars are promoted under a synthetic property name derived from
        /// the parent field and the scalar type (e.g. "foo__string"). If `false`, don't unify on conflicts.
        pub wrap_scalars: bool,
        /// Wrap the inferred top-level schema under a single required field with this name.
        /// Example: wrap_root = Some("labels") turns `{...}` into
        /// `{"type":"object","properties":{"labels":{...}},"required":["labels"]}`.
        pub wrap_root: Option<String>,
        /// Whether to output Avro schema rather than regular JSON Schema.
        #[cfg(feature = "avro")]
        pub avro: bool,
        /// Enable debug output. When `true`, prints detailed information about schema inference
        /// processes including field unification, map detection, and scalar wrapping decisions.
        pub debug: bool,
    }

    impl Default for SchemaInferenceConfig {
        fn default() -> Self {
            Self {
                ignore_outer_array: true,
                delimiter: None,
                schema_uri: Some("AUTO".to_string()),
                map_threshold: 20,
                map_max_required_keys: None,
                unify_maps: false,
                force_field_types: std::collections::HashMap::new(),
                wrap_scalars: true,
                wrap_root: None,
                #[cfg(feature = "avro")]
                avro: false,
                debug: false,
            }
        }
    }

    impl SchemaInferenceConfig {
        pub fn debug(&self, args: std::fmt::Arguments) {
            if self.debug {
                eprintln!("{}", args);
            }
        }
    }

    #[macro_export]
    macro_rules! debug {
        ($cfg:expr, $($arg:tt)*) => {
            $cfg.debug(format_args!($($arg)*))
        };
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct SchemaInferenceResult {
        pub schema: Value,
        pub processed_count: usize,
    }

    #[cfg(feature = "avro")]
    impl SchemaInferenceResult {
        pub fn to_avro_schema(
            &self,
            namespace: &str,
            utility_namespace: Option<&str>,
            base_uri: Option<&str>,
            split_top_level: bool,
        ) -> Value {
            avrotize::converter::jsons_to_avro(
                &self.schema,
                namespace,
                utility_namespace.unwrap_or(""),
                base_uri.unwrap_or("genson-core"),
                split_top_level,
            )
        }
    }

    fn validate_json(s: &str) -> Result<(), serde_json::Error> {
        let mut de = serde_json::Deserializer::from_str(s);
        serde::de::IgnoredAny::deserialize(&mut de)?; // lightweight: ignores the parsed value
        de.end()
    }

    fn validate_ndjson(s: &str) -> Result<(), serde_json::Error> {
        for line in s.lines() {
            let trimmed = line.trim();
            if trimmed.is_empty() {
                continue;
            }
            validate_json(trimmed)?; // propagate serde_json::Error
        }
        Ok(())
    }

    /// Normalize a schema that may be wrapped in one or more layers of
    /// `["null", <type>]` union arrays.
    ///
    /// During inference, schemas often get wrapped in a nullable-union
    /// more than once (e.g. `["null", ["null", {"type": "string"}]]`).
    /// This helper strips away *all* redundant layers of `["null", ...]`
    /// until only the innermost non-null schema remains.
    ///
    /// This ensures that equality checks and recursive unification don’t
    /// spuriously fail due to extra layers of null-wrapping.
    fn normalise_nullable(v: &serde_json::Value) -> &serde_json::Value {
        let mut current = v;
        loop {
            if let Some(arr) = current.as_array() {
                if arr.len() == 2 && arr.contains(&serde_json::Value::String("null".to_string())) {
                    // peel off the non-null element
                    current = arr
                        .iter()
                        .find(|x| *x != &serde_json::Value::String("null".to_string()))
                        .unwrap();
                    continue;
                }
            }
            return current;
        }
    }

    /// Return a string representation of a JSON Schema type.
    /// If it’s a union, pick the first non-"null" type.
    fn schema_type_str(schema: &Value) -> String {
        if let Some(t) = schema.get("type").and_then(|v| v.as_str()) {
            return t.to_string();
        }

        // handle union case: ["null", {"type": "string"}]
        if let Some(arr) = schema.as_array() {
            for v in arr {
                if v != "null" {
                    if let Some(t) = v.get("type").and_then(|x| x.as_str()) {
                        return t.to_string();
                    }
                }
            }
        }

        "unknown".to_string()
    }

    /// Check if a collection of record schemas can be unified into a single schema with selective nullable fields.
    ///
    /// This function determines whether heterogeneous record schemas are "unifiable" - meaning they
    /// can be merged into a single schema where only missing fields become nullable. This enables
    /// map inference for cases where record values have compatible but non-identical structures.
    ///
    /// Schemas are considered unifiable if:
    /// 1. All schemas represent record types (`"type": "object"` with `"properties"`)
    /// 2. Field names are either disjoint OR have identical types when they overlap
    /// 3. No field has conflicting type definitions across schemas
    ///
    /// Fields present in all schemas remain required, while fields missing from some schemas
    /// become nullable unions (e.g., `["null", {"type": "string"}]`).
    ///
    /// When `wrap_scalars` is enabled, scalar types that collide with object types are promoted
    /// to singleton objects under a synthetic key (e.g., `value__string`), allowing unification
    /// to succeed instead of failing.
    ///
    /// # Returns
    ///
    /// - `Some(unified_schema)` if schemas can be unified - contains all unique fields with selective nullability
    /// - `None` if schemas cannot be unified due to:
    ///   - Non-record types in the collection
    ///   - Conflicting field types (same field name, different types)
    ///   - Empty schema collection
    fn check_unifiable_schemas(
        schemas: &[Value],
        path: &str,
        config: &SchemaInferenceConfig,
    ) -> Option<Value> {
        if schemas.is_empty() {
            debug!(config, "{path}: failed (empty schema list)");
            return None;
        }

        // Only unify record schemas
        if !schemas
            .iter()
            .all(|s| s.get("type") == Some(&Value::String("object".into())))
        {
            // debug!(config, "{path}: failed (non-object schema): {schemas:?}");
            return None;
        }

        let mut all_fields = ordermap::OrderMap::new();
        let mut field_counts = std::collections::HashMap::new();

        // Helper function to check if two schemas are compatible (handling nullable vs non-nullable)
        let schemas_compatible = |existing: &Value, new: &Value| -> Option<Value> {
            if existing == new {
                return Some(existing.clone());
            }

            // Handle new JSON Schema nullable format: {"type": ["null", "string"]}
            let extract_nullable_info = |schema: &Value| -> (bool, Value) {
                if let Some(Value::Array(type_arr)) = schema.get("type") {
                    if type_arr.len() == 2 && type_arr.contains(&Value::String("null".into())) {
                        let non_null_type = type_arr
                            .iter()
                            .find(|t| *t != &Value::String("null".into()))
                            .unwrap();
                        (true, serde_json::json!({"type": non_null_type}))
                    } else {
                        (false, schema.clone())
                    }
                } else {
                    (false, schema.clone())
                }
            };

            let (existing_nullable, existing_inner) = extract_nullable_info(existing);
            let (new_nullable, new_inner) = extract_nullable_info(new);

            // If the inner types match, return the nullable version
            if existing_inner == new_inner {
                if existing_nullable || new_nullable {
                    let inner_type = existing_inner.get("type").unwrap();
                    return Some(serde_json::json!({
                        "type": ["null", inner_type]
                    }));
                } else {
                    return Some(existing_inner);
                }
            }

            None
        };

        // Collect all field types and count occurrences
        for (i, schema) in schemas.iter().enumerate() {
            if let Some(Value::Object(props)) = schema.get("properties") {
                for (field_name, field_schema) in props {
                    *field_counts.entry(field_name.clone()).or_insert(0) += 1;

                    match all_fields.entry(field_name.clone()) {
                        ordermap::map::Entry::Vacant(e) => {
                            debug!(config, "Schema[{i}] introduces new field `{field_name}`");

                            // Normalise before storing
                            e.insert(normalise_nullable(field_schema).clone());
                        }
                        ordermap::map::Entry::Occupied(mut e) => {
                            // Normalise both sides before comparison
                            let existing = normalise_nullable(e.get()).clone();
                            let new = normalise_nullable(field_schema).clone();

                            // First try the compatibility check for nullable/non-nullable
                            if let Some(compatible_schema) = schemas_compatible(&existing, &new) {
                                debug!(config, "Field `{field_name}` compatible (nullable/non-nullable unification)");
                                e.insert(compatible_schema);
                            } else if existing.get("type") == Some(&Value::String("object".into()))
                                && new.get("type") == Some(&Value::String("object".into()))
                            {
                                // Try recursive unify if both are objects
                                debug!(config,
                                    "Field `{field_name}` has conflicting object schemas, attempting recursive unify"
                                );
                                if let Some(unified) = check_unifiable_schemas(
                                    &[existing.clone(), new.clone()],
                                    &format!("{path}.{}", field_name),
                                    config,
                                ) {
                                    debug!(
                                        config,
                                        "Field `{field_name}` unified successfully after recursion"
                                    );
                                    e.insert(unified);
                                } else {
                                    debug!(config, "{path}.{}: failed to unify", field_name);
                                    return None;
                                }
                            } else {
                                // Handle scalar vs object promotion if wrap_scalars is enabled
                                if config.wrap_scalars {
                                    let existing_is_obj = existing.get("type")
                                        == Some(&Value::String("object".into()));
                                    let new_is_obj = field_schema.get("type")
                                        == Some(&Value::String("object".into()));

                                    if existing_is_obj ^ new_is_obj {
                                        // One is object, other is scalar → wrap scalar
                                        let (obj_schema, scalar_schema, scalar_side) =
                                            if existing_is_obj {
                                                (existing.clone(), field_schema.clone(), "new")
                                            } else {
                                                (field_schema.clone(), existing.clone(), "existing")
                                            };

                                        let type_suffix = schema_type_str(&scalar_schema);
                                        let wrapped_key =
                                            format!("{}__{}", field_name, type_suffix);

                                        debug!(config,
                                            "Promoting scalar on {} side: wrapping into object under key `{}`",
                                            scalar_side, wrapped_key
                                        );

                                        let mut wrapped_props = serde_json::Map::new();
                                        wrapped_props.insert(wrapped_key, scalar_schema.clone());

                                        let promoted = serde_json::json!({
                                            "type": "object",
                                            "properties": wrapped_props
                                        });

                                        // Recursively unify with the object schema
                                        if let Some(unified) = check_unifiable_schemas(
                                            &[obj_schema.clone(), promoted.clone()],
                                            &format!("{path}.{}", field_name),
                                            config,
                                        ) {
                                            debug!(config,
                                                "Field `{field_name}` unified successfully after scalar promotion"
                                            );
                                            e.insert(unified);
                                            continue;
                                        }
                                    }
                                }

                                // If we didn’t handle it, it’s a true conflict
                                debug!(config,
                                    "{path}.{field_name}: incompatible types:\n  existing={:#?}\n  new={:#?}",
                                    existing, field_schema
                                );
                                return None; // fundamentally incompatible types
                            }
                        }
                    }
                }
            } else {
                debug!(config, "Schema[{i}] has no properties object");
                return None;
            }
        }

        let total_schemas = schemas.len();
        let mut unified_properties = serde_json::Map::new();

        // Required in all -> non-nullable
        for (field_name, field_type) in &all_fields {
            let count = field_counts.get(field_name).unwrap_or(&0);
            if *count == total_schemas {
                debug!(
                    config,
                    "Field `{field_name}` present in all schemas → keeping non-nullable"
                );
                unified_properties.insert(field_name.clone(), field_type.clone());
            }
        }

        // Missing in some -> nullable
        for (field_name, field_type) in &all_fields {
            let count = field_counts.get(field_name).unwrap_or(&0);
            if *count < total_schemas {
                debug!(
                    config,
                    "Field `{field_name}` missing in {}/{} schemas → making nullable",
                    total_schemas - count,
                    total_schemas
                );

                // Create proper JSON Schema nullable syntax
                if let Some(type_str) = field_type.get("type").and_then(|t| t.as_str()) {
                    // Create a copy of the field_type and modify its type to be a union
                    let mut nullable_field = field_type.clone();
                    nullable_field["type"] = serde_json::json!(["null", type_str]);
                    unified_properties.insert(field_name.clone(), nullable_field);
                } else {
                    // Fallback for schemas without explicit type
                    unified_properties
                        .insert(field_name.clone(), serde_json::json!(["null", field_type]));
                }
            }
        }

        debug!(config, "Schemas unified successfully");
        Some(serde_json::json!({
            "type": "object",
            "properties": unified_properties
        }))
    }

    /// Post-process an inferred JSON Schema to rewrite certain object shapes as maps.
    ///
    /// This mutates the schema in place, applying user overrides and heuristics.
    ///
    /// # Rules
    /// - If the current field name matches a `force_field_types` override, that wins
    ///   (`"map"` rewrites to `additionalProperties`, `"record"` leaves as-is).
    /// - Otherwise, applies map inference heuristics based on:
    ///   - Total key cardinality (`map_threshold`)
    ///   - Required key cardinality (`map_max_required_keys`)
    ///   - Value homogeneity (all values must be homogeneous) OR
    ///   - Value unifiability (compatible record schemas when `unify_maps` enabled)
    /// - Recurses into nested objects/arrays, carrying field names down so overrides apply.
    fn rewrite_objects(
        schema: &mut Value,
        field_name: Option<&str>,
        config: &SchemaInferenceConfig,
    ) {
        if let Value::Object(obj) = schema {
            // --- Forced overrides by field name ---
            if let Some(name) = field_name {
                if let Some(forced) = config.force_field_types.get(name) {
                    match forced.as_str() {
                        "map" => {
                            obj.remove("properties");
                            obj.remove("required");
                            obj.insert(
                                "additionalProperties".to_string(),
                                serde_json::json!({ "type": "string" }),
                            );
                            return; // no need to apply heuristics or recurse
                        }
                        "record" => {
                            if let Some(props) =
                                obj.get_mut("properties").and_then(|p| p.as_object_mut())
                            {
                                for (k, v) in props {
                                    rewrite_objects(v, Some(k), config);
                                }
                            }
                            if let Some(items) = obj.get_mut("items") {
                                rewrite_objects(items, None, config);
                            }
                            return;
                        }
                        _ => {}
                    }
                }
            }

            // --- Heuristic rewrite ---
            if let Some(props) = obj.get("properties").and_then(|p| p.as_object()) {
                let key_count = props.len(); // |UK| - total keys observed
                let above_threshold = key_count >= config.map_threshold;

                // Copy out child schema shapes
                let child_schemas: Vec<Value> = props.values().cloned().collect();

                // Detect map-of-records only if:
                // - all children are identical
                // - and that child is itself an object with "properties" (i.e. a proper record)
                if above_threshold {
                    if let Some(first) = child_schemas.first() {
                        if first.get("type") == Some(&Value::String("object".into()))
                            && first.get("properties").is_some()
                            && child_schemas.len() > 1
                        {
                            let all_same = child_schemas.iter().all(|other| other == first);
                            if all_same {
                                obj.remove("properties");
                                obj.remove("required");
                                obj.insert("additionalProperties".to_string(), first.clone());
                                return;
                            }
                        }
                    }
                }

                // Calculate required key count |RK|
                let required_key_count = obj
                    .get("required")
                    .and_then(|r| r.as_array())
                    .map(|r| r.len())
                    .unwrap_or(0);

                // Check for unifiable schemas
                let mut unified_schema: Option<Value> = None;
                if let Some(first_schema) = props.values().next() {
                    if props.values().all(|schema| schema == first_schema) {
                        // Handle union types properly - extract the non-null type for additionalProperties
                        if let Value::Array(arr) = first_schema {
                            if arr.len() == 2 && arr.contains(&Value::String("null".to_string())) {
                                // This is a nullable union - extract the non-null type
                                let non_null_type = arr
                                    .iter()
                                    .find(|v| *v != &Value::String("null".to_string()))
                                    .unwrap();
                                unified_schema = Some(non_null_type.clone());
                            } else {
                                unified_schema = Some(first_schema.clone());
                            }
                        } else {
                            unified_schema = Some(first_schema.clone());
                        }
                    } else if config.unify_maps {
                        // Detect if these are all arrays of records
                        if child_schemas
                            .iter()
                            .all(|s| s.get("type") == Some(&Value::String("array".into())))
                        {
                            // Collect item schemas, short-circuit if any missing
                            let mut item_schemas = Vec::with_capacity(child_schemas.len());
                            let mut all_items_ok = true;
                            for s in &child_schemas {
                                if let Some(items) = s.get("items") {
                                    item_schemas.push(items.clone());
                                } else {
                                    all_items_ok = false;
                                    break;
                                }
                            }
                            if all_items_ok {
                                if let Some(unified_items) = check_unifiable_schemas(
                                    &item_schemas,
                                    field_name.unwrap_or(""),
                                    config,
                                ) {
                                    unified_schema = Some(serde_json::json!({
                                        "type": "array",
                                        "items": unified_items
                                    }));
                                }
                            }
                        } else {
                            unified_schema = check_unifiable_schemas(
                                &child_schemas,
                                field_name.unwrap_or(""),
                                config,
                            );
                        }
                    }
                }

                // Apply map inference logic
                let should_be_map = if above_threshold && unified_schema.is_some() {
                    if let Some(max_required) = config.map_max_required_keys {
                        required_key_count <= max_required
                    } else {
                        true
                    }
                } else {
                    false
                };

                if should_be_map {
                    if let Some(schema) = unified_schema {
                        obj.remove("properties");
                        obj.remove("required");
                        obj.insert("type".to_string(), Value::String("object".to_string()));
                        obj.insert("additionalProperties".to_string(), schema);
                        return;
                    }
                }
            }

            // --- Recurse into nested values ---
            if let Some(props) = obj.get_mut("properties").and_then(|p| p.as_object_mut()) {
                for (k, v) in props {
                    rewrite_objects(v, Some(k), config);
                }
            }
            if let Some(items) = obj.get_mut("items") {
                rewrite_objects(items, None, config);
            }
            for v in obj.values_mut() {
                rewrite_objects(v, None, config);
            }
        } else if let Value::Array(arr) = schema {
            for v in arr {
                rewrite_objects(v, None, config);
            }
        }
    }

    /// Recursively reorder union type arrays in a JSON Schema by canonical precedence.
    ///
    /// Special case: preserves the common `["null", T]` pattern without reordering.
    pub fn reorder_unions(schema: &mut Value) {
        match schema {
            Value::Object(obj) => {
                if let Some(Value::Array(types)) = obj.get_mut("type") {
                    // sort by canonical precedence, but keep ["null", T] pattern intact
                    if !(types.len() == 2 && types.iter().any(|t| t == "null")) {
                        types.sort_by_key(type_rank);
                    }
                }
                // recurse into properties/items/etc.
                for v in obj.values_mut() {
                    reorder_unions(v);
                }
            }
            Value::Array(arr) => {
                for v in arr {
                    reorder_unions(v);
                }
            }
            _ => {}
        }
    }

    /// Assign a numeric precedence rank to a JSON Schema type.
    ///
    /// Used by `reorder_unions` to sort union members deterministically.
    /// - Null always first
    /// - Containers before scalars (to enforce widening)
    /// - Scalars ordered by narrowness
    /// - Unknown types last
    pub fn type_rank(val: &Value) -> usize {
        match val {
            Value::String(s) => type_string_rank(s),
            Value::Object(obj) => {
                if let Some(Value::String(t)) = obj.get("type") {
                    type_string_rank(t)
                } else {
                    100 // object with no "type" field
                }
            }
            _ => 100, // non-string/non-object
        }
    }

    /// Internal helper: rank by type string
    fn type_string_rank(s: &str) -> usize {
        match s {
            // Null always first
            "null" => 0,

            // Containers before scalars: widening takes precedence
            "map" => 1,
            "array" => 2,
            "object" | "record" => 3,

            // Scalars (ordered by 'narrowness')
            "boolean" => 10,
            "integer" | "int" | "long" => 11,
            "number" | "float" | "double" => 12,
            "enum" => 13,
            "string" => 14,
            "fixed" => 15,
            "bytes" => 16,

            // Fallback
            _ => 99,
        }
    }

    /// Infer JSON schema from a collection of JSON strings
    pub fn infer_json_schema_from_strings(
        json_strings: &[String],
        config: SchemaInferenceConfig,
    ) -> Result<SchemaInferenceResult, String> {
        debug!(config, "Schema inference config: {:#?}", config);
        if json_strings.is_empty() {
            return Err("No JSON strings provided".to_string());
        }

        // Wrap the entire genson-rs interaction in panic handling
        let result = panic::catch_unwind(AssertUnwindSafe(
            || -> Result<SchemaInferenceResult, String> {
                // Create schema builder
                let mut builder = get_builder(config.schema_uri.as_deref());

                // Build config for genson-rs
                let build_config = BuildConfig {
                    delimiter: config.delimiter,
                    ignore_outer_array: config.ignore_outer_array,
                };

                let mut processed_count = 0;

                // Process each JSON string
                for (i, json_str) in json_strings.iter().enumerate() {
                    if json_str.trim().is_empty() {
                        continue;
                    }

                    // Choose validation strategy based on delimiter
                    let validation_result = if let Some(delim) = config.delimiter {
                        if delim == b'\n' {
                            validate_ndjson(json_str)
                        } else {
                            Err(serde_json::Error::custom(format!(
                                "Unsupported delimiter: {:?}",
                                delim
                            )))
                        }
                    } else {
                        validate_json(json_str)
                    };

                    if let Err(parse_error) = validation_result {
                        let truncated_json = if json_str.len() > MAX_JSON_ERROR_LENGTH {
                            format!(
                                "{}... [truncated {} chars]",
                                &json_str[..MAX_JSON_ERROR_LENGTH],
                                json_str.len() - MAX_JSON_ERROR_LENGTH
                            )
                        } else {
                            json_str.clone()
                        };

                        return Err(format!(
                            "Invalid JSON input at index {}: {} - JSON: {}",
                            i + 1,
                            parse_error,
                            truncated_json
                        ));
                    }

                    // Safe: JSON is valid, now hand off to genson-rs
                    let prepared_json: Cow<str> = if let Some(ref field) = config.wrap_root {
                        if config.delimiter == Some(b'\n') {
                            // NDJSON: wrap each line separately
                            let mut wrapped_lines = Vec::new();
                            for line in json_str.lines() {
                                let trimmed = line.trim();
                                if trimmed.is_empty() {
                                    continue;
                                }
                                let inner_val: Value =
                                    serde_json::from_str(trimmed).map_err(|e| {
                                        format!(
                                            "Failed to parse NDJSON line before wrap_root: {}",
                                            e
                                        )
                                    })?;
                                wrapped_lines
                                    .push(serde_json::json!({ field: inner_val }).to_string());
                            }
                            Cow::Owned(wrapped_lines.join("\n"))
                        } else {
                            // Single JSON doc
                            let inner_val: Value = serde_json::from_str(json_str).map_err(|e| {
                                format!("Failed to parse JSON before wrap_root: {}", e)
                            })?;
                            Cow::Owned(serde_json::json!({ field: inner_val }).to_string())
                        }
                    } else {
                        Cow::Borrowed(json_str)
                    };

                    let mut bytes = prepared_json.as_bytes().to_vec();

                    // Build schema incrementally - this is where panics happen
                    let _schema = build_json_schema(&mut builder, &mut bytes, &build_config);
                    processed_count += 1;
                }

                // Get final schema
                let mut final_schema = builder.to_schema();
                rewrite_objects(&mut final_schema, None, &config);
                reorder_unions(&mut final_schema);

                #[cfg(feature = "avro")]
                if config.avro {
                    let avro_schema = SchemaInferenceResult {
                        schema: final_schema.clone(),
                        processed_count,
                    }
                    .to_avro_schema(
                        "genson", // namespace
                        Some(""),
                        Some(""), // base_uri
                        false,    // don't split top-level
                    );
                    return Ok(SchemaInferenceResult {
                        schema: avro_schema,
                        processed_count,
                    });
                }

                Ok(SchemaInferenceResult {
                    schema: final_schema,
                    processed_count,
                })
            },
        ));

        // Handle the result of panic::catch_unwind
        match result {
            Ok(Ok(schema_result)) => Ok(schema_result),
            Ok(Err(e)) => Err(e),
            Err(_panic) => {
                Err("JSON schema inference failed due to invalid JSON input".to_string())
            }
        }
    }

    #[cfg(test)]
    mod tests {
        use super::*;
        use predicates::prelude::*;
        use serde_json::json;

        #[test]
        fn test_reorder_unions_string_float_null() {
            // Unordered union: string, float, null
            let mut schema = json!({
                "type": ["string", "float", "null"]
            });

            reorder_unions(&mut schema);

            // After reordering, null should come first, then float/number, then string
            assert_eq!(
                schema,
                json!({
                    "type": ["null", "float", "string"]
                })
            );
        }

        #[test]
        fn test_basic_schema_inference() {
            let json_strings = vec![
                r#"{"name": "Alice", "age": 30}"#.to_string(),
                r#"{"name": "Bob", "age": 25, "city": "NYC"}"#.to_string(),
            ];

            let result =
                infer_json_schema_from_strings(&json_strings, SchemaInferenceConfig::default())
                    .expect("Schema inference should succeed");

            // Test processed count
            assert_eq!(result.processed_count, 2);

            // Use predicates to test schema structure
            let schema_str = result.schema.to_string();

            predicate::str::contains("\"type\"")
                .and(predicate::str::contains("object"))
                .eval(&schema_str);

            predicate::str::contains("\"properties\"").eval(&schema_str);

            // Check that both name and age properties are present
            predicate::str::contains("\"name\"")
                .and(predicate::str::contains("\"age\""))
                .eval(&schema_str);

            println!(
                "✅ Generated schema: {}",
                serde_json::to_string_pretty(&result.schema).unwrap()
            );
        }

        #[test]
        fn test_empty_input() {
            let json_strings = vec![];
            let result =
                infer_json_schema_from_strings(&json_strings, SchemaInferenceConfig::default());

            assert!(result.is_err());

            let error_msg = result.unwrap_err();
            predicate::str::contains("No JSON strings provided").eval(&error_msg);

            println!("✅ Empty input correctly rejected with: {}", error_msg);
        }

        #[test]
        fn test_invalid_json_variants() {
            let test_cases = vec![
                (
                    r#"{"name": "Alice"}"#,
                    r#"{"invalid": json}"#,
                    "unquoted value",
                ),
                (
                    r#"{"valid": "json"}"#,
                    r#"{"incomplete":"#,
                    "incomplete string",
                ),
                (r#"{"good": "data"}"#, r#"{"trailing":,"#, "trailing comma"),
                (
                    r#"{"working": true}"#,
                    r#"{invalid: "json"}"#,
                    "unquoted key",
                ),
                (
                    r#"{"normal": "object"}"#,
                    r#"{"nested": {"broken": json}}"#,
                    "nested broken JSON",
                ),
            ];

            for (valid_json, invalid_json, description) in test_cases {
                println!("🧪 Testing: {}", description);
                println!("   Valid JSON: {}", valid_json);
                println!("   Invalid JSON: {}", invalid_json);

                let json_strings = vec![valid_json.to_string(), invalid_json.to_string()];

                let result =
                    infer_json_schema_from_strings(&json_strings, SchemaInferenceConfig::default());

                // Should return an error instead of panicking
                assert!(result.is_err(), "Expected error for case: {}", description);

                let error_msg = result.unwrap_err();

                // Use predicates to verify error message content
                predicate::str::contains("Invalid JSON input at position").eval(&error_msg);

                // For short JSON strings, verify the content is included
                if invalid_json.len() <= MAX_JSON_ERROR_LENGTH {
                    predicate::str::contains(invalid_json).eval(&error_msg);
                } else {
                    // For long JSON, just check that truncation happened
                    predicate::str::contains("truncated").eval(&error_msg);
                }

                // Ensure we don't have panic-related messages
                predicate::str::contains("panicked").not().eval(&error_msg);

                predicate::str::contains("SIGABRT").not().eval(&error_msg);

                println!("   ❌ Correctly failed with: {}", error_msg);
                println!();
            }
        }

        #[test]
        fn test_mixed_valid_and_empty_strings() {
            let json_strings = vec![
                r#"{"name": "Alice", "age": 30}"#.to_string(),
                "".to_string(),    // Empty string should be skipped
                "   ".to_string(), // Whitespace-only should be skipped
                r#"{"name": "Bob", "age": 25}"#.to_string(),
            ];

            let result =
                infer_json_schema_from_strings(&json_strings, SchemaInferenceConfig::default())
                    .expect("Should succeed with valid JSON, skipping empty strings");

            // Should process only the 2 valid JSON strings
            assert_eq!(result.processed_count, 2);

            let schema_str = result.schema.to_string();
            predicate::str::contains("\"name\"")
                .and(predicate::str::contains("\"age\""))
                .eval(&schema_str);

            println!(
                "✅ Processed {} valid strings, skipped empty ones",
                result.processed_count
            );
        }

        #[test]
        fn test_schema_config_variations() {
            let json_strings = vec![r#"[{"item": "first"}, {"item": "second"}]"#.to_string()];

            // Test with ignore_outer_array = false
            let config_array = SchemaInferenceConfig {
                ignore_outer_array: false,
                ..Default::default()
            };

            let result = infer_json_schema_from_strings(&json_strings, config_array)
                .expect("Should handle array schema");

            let schema_str = result.schema.to_string();
            predicate::str::contains("\"type\"")
                .and(predicate::str::contains("array"))
                .eval(&schema_str);

            println!(
                "✅ Array schema: {}",
                serde_json::to_string_pretty(&result.schema).unwrap()
            );

            // Test with ignore_outer_array = true (default)
            let config_object = SchemaInferenceConfig {
                ignore_outer_array: true,
                ..Default::default()
            };

            let result = infer_json_schema_from_strings(&json_strings, config_object)
                .expect("Should handle object schema from array items");

            let schema_str = result.schema.to_string();
            predicate::str::contains("\"type\"")
                .and(predicate::str::contains("object"))
                .eval(&schema_str);

            predicate::str::contains("\"item\"").eval(&schema_str);

            println!(
                "✅ Object schema from array items: {}",
                serde_json::to_string_pretty(&result.schema).unwrap()
            );
        }

        #[test]
        fn test_very_long_invalid_json() {
            // Create a very long invalid JSON string
            let long_value = "x".repeat(500); // 500 char string
            let long_invalid_json = format!(
                r#"{{"field1": "{}", "field2": "{}", "field3": "{}", "field4": "{}", "invalid_syntax": }}"#,
                long_value, long_value, long_value, long_value
            );

            let json_strings = vec![
                r#"{"valid": "json"}"#.to_string(),
                long_invalid_json.clone(),
            ];

            println!(
                "🧪 Testing very long invalid JSON ({} chars)",
                long_invalid_json.len()
            );

            let result =
                infer_json_schema_from_strings(&json_strings, SchemaInferenceConfig::default());

            assert!(result.is_err(), "Expected error for very long invalid JSON");

            let error_msg = result.unwrap_err();

            println!("The error message was: {}", error_msg);

            // Should contain truncation indicator
            predicate::str::contains("truncated").eval(&error_msg);

            // Should contain position information
            predicate::str::contains("Invalid JSON input at position 2").eval(&error_msg);

            // Error message should be reasonable length (much shorter than original JSON)
            assert!(
                error_msg.len() < long_invalid_json.len() / 2,
                "Error message should be much shorter than original JSON"
            );

            println!(
                "   ❌ Correctly truncated long JSON in error: {}",
                error_msg
            );

            // Verify the error message doesn't exceed a reasonable length
            assert!(
                error_msg.len() < 500,
                "Error message should be under 500 chars, got: {}",
                error_msg.len()
            );
        }

        #[test]
        fn test_complex_nested_schema() {
            let json_strings = vec![
                json!({
                    "user": {
                        "id": 123,
                        "profile": {
                            "name": "Alice",
                            "preferences": ["dark_mode", "notifications"]
                        }
                    },
                    "metadata": {
                        "created_at": "2024-01-01",
                        "version": 1
                    }
                })
                .to_string(),
                json!({
                    "user": {
                        "id": 456,
                        "profile": {
                            "name": "Bob",
                            "preferences": ["light_mode"]
                        }
                    },
                    "metadata": {
                        "created_at": "2024-01-02",
                        "version": 2
                    }
                })
                .to_string(),
            ];

            let result =
                infer_json_schema_from_strings(&json_strings, SchemaInferenceConfig::default())
                    .expect("Should handle complex nested schema");

            assert_eq!(result.processed_count, 2);

            let schema_str = result.schema.to_string();

            // Check for nested structure
            predicate::str::contains("\"user\"")
                .and(predicate::str::contains("\"metadata\""))
                .and(predicate::str::contains("\"profile\""))
                .and(predicate::str::contains("\"preferences\""))
                .eval(&schema_str);

            println!("✅ Complex nested schema generated successfully");
            println!(
                "Schema: {}",
                serde_json::to_string_pretty(&result.schema).unwrap()
            );
        }

        #[test]
        fn test_ndjson_parsing() {
            // Two valid JSON objects separated by newlines (NDJSON format)
            let ndjson_input = r#"
{"name": "Alice", "age": 30}
{"name": "Bob", "age": 25, "city": "NYC"}
{"name": "Charlie"}
"#;

            let json_strings = vec![ndjson_input.to_string()];

            let config = SchemaInferenceConfig {
                delimiter: Some(b'\n'),
                ..Default::default()
            };

            let result = infer_json_schema_from_strings(&json_strings, config)
                .expect("NDJSON schema inference should succeed");

            // All 3 objects should be processed
            assert_eq!(result.processed_count, 1,
            "NDJSON should be counted as a single input string but parsed into multiple rows internally"
        );

            let schema_str = result.schema.to_string();

            // The schema should include properties from all lines
            assert!(!schema_str.contains("Alice")); // values are not in schema
            assert!(schema_str.contains("\"name\""));
            assert!(schema_str.contains("\"age\""));
            assert!(schema_str.contains("\"city\""));

            println!(
                "✅ NDJSON schema generated: {}",
                serde_json::to_string_pretty(&result.schema).unwrap()
            );
        }

        #[test]
        fn test_invalid_ndjson_line() {
            // Second line is malformed
            let ndjson_input = r#"
{"valid": true}
{"invalid": json}
{"also_valid": 123}
"#;

            let json_strings = vec![ndjson_input.to_string()];

            let config = SchemaInferenceConfig {
                delimiter: Some(b'\n'),
                ..Default::default()
            };

            let result = infer_json_schema_from_strings(&json_strings, config.clone());

            assert!(result.is_err(), "Expected error for malformed NDJSON line");

            let err_msg = result.unwrap_err();
            debug!(config, "Got error: {}", err_msg);
            assert!(
                err_msg
                    .contains("Invalid JSON input at index 1: expected value at line 1 column 13"),
                "Error message should report the failing line"
            );
            println!("✅ Correctly rejected malformed NDJSON: {}", err_msg);
        }

        /// Two objects with varying keys and homogeneous string values (low map threshold)
        #[test]
        fn test_map_threshold_rewrite() {
            let json_strings = vec![
                r#"{"labels": {"en": "Hello", "fr": "Bonjour"}}"#.to_string(),
                r#"{"labels": {"de": "Hallo", "es": "Hola"}}"#.to_string(),
            ];

            let config = SchemaInferenceConfig {
                map_threshold: 2,
                ..Default::default()
            };
            let result = infer_json_schema_from_strings(&json_strings, config).unwrap();

            let labels = &result.schema["properties"]["labels"];
            assert_eq!(labels["type"], "object");
            assert!(labels.get("additionalProperties").is_some());
            assert!(labels.get("properties").is_none());
        }

        /// Two objects with varying keys and homogeneous string values (default map threshold)
        #[test]
        fn test_map_threshold_as_record() {
            let json_strings = vec![
                r#"{"labels": {"en": "Hello", "fr": "Bonjour"}}"#.to_string(),
                r#"{"labels": {"de": "Hallo", "es": "Hola"}}"#.to_string(),
            ];

            let result =
                infer_json_schema_from_strings(&json_strings, SchemaInferenceConfig::default())
                    .unwrap();

            let labels = &result.schema["properties"]["labels"];
            assert!(labels.get("properties").is_some());
            assert!(labels.get("additionalProperties").is_none());
        }

        #[test]
        fn test_wrap_root_inserts_single_required_field() {
            let json_strings = vec![
                r#"{"en":{"language":"en","value":"Hello"},"fr":{"language":"fr","value":"Bonjour"}}"#.to_string(),
            ];

            let cfg = SchemaInferenceConfig {
                wrap_root: Some("labels".to_string()),
                ..Default::default()
            };

            let out = infer_json_schema_from_strings(&json_strings, cfg).unwrap();
            let sch = out.schema;

            assert_eq!(sch["type"], "object");
            assert_eq!(sch["required"], serde_json::json!(["labels"]));
            assert!(sch["properties"]["labels"].is_object());
        }

        #[test]
        fn test_rewrite_objects_map_of_records() {
            use serde_json::json;

            // Schema that genson-rs would roughly emit for {"en": {...}, "fr": {...}}
            let mut schema = json!({
                "type": "object",
                "properties": {
                    "en": {
                        "type": "object",
                        "properties": {
                            "language": { "type": "string" },
                            "value": { "type": "string" }
                        },
                        "required": ["language", "value"]
                    },
                    "fr": {
                        "type": "object",
                        "properties": {
                            "language": { "type": "string" },
                            "value": { "type": "string" }
                        },
                        "required": ["language", "value"]
                    }
                },
                "required": ["en","fr"]
            });

            let cfg = SchemaInferenceConfig {
                map_threshold: 2, // force detection at 2 keys
                ..Default::default()
            };

            rewrite_objects(&mut schema, None, &cfg);

            // After rewrite, we should have additionalProperties instead of fixed properties
            assert_eq!(schema["type"], "object");
            assert!(schema.get("properties").is_none());
            assert!(schema.get("required").is_none());

            // additionalProperties should carry the inner record shape
            let ap = schema
                .get("additionalProperties")
                .expect("should insert additionalProperties");

            assert_eq!(ap["type"], "object");
            assert_eq!(ap["properties"]["language"], json!({ "type": "string" }));
            assert_eq!(ap["properties"]["value"], json!({ "type": "string" }));
        }

        #[test]
        fn test_map_of_strings_not_promoted_to_records() {
            let schema = json!({
                "type": "object",
                "properties": {
                    "labels": {
                        "type": "object",
                        "properties": {
                            "en": { "type": "string" },
                            "fr": { "type": "string" }
                        },
                        "required": ["en", "fr"]
                    }
                },
                "required": ["labels"]
            });

            let mut sch = schema.clone();
            let cfg = SchemaInferenceConfig {
                map_threshold: 2,
                ..Default::default()
            };
            rewrite_objects(&mut sch, None, &cfg);

            assert_eq!(
                sch["properties"]["labels"]["additionalProperties"]["type"],
                "string"
            );
        }

        #[test]
        fn test_rewrite_objects_respects_map_max_required_keys() {
            let mut schema = json!({
                "type": "object",
                "properties": {
                    "field1": {"type": "string"},
                    "field2": {"type": "string"}
                },
                "required": ["field1", "field2"]
            });

            let config = SchemaInferenceConfig {
                map_threshold: 2,
                map_max_required_keys: Some(1), // Max 1 required key for maps
                ..Default::default()
            };

            rewrite_objects(&mut schema, None, &config);

            // Should remain as record because 2 required keys > 1
            assert_eq!(schema["type"], "object");
            assert!(schema.get("properties").is_some());
            assert!(schema.get("additionalProperties").is_none());
        }

        #[test]
        fn test_rewrite_objects_allows_map_with_few_required_keys() {
            let mut schema = json!({
                "type": "object",
                "properties": {
                    "field1": {"type": "string"},
                    "field2": {"type": "string"}
                },
                "required": ["field1"] // Only 1 required key
            });

            let config = SchemaInferenceConfig {
                map_threshold: 2,
                map_max_required_keys: Some(1), // Max 1 required key for maps
                ..Default::default()
            };

            rewrite_objects(&mut schema, None, &config);

            // Should become map because 1 required key ≤ 1
            assert_eq!(schema["type"], "object");
            assert!(schema.get("additionalProperties").is_some());
            assert!(schema.get("properties").is_none());
        }

        #[test]
        fn test_rewrite_objects_none_max_required_keys_preserves_behavior() {
            let mut schema = json!({
                "type": "object",
                "properties": {
                    "field1": {"type": "string"},
                    "field2": {"type": "string"},
                    "field3": {"type": "string"}
                },
                "required": ["field1", "field2", "field3"]
            });

            let config = SchemaInferenceConfig {
                map_threshold: 2,
                map_max_required_keys: None, // No gating
                ..Default::default()
            };

            rewrite_objects(&mut schema, None, &config);

            // Should become map because None means no gating (old behavior)
            assert_eq!(schema["type"], "object");
            assert!(schema.get("additionalProperties").is_some());
            assert!(schema.get("properties").is_none());
        }

        #[test]
        fn test_rewrite_objects_zero_max_required_keys() {
            let mut schema = json!({
                "type": "object",
                "properties": {
                    "field1": {"type": "string"},
                    "field2": {"type": "string"}
                },
                "required": ["field1"]
            });

            let config = SchemaInferenceConfig {
                map_threshold: 2,
                map_max_required_keys: Some(0), // Only allow maps with 0 required keys
                ..Default::default()
            };

            rewrite_objects(&mut schema, None, &config);

            // Should remain as record because 1 required key > 0
            assert_eq!(schema["type"], "object");
            assert!(schema.get("properties").is_some());
            assert!(schema.get("additionalProperties").is_none());
        }

        #[test]
        fn test_rewrite_objects_zero_required_keys_allowed() {
            let mut schema = json!({
                "type": "object",
                "properties": {
                    "field1": {"type": "string"},
                    "field2": {"type": "string"}
                }
                // No required array = 0 required keys
            });

            let config = SchemaInferenceConfig {
                map_threshold: 2,
                map_max_required_keys: Some(0), // Only allow maps with 0 required keys
                ..Default::default()
            };

            rewrite_objects(&mut schema, None, &config);

            // Should become map because 0 required keys ≤ 0
            assert_eq!(schema["type"], "object");
            assert!(schema.get("additionalProperties").is_some());
            assert!(schema.get("properties").is_none());
        }

        #[test]
        fn test_rewrite_objects_force_override_wins() {
            let mut schema = json!({
                "type": "object",
                "properties": {
                    "field1": {"type": "string"},
                    "field2": {"type": "string"}
                },
                "required": ["field1", "field2"]
            });

            let mut force_types = std::collections::HashMap::new();
            force_types.insert("test_field".to_string(), "map".to_string());

            let config = SchemaInferenceConfig {
                map_threshold: 2,
                map_max_required_keys: Some(0), // Would normally block this
                force_field_types: force_types,
                ..Default::default()
            };

            // Apply with field name that matches force override
            rewrite_objects(&mut schema, Some("test_field"), &config);

            // Should become map despite having required keys due to force override
            assert_eq!(schema["type"], "object");
            assert!(schema.get("additionalProperties").is_some());
            assert!(schema.get("properties").is_none());
        }

        #[test]
        fn test_rewrite_objects_non_homogeneous_values_not_rewritten() {
            let mut schema = json!({
                "type": "object",
                "properties": {
                    "field1": {"type": "string"},
                    "field2": {"type": "integer"} // Non-homogeneous
                },
                "required": []
            });

            let config = SchemaInferenceConfig {
                map_threshold: 2,
                map_max_required_keys: Some(5), // Would allow this
                ..Default::default()
            };

            rewrite_objects(&mut schema, None, &config);

            // Should remain as record because values are not homogeneous
            assert_eq!(schema["type"], "object");
            assert!(schema.get("properties").is_some());
            assert!(schema.get("additionalProperties").is_none());
        }

        #[test]
        fn test_rewrite_objects_below_threshold_not_rewritten() {
            let mut schema = json!({
                "type": "object",
                "properties": {
                    "field1": {"type": "string"}
                },
                "required": []
            });

            let config = SchemaInferenceConfig {
                map_threshold: 5,               // Above the key count
                map_max_required_keys: Some(5), // Would allow this
                ..Default::default()
            };

            rewrite_objects(&mut schema, None, &config);

            // Should remain as record because below threshold
            assert_eq!(schema["type"], "object");
            assert!(schema.get("properties").is_some());
            assert!(schema.get("additionalProperties").is_none());
        }

        #[test]
        fn test_map_max_required_keys_with_wrap_root() {
            let json_strings = vec![
                r#"{"en":{"language":"en","value":"Hello"},"fr":{"language":"fr","value":"Bonjour"}}"#.to_string(),
            ];

            let cfg = SchemaInferenceConfig {
                wrap_root: Some("labels".to_string()),
                map_threshold: 2,
                map_max_required_keys: Some(1), // Should allow the wrapped content
                ..Default::default()
            };

            let out = infer_json_schema_from_strings(&json_strings, cfg).unwrap();
            let sch = out.schema;

            assert_eq!(sch["type"], "object");
            assert_eq!(sch["required"], serde_json::json!(["labels"]));

            // The wrapped labels should have the map logic applied
            let labels_content = &sch["properties"]["labels"];
            assert!(labels_content.is_object());

            println!("✅ map_max_required_keys works with wrap_root");
        }

        #[test]
        fn test_wrap_scalars_in_map_of_records() {
            let json_strings = vec![
                // "root" field is a map, all map keys have a record{id,value},
                // for map keys A/B value is a record{hello} and for map key C value is a string
                // Row 1: value is an object
                r#"{"root": {"A": {"id": 1, "value": {"hello": "world"}}}}"#.to_string(),
                // Row 2: value is an object, again
                r#"{"root": {"B": {"id": 2, "value": {"hello": "foo"}}}}"#.to_string(),
                // Row 3: value is just a string
                r#"{"root": {"C": {"id": 3, "value": "bar"}}}"#.to_string(),
            ];

            let cfg = SchemaInferenceConfig {
                map_threshold: 3,
                map_max_required_keys: Some(0),
                unify_maps: true,
                wrap_scalars: true,
                ..Default::default()
            };

            let result = infer_json_schema_from_strings(&json_strings, cfg)
                .expect("Schema inference should succeed with wrap_scalars");

            let sch = result.schema;

            // Navigate to root map’s value type
            let root_additional = &sch["properties"]["root"]["additionalProperties"];
            assert_eq!(root_additional["type"], "object");

            // The "value" field should be promoted and contain both object and scalar string form
            let value_schema = &root_additional["properties"]["value"];
            assert!(value_schema.is_object());

            // Should contain the synthetic key for the wrapped scalar
            assert!(
                value_schema["properties"]
                    .as_object()
                    .unwrap()
                    .keys()
                    .any(|k| k.contains("__string")),
                "Expected synthetic scalar wrapper key inside value schema, got: {}",
                serde_json::to_string_pretty(value_schema).unwrap()
            );

            println!(
                "✅ wrap_scalars promoted scalar inside map-of-records: {}",
                serde_json::to_string_pretty(value_schema).unwrap()
            );
        }
    }
}
pub use innermod::*;