ferrolearn-preprocess 0.5.0

Preprocessing transformers for the ferrolearn ML framework
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
//! Divergence audit: `ferrolearn-preprocess` `OrdinalEncoder` vs scikit-learn
//! 1.5.2 `sklearn/preprocessing/_encoders.py::class OrdinalEncoder` (`:1235`).
//!
//! EVERY expected value below is grounded in a LIVE sklearn 1.5.2 oracle call
//! (run from /tmp) — NEVER copied from the ferrolearn side (R-CHAR-3).
//!
//! Oracle session (sklearn 1.5.2, run from /tmp):
//! ```text
//! >>> from sklearn.preprocessing import OrdinalEncoder; import numpy as np
//! >>> OrdinalEncoder().fit_transform(
//! ...   [['cat','small'],['dog','large'],['cat','medium'],['bird','small']])
//!     -> array([[1.,2.],[2.,0.],[1.,1.],[0.,2.]])   dtype float64
//! >>> .categories_  -> [['bird','cat','dog'], ['large','medium','small']]
//! >>> np.unique(['B','a','A','b','10','2']).tolist()
//!     -> ['10','2','A','B','a','b']                 # digits < upper < lower
//! >>> OrdinalEncoder().fit([['z'],['é'],['a'],['Z'],['€'],['ä']]).categories_[0]
//!     -> ['Z','a','z','ä','é','€']                  # codepoint order
//! >>> .transform([['€'],['Z'],['a']])               -> [[5.],[0.],[1.]]
//! >>> OrdinalEncoder().fit([['cat','small'],['dog','large']])
//! ...   .transform([['fish','small']])
//!     -> ValueError: Found unknown categories ['fish'] in column 0 ...
//! >>> OrdinalEncoder().fit(np.empty((0,2),dtype=object))
//!     -> ValueError: Found array with 0 sample(s) ... minimum of 1 is required.
//! >>> OrdinalEncoder().fit([['a'],['a'],['b'],['a']]).categories_[0] -> ['a','b']
//! >>> OrdinalEncoder().fit([['a','b'],['b','a']]).categories_
//!     -> [['a','b'],['a','b']]
//! >>> .transform([['a','b'],['b','a']]) -> [[0.,1.],[1.,0.]]
//! ```
//!
//! VERDICT: the String-ordinal path matches the oracle bit-for-bit on
//! categories_, ordinal values, sort order (incl. non-ASCII), duplicate folding,
//! multi-column independence, single-row fit, unknown-category rejection, and
//! empty-fit rejection. These are GREEN guards (verify-and-document). REQ-3 (the
//! output container dtype) is now SHIPPED: `transform`/`fit_transform` return
//! `Array2<f64>`, matching sklearn's `dtype=np.float64` default (`:1262`), so the
//! oracle f64 VALUES are asserted directly over an `f64` container (a compile-time
//! type guarantee + a value check). The CONFIGURABLE non-float64 `dtype` ctor
//! param remains a follow-on (blocker #1158).
//!
//! Additional live oracle (sklearn 1.5.2, run from /tmp):
//! ```text
//! >>> from sklearn.preprocessing import OrdinalEncoder
//! >>> o = OrdinalEncoder().fit_transform(
//! ...   [['bird','large'],['dog','small'],['cat','medium'],['bird','small']])
//! >>> o.tolist(); o.dtype
//!     -> [[0.,0.],[2.,2.],[1.,1.],[0.,2.]]   float64
//! >>> cats=['b00','b01','b02','b03','b04','b05','b06','b07','b08','b09','b10']
//! >>> e=OrdinalEncoder().fit([[c] for c in cats])
//! >>> e.transform([['b10']]).tolist(); e.transform([['b10']]).dtype
//!     -> [[10.0]]   float64        # lex index 10 -> exact 10.0
//! ```

use ferrolearn_core::traits::{Fit, FitTransform, Transform};
use ferrolearn_preprocess::{HandleUnknown, OrdinalEncoder};
use ndarray::Array2;

/// Helper to build the `Vec<Vec<String>>` for explicit `with_categories`.
fn cats(lists: &[&[&str]]) -> Vec<Vec<String>> {
    lists
        .iter()
        .map(|l| l.iter().map(std::string::ToString::to_string).collect())
        .collect()
}

/// Build an `n x 2` string array from `(col0, col1)` row tuples.
fn make_2col(rows: &[(&str, &str)]) -> Array2<String> {
    let flat: Vec<String> = rows
        .iter()
        .flat_map(|(a, b)| [a.to_string(), b.to_string()])
        .collect();
    Array2::from_shape_vec((rows.len(), 2), flat).unwrap()
}

/// Build an `n x 1` string column.
fn make_1col(vals: &[&str]) -> Array2<String> {
    Array2::from_shape_vec(
        (vals.len(), 1),
        vals.iter().map(std::string::ToString::to_string).collect(),
    )
    .unwrap()
}

// ===========================================================================
// GREEN GUARD 1 (REQ-1 / REQ-2) — ordinal VALUES + categories_ match oracle.
//
// LIVE oracle (sklearn 1.5.2):
//   fit_transform([['cat','small'],['dog','large'],['cat','medium'],
//                  ['bird','small']])
//     -> [[1.,2.],[2.,0.],[1.,1.],[0.,2.]]
//   categories_ -> [['bird','cat','dog'], ['large','medium','small']]
// sklearn `_encoders.py:99` `result = _unique(Xi)` (sorted unique); the output
// dtype is float64 (`:1262`). R-CHAR-3: expected values are the live-oracle
// float64 outputs, not ferrolearn literals.
// ===========================================================================
#[test]
fn green_value_match_and_categories() {
    // Expected from the LIVE sklearn oracle (see header) — float64 values.
    let sk_values: [[f64; 2]; 4] = [[1., 2.], [2., 0.], [1., 1.], [0., 2.]];
    let sk_cat0 = ["bird", "cat", "dog"];
    let sk_cat1 = ["large", "medium", "small"];

    let enc = OrdinalEncoder::new();
    let x = make_2col(&[
        ("cat", "small"),
        ("dog", "large"),
        ("cat", "medium"),
        ("bird", "small"),
    ]);
    let fitted = enc.fit(&x, &()).unwrap();

    assert_eq!(fitted.categories()[0], sk_cat0, "categories_[0] (col 0)");
    assert_eq!(fitted.categories()[1], sk_cat1, "categories_[1] (col 1)");

    // Output is now `Array2<f64>` (REQ-3, sklearn `dtype=np.float64`).
    let encoded: ndarray::Array2<f64> = fitted.transform(&x).unwrap();
    for (i, row) in sk_values.iter().enumerate() {
        for (j, &expect) in row.iter().enumerate() {
            assert_eq!(
                encoded[[i, j]],
                expect,
                "ordinal value at [{i},{j}] vs sklearn float64 oracle"
            );
        }
    }
}

// ===========================================================================
// GREEN GUARD 2 (REQ-1) — lexicographic String::sort == np.unique on a mixed
// ASCII column.
//
// LIVE oracle: np.unique(['B','a','A','b','10','2']).tolist()
//   -> ['10','2','A','B','a','b']   (digits < uppercase < lowercase)
// sklearn `_encoders.py:99` `_unique(Xi)`; Rust `String::sort` is UTF-8 byte
// order == codepoint order == numpy's order on this column.
// ===========================================================================
#[test]
fn green_lexicographic_sort_matches_np_unique() {
    // Expected from LIVE np.unique oracle (numpy str_ dtype).
    let sk_sorted = ["10", "2", "A", "B", "a", "b"];

    let enc = OrdinalEncoder::new();
    let x = make_1col(&["B", "a", "A", "b", "10", "2"]);
    let fitted = enc.fit(&x, &()).unwrap();

    assert_eq!(
        fitted.categories()[0],
        sk_sorted,
        "categories_[0] sort order vs np.unique"
    );
}

// ===========================================================================
// GREEN GUARD 3 (REQ-1) — non-ASCII / multibyte codepoint order matches the
// LIVE encoder oracle (not just np.unique on str_, but OrdinalEncoder itself).
//
// LIVE oracle:
//   OrdinalEncoder().fit([['z'],['é'],['a'],['Z'],['€'],['ä']]).categories_[0]
//     -> ['Z','a','z','ä','é','€']
//   .transform([['€'],['Z'],['a']]) -> [[5.],[0.],[1.]]
// ===========================================================================
#[test]
fn green_non_ascii_codepoint_order() {
    let sk_cats = ["Z", "a", "z", "ä", "é", ""];
    let sk_tf: [f64; 3] = [5., 0., 1.]; // for €, Z, a (oracle float64)

    let enc = OrdinalEncoder::new();
    let x = make_1col(&["z", "é", "a", "Z", "", "ä"]);
    let fitted = enc.fit(&x, &()).unwrap();
    assert_eq!(
        fitted.categories()[0],
        sk_cats,
        "non-ASCII categories_ vs live OrdinalEncoder oracle"
    );

    let probe = make_1col(&["", "Z", "a"]);
    let out = fitted.transform(&probe).unwrap();
    for (i, &expect) in sk_tf.iter().enumerate() {
        assert_eq!(out[[i, 0]], expect, "non-ASCII ordinal at [{i},0]");
    }
}

// ===========================================================================
// GREEN GUARD 4 (REQ-2) — unknown category rejected, matching sklearn's
// default handle_unknown='error'.
//
// LIVE oracle:
//   OrdinalEncoder().fit([['cat','small'],['dog','large']])
//     .transform([['fish','small']])
//   -> ValueError: Found unknown categories ['fish'] in column 0 during transform
// Both sides REJECT (green guard); the message nuance (R-DEV-2) is NOT pinned.
// ===========================================================================
#[test]
fn green_unknown_category_rejected() {
    let enc = OrdinalEncoder::new();
    let x_train = make_2col(&[("cat", "small"), ("dog", "large")]);
    let fitted = enc.fit(&x_train, &()).unwrap();
    let x_test = make_2col(&[("fish", "small")]);
    assert!(
        fitted.transform(&x_test).is_err(),
        "sklearn raises ValueError on unknown 'fish'; ferrolearn must Err too"
    );
}

// ===========================================================================
// GREEN GUARD 5 (REQ-1) — empty-fit rejection MATCHES sklearn.
//
// LIVE oracle:
//   OrdinalEncoder().fit(np.empty((0,2),dtype=object))
//   -> ValueError: Found array with 0 sample(s) (shape=(0,2)) while a minimum
//      of 1 is required.
// Unlike LabelEncoder (which ALLOWS empty fit -> a pinned divergence),
// OrdinalEncoder REJECTS 0 samples via check_array. ferrolearn's
// InsufficientSamples therefore MATCHES — no divergence to pin here.
// ===========================================================================
#[test]
fn green_empty_fit_rejected_matches_sklearn() {
    let enc = OrdinalEncoder::new();
    let x: Array2<String> = Array2::from_shape_vec((0, 2), vec![]).unwrap();
    assert!(
        enc.fit(&x, &()).is_err(),
        "sklearn raises ValueError on 0-sample fit; ferrolearn must Err too"
    );
}

// ===========================================================================
// GREEN GUARD 6 (REQ-2) — fit_transform == fit then transform (oracle-anchored
// to the Probe-1 values so it is not a pure self-equality tautology).
//
// LIVE oracle: fit_transform of the Probe-1 matrix -> [[1.,2.],[2.,0.],
//   [1.,1.],[0.,2.]]. We assert both fit_transform AND separate fit+transform
//   equal that oracle matrix (R-CHAR-3: anchored to live values, not to each
//   other).
// ===========================================================================
#[test]
fn green_fit_transform_equals_oracle() {
    let sk_values: [[f64; 2]; 4] = [[1., 2.], [2., 0.], [1., 1.], [0., 2.]];
    let expected: Array2<f64> = Array2::from_shape_vec(
        (4, 2),
        sk_values.iter().flat_map(|r| r.iter().copied()).collect(),
    )
    .unwrap();

    let enc = OrdinalEncoder::new();
    let x = make_2col(&[
        ("cat", "small"),
        ("dog", "large"),
        ("cat", "medium"),
        ("bird", "small"),
    ]);

    let via_ft = enc.fit_transform(&x).unwrap();
    let via_sep = enc.fit(&x, &()).unwrap().transform(&x).unwrap();

    assert_eq!(via_ft, expected, "fit_transform vs live oracle values");
    assert_eq!(via_sep, expected, "fit+transform vs live oracle values");
    assert_eq!(via_ft, via_sep, "fit_transform == fit then transform");
}

// ===========================================================================
// GREEN GUARD 7 (REQ-1/REQ-2) — duplicate folding, multi-column independence,
// single-row fit all match the LIVE encoder oracle.
//
// LIVE oracle:
//   fit([['a'],['a'],['b'],['a']]).categories_[0]      -> ['a','b']
//   fit([['a','b'],['b','a']]).categories_             -> [['a','b'],['a','b']]
//   .transform([['a','b'],['b','a']])                  -> [[0.,1.],[1.,0.]]
//   fit([['solo','x']]).categories_                    -> [['solo'],['x']]
// ===========================================================================
#[test]
fn green_duplicates_independence_single_row() {
    // Duplicate folding.
    let enc = OrdinalEncoder::new();
    let dup = make_1col(&["a", "a", "b", "a"]);
    let fitted = enc.fit(&dup, &()).unwrap();
    assert_eq!(fitted.categories()[0], ["a", "b"], "dup categories_");

    // Multi-column independence: same strings, two columns, identical sorted set.
    let indep = make_2col(&[("a", "b"), ("b", "a")]);
    let fitted = enc.fit(&indep, &()).unwrap();
    assert_eq!(fitted.categories()[0], ["a", "b"], "indep col0");
    assert_eq!(fitted.categories()[1], ["a", "b"], "indep col1");
    let out = fitted.transform(&indep).unwrap();
    // Oracle: [[0.,1.],[1.,0.]] (float64)
    assert_eq!(out[[0, 0]], 0.0);
    assert_eq!(out[[0, 1]], 1.0);
    assert_eq!(out[[1, 0]], 1.0);
    assert_eq!(out[[1, 1]], 0.0);

    // Single-row fit.
    let single = make_2col(&[("solo", "x")]);
    let fitted = enc.fit(&single, &()).unwrap();
    assert_eq!(fitted.categories()[0], ["solo"], "single-row col0");
    assert_eq!(fitted.categories()[1], ["x"], "single-row col1");
}

// ===========================================================================
// GREEN GUARD 8 (REQ-3) — output container dtype is float64, value-EXACT to the
// live oracle's float64 matrix over an `Array2<f64>` (type guarantee + values).
//
// LIVE oracle (sklearn 1.5.2, run from /tmp):
//   OrdinalEncoder().fit_transform(
//     [['bird','large'],['dog','small'],['cat','medium'],['bird','small']])
//   -> [[0.,0.],[2.,2.],[1.,1.],[0.,2.]]   dtype float64
//   (col0 cats ['bird','cat','dog']; col1 cats ['large','medium','small'])
// The `Array2<f64>` binding is a COMPILE-TIME proof of REQ-3 (the output is no
// longer `Array2<usize>`); the value asserts match the oracle bit-for-bit.
// ===========================================================================
#[test]
fn green_fit_transform_f64_oracle() {
    // Expected from the LIVE sklearn oracle (see header) — float64.
    let sk: [[f64; 2]; 4] = [[0., 0.], [2., 2.], [1., 1.], [0., 2.]];

    let enc = OrdinalEncoder::new();
    let x = make_2col(&[
        ("bird", "large"),
        ("dog", "small"),
        ("cat", "medium"),
        ("bird", "small"),
    ]);

    // Explicit `Array2<f64>` type annotation: REQ-3 compile-time guarantee that
    // the output container is float64, matching sklearn `dtype=np.float64`.
    let encoded: Array2<f64> = enc.fit_transform(&x).unwrap();
    assert_eq!(encoded.dim(), (4, 2), "shape vs oracle");
    for (i, row) in sk.iter().enumerate() {
        for (j, &expect) in row.iter().enumerate() {
            assert_eq!(
                encoded[[i, j]],
                expect,
                "f64 ordinal at [{i},{j}] vs oracle"
            );
        }
    }
}

// ===========================================================================
// GREEN GUARD 9 (REQ-3) — a large ordinal index casts to an EXACT f64
// (lossless, sklearn float64). Index 10 -> 10.0.
//
// LIVE oracle (sklearn 1.5.2, run from /tmp):
//   cats=['b00','b01','b02','b03','b04','b05','b06','b07','b08','b09','b10']
//   e=OrdinalEncoder().fit([[c] for c in cats])
//   e.transform([['b10']]) -> [[10.0]]  dtype float64   (lex index 10)
// ===========================================================================
#[test]
fn green_exact_integer_index_to_f64() {
    let cats = [
        "b00", "b01", "b02", "b03", "b04", "b05", "b06", "b07", "b08", "b09", "b10",
    ];
    let enc = OrdinalEncoder::new();
    let x = make_1col(&cats);
    let fitted = enc.fit(&x, &()).unwrap();
    // Lexicographic order keeps b00..b10 already sorted -> b10 is index 10.
    assert_eq!(fitted.categories()[0][10], "b10", "lex index 10 is b10");

    let probe = make_1col(&["b10"]);
    let out: Array2<f64> = fitted.transform(&probe).unwrap();
    // Oracle: [[10.0]]. f64 represents 10 exactly.
    assert_eq!(out[[0, 0]], 10.0, "index 10 -> exact 10.0 (lossless f64)");
}

// ===========================================================================
// REQ-5 — handle_unknown='use_encoded_value' + unknown_value.
//
// EVERY expected value below comes from a LIVE sklearn 1.5.2 oracle (R-CHAR-3),
// reproduced via the `python3 -c` command cited above each test.
// ===========================================================================

// ---------------------------------------------------------------------------
// GREEN GUARD 10 (REQ-5) — use_encoded_value with unknown_value=-1.0: unknown
// categories -> -1.0, seen categories -> their ordinal index.
//
// LIVE oracle (sklearn 1.5.2, run from /tmp):
//   python3 -c "from sklearn.preprocessing import OrdinalEncoder; \
//     e=OrdinalEncoder(handle_unknown='use_encoded_value',unknown_value=-1)\
//       .fit([['cat'],['dog'],['cat']]); \
//     print(e.transform([['bird'],['dog']]).tolist())"
//   -> [[-1.0], [1.0]]
// (categories_[0]=['cat','dog']; 'bird' unknown -> -1.0; 'dog' -> index 1.)
// ---------------------------------------------------------------------------
#[test]
fn green_use_encoded_value_minus_one() {
    let sk: [f64; 2] = [-1.0, 1.0]; // 'bird' (unknown), 'dog' (index 1)

    let enc = OrdinalEncoder::new()
        .with_handle_unknown(HandleUnknown::UseEncodedValue)
        .with_unknown_value(-1.0);
    let x_train = make_1col(&["cat", "dog", "cat"]);
    let fitted = enc.fit(&x_train, &()).unwrap();

    let probe = make_1col(&["bird", "dog"]);
    let out: Array2<f64> = fitted.transform(&probe).unwrap();
    assert_eq!(out[[0, 0]], sk[0], "unknown 'bird' -> -1.0 (oracle)");
    assert_eq!(out[[1, 0]], sk[1], "seen 'dog' -> 1.0 (oracle)");
}

// ---------------------------------------------------------------------------
// GREEN GUARD 11 (REQ-5) — multi-feature use_encoded_value, unknown_value=-1.0.
//
// LIVE oracle (sklearn 1.5.2, run from /tmp):
//   python3 -c "from sklearn.preprocessing import OrdinalEncoder; \
//     e=OrdinalEncoder(handle_unknown='use_encoded_value',unknown_value=-1)\
//       .fit([['cat','x'],['dog','y'],['cat','x']]); \
//     print(e.transform([['bird','z'],['dog','x']]).tolist())"
//   -> [[-1.0, -1.0], [1.0, 0.0]]
// (col0 cats ['cat','dog']; col1 cats ['x','y']; 'bird'/'z' unknown -> -1.0;
//  'dog'->1, 'x'->0.)
// ---------------------------------------------------------------------------
#[test]
fn green_use_encoded_value_multifeature() {
    let sk: [[f64; 2]; 2] = [[-1.0, -1.0], [1.0, 0.0]];

    let enc = OrdinalEncoder::new()
        .with_handle_unknown(HandleUnknown::UseEncodedValue)
        .with_unknown_value(-1.0);
    let x_train = make_2col(&[("cat", "x"), ("dog", "y"), ("cat", "x")]);
    let fitted = enc.fit(&x_train, &()).unwrap();

    let probe = make_2col(&[("bird", "z"), ("dog", "x")]);
    let out: Array2<f64> = fitted.transform(&probe).unwrap();
    for (i, row) in sk.iter().enumerate() {
        for (j, &expect) in row.iter().enumerate() {
            assert_eq!(out[[i, j]], expect, "multi-feature uev at [{i},{j}]");
        }
    }
}

// ---------------------------------------------------------------------------
// GREEN GUARD 12 (REQ-5) — use_encoded_value with unknown_value=nan: unknown
// categories -> NaN, seen categories -> their ordinal index.
//
// LIVE oracle (sklearn 1.5.2, run from /tmp):
//   python3 -c "import numpy as np; from sklearn.preprocessing import \
//     OrdinalEncoder; e=OrdinalEncoder(handle_unknown='use_encoded_value',\
//     unknown_value=np.nan).fit([['cat'],['dog'],['cat']]); \
//     print(e.transform([['bird'],['dog']]).tolist())"
//   -> [[nan], [1.0]]
// ---------------------------------------------------------------------------
#[test]
fn green_use_encoded_value_nan() {
    let enc = OrdinalEncoder::new()
        .with_handle_unknown(HandleUnknown::UseEncodedValue)
        .with_unknown_value(f64::NAN);
    let x_train = make_1col(&["cat", "dog", "cat"]);
    let fitted = enc.fit(&x_train, &()).unwrap();

    let probe = make_1col(&["bird", "dog"]);
    let out: Array2<f64> = fitted.transform(&probe).unwrap();
    assert!(out[[0, 0]].is_nan(), "unknown 'bird' -> NaN (oracle nan)");
    assert_eq!(out[[1, 0]], 1.0, "seen 'dog' -> 1.0 (oracle)");
}

// ---------------------------------------------------------------------------
// RED GUARD 1 (REQ-5) — use_encoded_value WITHOUT unknown_value -> fit Err.
//
// LIVE oracle (sklearn 1.5.2, run from /tmp):
//   python3 -c "from sklearn.preprocessing import OrdinalEncoder; \
//     OrdinalEncoder(handle_unknown='use_encoded_value')\
//       .fit([['cat'],['dog'],['cat']])"
//   -> TypeError: unknown_value should be an integer or np.nan when
//      handle_unknown is 'use_encoded_value', got None.
// ferrolearn maps sklearn's TypeError -> FerroError::InvalidParameter (Err).
// ---------------------------------------------------------------------------
#[test]
fn red_uev_requires_unknown_value() {
    let enc = OrdinalEncoder::new().with_handle_unknown(HandleUnknown::UseEncodedValue);
    let x_train = make_1col(&["cat", "dog", "cat"]);
    assert!(
        enc.fit(&x_train, &()).is_err(),
        "sklearn raises TypeError (no unknown_value); ferrolearn must Err"
    );
}

// ---------------------------------------------------------------------------
// RED GUARD 2 (REQ-5) — error-mode WITH unknown_value set -> fit Err.
//
// LIVE oracle (sklearn 1.5.2, run from /tmp):
//   python3 -c "from sklearn.preprocessing import OrdinalEncoder; \
//     OrdinalEncoder(handle_unknown='error',unknown_value=-1)\
//       .fit([['cat'],['dog'],['cat']])"
//   -> TypeError: unknown_value should only be set when handle_unknown is
//      'use_encoded_value', got -1.
// ---------------------------------------------------------------------------
#[test]
fn red_error_mode_forbids_unknown_value() {
    // Default handle_unknown is Error; set an unknown_value to provoke the Err.
    let enc = OrdinalEncoder::new().with_unknown_value(-1.0);
    assert_eq!(
        enc.handle_unknown(),
        HandleUnknown::Error,
        "default is Error"
    );
    let x_train = make_1col(&["cat", "dog", "cat"]);
    assert!(
        enc.fit(&x_train, &()).is_err(),
        "sklearn raises TypeError (unknown_value in error mode); ferrolearn must Err"
    );
}

// ---------------------------------------------------------------------------
// RED GUARD 3 (REQ-5) — unknown_value collides with an in-range encoding index
// -> fit Err; while negative / >= max_cardinality / nan all SUCCEED.
//
// LIVE oracle (sklearn 1.5.2, run from /tmp):
//   python3 -c "import numpy as np; from sklearn.preprocessing import \
//     OrdinalEncoder
//   for v in [1,-1,5,np.nan]:
//       try:
//           OrdinalEncoder(handle_unknown='use_encoded_value',unknown_value=v)\
//               .fit([['cat'],['dog'],['cat']]); print(v,'OK')
//       except Exception as e: print(v,type(e).__name__)"
//   -> 1 ValueError   (in [0, n_categories=2) -> collision)
//      -1 OK          (negative)
//      5 OK           (>= max_cardinality)
//      nan OK         (nan sentinel)
//   (collision msg: "The used value for unknown_value 1 is one of the values
//    already used for encoding the seen categories.")
// ---------------------------------------------------------------------------
#[test]
fn red_unknown_value_collision_in_range() {
    // categories_[0] = ['cat','dog'] -> max_cardinality = 2; valid indices 0,1.
    let x_train = make_1col(&["cat", "dog", "cat"]);

    // v = 1.0 collides (in [0, 2)) -> Err.
    let collide = OrdinalEncoder::new()
        .with_handle_unknown(HandleUnknown::UseEncodedValue)
        .with_unknown_value(1.0);
    assert!(
        collide.fit(&x_train, &()).is_err(),
        "unknown_value=1 in [0,2) collides; sklearn ValueError -> Err"
    );
}

// ---------------------------------------------------------------------------
// GREEN GUARD 13 (REQ-5) — unknown_value -1 (negative), 5 (>= cardinality), nan
// all PASS fit (companions to RED GUARD 3; same live oracle session).
// ---------------------------------------------------------------------------
#[test]
fn green_unknown_value_negative_or_oob_or_nan_ok() {
    let x_train = make_1col(&["cat", "dog", "cat"]);

    for v in [-1.0, 5.0, f64::NAN] {
        let enc = OrdinalEncoder::new()
            .with_handle_unknown(HandleUnknown::UseEncodedValue)
            .with_unknown_value(v);
        assert!(
            enc.fit(&x_train, &()).is_ok(),
            "unknown_value={v} is OK in sklearn (negative / out-of-range / nan)"
        );
    }
}

// ---------------------------------------------------------------------------
// GREEN GUARD 14 (REQ-5) — DEFAULT (handle_unknown='error') still rejects
// unknown categories at transform (REQ-2 preserved, UNCHANGED).
//
// LIVE oracle (sklearn 1.5.2, run from /tmp):
//   python3 -c "from sklearn.preprocessing import OrdinalEncoder; \
//     OrdinalEncoder().fit([['cat'],['dog']]).transform([['fish']])"
//   -> ValueError: Found unknown categories ['fish'] in column 0 during transform
// ---------------------------------------------------------------------------
#[test]
fn green_error_mode_unknown_still_rejected() {
    let enc = OrdinalEncoder::new(); // default Error mode
    assert_eq!(enc.handle_unknown(), HandleUnknown::Error);
    assert_eq!(enc.unknown_value(), None);
    let fitted = enc.fit(&make_1col(&["cat", "dog"]), &()).unwrap();
    assert!(
        fitted.transform(&make_1col(&["fish"])).is_err(),
        "default error-mode must still reject unknown 'fish' (REQ-2 preserved)"
    );
}

// ===========================================================================
// REQ-9 — inverse_transform.
//
// EVERY expected value below comes from a LIVE sklearn 1.5.2 oracle (R-CHAR-3),
// reproduced via the `python3 -c` command cited above each test. The encoder
// fixture for the block:
//   python3 -c "from sklearn.preprocessing import OrdinalEncoder; \
//     e=OrdinalEncoder().fit([['cat','x'],['dog','y'],['cat','z']]); \
//     print([c.tolist() for c in e.categories_])"
//   -> [['cat','dog'], ['x','y','z']]
// ===========================================================================

/// The shared fixture: fit on cat/dog x col0 and x/y/z col1.
fn fit_inv_fixture() -> ferrolearn_preprocess::FittedOrdinalEncoder {
    let enc = OrdinalEncoder::new();
    let x = make_2col(&[("cat", "x"), ("dog", "y"), ("cat", "z")]);
    enc.fit(&x, &()).unwrap()
}

// ---------------------------------------------------------------------------
// GREEN GUARD 15 (REQ-9) — roundtrip: inverse_transform(transform(X)) == X,
// multi-feature.
//
// LIVE oracle (sklearn 1.5.2, run from /tmp):
//   python3 -c "from sklearn.preprocessing import OrdinalEncoder; \
//     e=OrdinalEncoder().fit([['cat','x'],['dog','y'],['cat','z']]); \
//     X=[['cat','x'],['dog','y'],['cat','z']]; \
//     print(e.inverse_transform(e.transform(X)).tolist())"
//   -> [['cat','x'],['dog','y'],['cat','z']]   (== the original X)
// ---------------------------------------------------------------------------
#[test]
fn green_inverse_roundtrip_multifeature() {
    let fitted = fit_inv_fixture();
    let x = make_2col(&[("cat", "x"), ("dog", "y"), ("cat", "z")]);
    let encoded = fitted.transform(&x).unwrap();
    let recovered = fitted.inverse_transform(&encoded).unwrap();
    // sklearn roundtrip recovers the original strings exactly.
    assert_eq!(
        recovered, x,
        "inverse_transform(transform(X)) == X (oracle)"
    );
}

// ---------------------------------------------------------------------------
// GREEN GUARD 16 (REQ-9) — held-out valid ordinals decode to the oracle strings.
//
// LIVE oracle (sklearn 1.5.2, run from /tmp):
//   python3 -c "from sklearn.preprocessing import OrdinalEncoder; \
//     e=OrdinalEncoder().fit([['cat','x'],['dog','y'],['cat','z']]); \
//     print(e.inverse_transform([[1.,0.]]).tolist())"
//   -> [['dog','x']]   (col0 index 1 -> 'dog'; col1 index 0 -> 'x')
// ---------------------------------------------------------------------------
#[test]
fn green_inverse_held_out_valid_ordinals() {
    let fitted = fit_inv_fixture();
    let probe = Array2::from_shape_vec((1, 2), vec![1.0_f64, 0.0]).unwrap();
    let out = fitted.inverse_transform(&probe).unwrap();
    // Oracle: [['dog','x']].
    assert_eq!(out[[0, 0]], "dog", "col0 index 1 -> 'dog' (oracle)");
    assert_eq!(out[[0, 1]], "x", "col1 index 0 -> 'x' (oracle)");
}

// ---------------------------------------------------------------------------
// RED GUARD 4 (REQ-9) — out-of-range POSITIVE ordinal -> Err (MATCHES sklearn
// IndexError).
//
// LIVE oracle (sklearn 1.5.2, run from /tmp):
//   python3 -c "from sklearn.preprocessing import OrdinalEncoder; \
//     e=OrdinalEncoder().fit([['cat','x'],['dog','y'],['cat','z']]); \
//     e.inverse_transform([[9.,0.]])"
//   -> IndexError: index 9 is out of bounds for axis 0 with size 2
// ferrolearn maps sklearn's IndexError -> FerroError::InvalidParameter (Err).
// ---------------------------------------------------------------------------
#[test]
fn red_inverse_out_of_range_positive() {
    let fitted = fit_inv_fixture();
    // col0 has 2 categories; index 9 is out of bounds.
    let probe = Array2::from_shape_vec((1, 2), vec![9.0_f64, 0.0]).unwrap();
    assert!(
        fitted.inverse_transform(&probe).is_err(),
        "index 9 with 2 categories -> sklearn IndexError; ferrolearn must Err"
    );
}

// ---------------------------------------------------------------------------
// RED GUARD 5 (REQ-9) — NEGATIVE ordinal -> Err.
//
// DIVERGENCE (R-HONEST-3): sklearn does NOT error here — `-1.0` is cast to
// int64 and numpy NEGATIVE INDEXING wraps it to the LAST category.
//
// LIVE oracle (sklearn 1.5.2, run from /tmp):
//   python3 -c "from sklearn.preprocessing import OrdinalEncoder; \
//     e=OrdinalEncoder().fit([['cat','x'],['dog','y'],['cat','z']]); \
//     print(e.inverse_transform([[-1.,0.]]).tolist())"
//   -> [['dog','x']]   (numpy categories_[0][-1] == 'dog'; NOT an error)
// ferrolearn now MIRRORS numpy's negative-index wrap (#1164 faithful).
// ---------------------------------------------------------------------------
#[test]
fn green_inverse_negative_wraps_like_numpy() {
    let fitted = fit_inv_fixture();
    // LIVE oracle: inverse_transform([[-1.,0.]]) -> [['dog','x']]
    // (categories_[0][-1] == 'dog'); [[-2.,0.]] -> [['cat','x']] (idx -2+2=0).
    let probe = Array2::from_shape_vec((1, 2), vec![-1.0_f64, 0.0]).unwrap();
    let out = fitted.inverse_transform(&probe).unwrap();
    assert_eq!(out[[0, 0]], "dog");
    assert_eq!(out[[0, 1]], "x");
    let probe2 = Array2::from_shape_vec((1, 2), vec![-2.0_f64, 0.0]).unwrap();
    let out2 = fitted.inverse_transform(&probe2).unwrap();
    assert_eq!(out2[[0, 0]], "cat");
    // -3.0 wraps to -1 (still < 0) -> out of bounds -> Err (sklearn IndexError).
    let probe3 = Array2::from_shape_vec((1, 2), vec![-3.0_f64, 0.0]).unwrap();
    assert!(fitted.inverse_transform(&probe3).is_err());
}

// ---------------------------------------------------------------------------
// GREEN GUARD (REQ-9) — NON-INTEGER ordinal truncates toward zero (sklearn).
//
// sklearn: `1.5` is cast to int64 (truncates toward zero -> 1) and decodes to
// 'dog'; `0.7` -> 0 -> 'cat'. ferrolearn now MIRRORS this (#1164 faithful).
//
// LIVE oracle (sklearn 1.5.2, run from /tmp):
//   python3 -c "from sklearn.preprocessing import OrdinalEncoder; \
//     e=OrdinalEncoder().fit([['cat','x'],['dog','y'],['cat','z']]); \
//     print(e.inverse_transform([[1.5,0.]]).tolist())"
//   -> [['dog','x']]   (astype('int64') truncates 1.5 -> 1 -> 'dog')
// ---------------------------------------------------------------------------
#[test]
fn green_inverse_non_integer_truncates_like_numpy() {
    let fitted = fit_inv_fixture();
    let probe = Array2::from_shape_vec((1, 2), vec![1.5_f64, 0.0]).unwrap();
    let out = fitted.inverse_transform(&probe).unwrap();
    assert_eq!(out[[0, 0]], "dog"); // 1.5 -> 1 -> 'dog'
    assert_eq!(out[[0, 1]], "x");
    let probe2 = Array2::from_shape_vec((1, 2), vec![0.7_f64, 0.0]).unwrap();
    let out2 = fitted.inverse_transform(&probe2).unwrap();
    assert_eq!(out2[[0, 0]], "cat"); // 0.7 -> 0 -> 'cat'
}

// ---------------------------------------------------------------------------
// RED GUARD 7 (REQ-9) — ncols mismatch -> Err (MATCHES sklearn ValueError).
//
// LIVE oracle (sklearn 1.5.2, run from /tmp):
//   python3 -c "from sklearn.preprocessing import OrdinalEncoder; \
//     e=OrdinalEncoder().fit([['cat','x'],['dog','y'],['cat','z']]); \
//     e.inverse_transform([[1.,0.,2.]])"
//   -> ValueError: Shape of the passed X data is not correct. Expected 2 columns, got 3.
// ---------------------------------------------------------------------------
#[test]
fn red_inverse_ncols_mismatch() {
    let fitted = fit_inv_fixture();
    let probe = Array2::from_shape_vec((1, 3), vec![1.0_f64, 0.0, 2.0]).unwrap();
    assert!(
        fitted.inverse_transform(&probe).is_err(),
        "3 cols when 2 expected -> sklearn ValueError; ferrolearn must Err"
    );
}

// ---------------------------------------------------------------------------
// RED GUARD 8 (REQ-9) — 0-row input -> Err (MATCHES sklearn ValueError via
// check_array, symmetric with the transform #2220 guard).
//
// LIVE oracle (sklearn 1.5.2, run from /tmp):
//   python3 -c "import numpy as np; from sklearn.preprocessing import \
//     OrdinalEncoder; \
//     e=OrdinalEncoder().fit([['cat','x'],['dog','y'],['cat','z']]); \
//     e.inverse_transform(np.empty((0,2)))"
//   -> ValueError: Found array with 0 sample(s) (shape=(0, 2)) while a minimum
//      of 1 is required.
// ---------------------------------------------------------------------------
#[test]
fn red_inverse_zero_row() {
    let fitted = fit_inv_fixture();
    let probe: Array2<f64> = Array2::from_shape_vec((0, 2), vec![]).unwrap();
    assert!(
        fitted.inverse_transform(&probe).is_err(),
        "0-row inverse -> sklearn ValueError (check_array); ferrolearn must Err"
    );
}

// ---------------------------------------------------------------------------
// RED GUARD 9 (REQ-9) — use_encoded_value unknown_value cell -> Err.
//
// SCOPE LIMITATION (R-HONEST-3): sklearn maps the `unknown_value` cell back to
// `None`, which `Array2<String>` cannot represent (would need
// `Array2<Option<String>>`). The `unknown_value` (-1) is itself out of the
// valid `[0, len)` range, so ferrolearn takes the out-of-range error path.
//
// LIVE oracle (sklearn 1.5.2, run from /tmp):
//   python3 -c "from sklearn.preprocessing import OrdinalEncoder; \
//     e=OrdinalEncoder(handle_unknown='use_encoded_value',unknown_value=-1)\
//       .fit([['cat','x'],['dog','y'],['cat','z']]); \
//     print(e.inverse_transform([[-1.,0.]]).tolist())"
//   -> [[None, 'x']]   (the unknown_value cell decodes to None)
// ferrolearn ERRORS (cannot represent None) — the honest, non-fabricating
// behavior; the default Error-mode encoder's inverse is complete & bit-exact.
// ---------------------------------------------------------------------------
#[test]
fn red_inverse_use_encoded_value_unknown_cell() {
    let enc = OrdinalEncoder::new()
        .with_handle_unknown(HandleUnknown::UseEncodedValue)
        .with_unknown_value(-1.0);
    let x_train = make_2col(&[("cat", "x"), ("dog", "y"), ("cat", "z")]);
    let fitted = enc.fit(&x_train, &()).unwrap();
    let probe = Array2::from_shape_vec((1, 2), vec![-1.0_f64, 0.0]).unwrap();
    // sklearn returns [[None,'x']]; ferrolearn cannot represent None -> Err.
    assert!(
        fitted.inverse_transform(&probe).is_err(),
        "use_encoded_value cell -> sklearn [[None,'x']]; ferrolearn errors (Array2<String> can't hold None)"
    );
}

// ===========================================================================
// REQ-10 (#1165): get_feature_names_out (OneToOneFeatureMixin) + n_features_in_.
//
// Live oracle (sklearn 1.5.2, run from /tmp):
//   e = OrdinalEncoder().fit([['cat','x'],['dog','y']])
//   e.n_features_in_                    -> 2
//   e.get_feature_names_out().tolist()  -> ['x0', 'x1']
//   e.get_feature_names_out(['a','b'])  -> ['a', 'b']
// ===========================================================================
#[test]
fn req10_feature_names_out_and_n_features_in() {
    use ferrolearn_core::traits::Fit;
    use ferrolearn_preprocess::OrdinalEncoder;
    use ndarray::array;

    let x = array![
        ["cat".to_string(), "x".to_string()],
        ["dog".to_string(), "y".to_string()]
    ];
    let fitted = OrdinalEncoder::new().fit(&x, &()).unwrap();

    // n_features_in_ == 2
    assert_eq!(fitted.n_features_in(), 2);

    // default input_features=None -> ['x0','x1']
    let names = fitted.get_feature_names_out(None).unwrap();
    assert_eq!(names, vec!["x0".to_string(), "x1".to_string()]);

    // explicit input_features -> returned verbatim (one-to-one)
    let custom = vec!["a".to_string(), "b".to_string()];
    let named = fitted.get_feature_names_out(Some(&custom)).unwrap();
    assert_eq!(named, custom);

    // wrong-length input_features -> Err (sklearn ValueError)
    let bad = vec!["only_one".to_string()];
    assert!(fitted.get_feature_names_out(Some(&bad)).is_err());
}

// ===========================================================================
// REQ-7 (#1162) — explicit `categories` param (Categories::Explicit).
//
// EVERY expected value below comes from a LIVE sklearn 1.5.2 oracle (R-CHAR-3),
// reproduced via the `python3 -c` command cited above each test.
// ===========================================================================

// ---------------------------------------------------------------------------
// GREEN GUARD 17 (REQ-7) — explicit categories used in the GIVEN order (NOT
// re-sorted); ordinal indices follow the supplied order.
//
// LIVE oracle (sklearn 1.5.2, run from /tmp):
//   python3 -c "from sklearn.preprocessing import OrdinalEncoder; \
//     e=OrdinalEncoder(categories=[['dog','cat','bird']]).fit([['cat'],['dog']]); \
//     print([c.tolist() for c in e.categories_]); \
//     print(e.transform([['cat'],['dog'],['bird']]).tolist())"
//   -> [['dog', 'cat', 'bird']]            # GIVEN order, NOT sorted
//      [[1.0], [0.0], [2.0]]               # cat->1, dog->0, bird->2 (given order)
// ---------------------------------------------------------------------------
#[test]
fn green_explicit_given_order_not_sorted() {
    let enc = OrdinalEncoder::new().with_categories(cats(&[&["dog", "cat", "bird"]]));
    let x = make_1col(&["cat", "dog"]);
    let fitted = enc.fit(&x, &()).unwrap();

    // categories_ are the GIVEN list, NOT sorted.
    assert_eq!(
        fitted.categories()[0],
        ["dog", "cat", "bird"],
        "categories_ in given order (oracle)"
    );

    let probe = make_1col(&["cat", "dog", "bird"]);
    let out: Array2<f64> = fitted.transform(&probe).unwrap();
    // Oracle: [[1.0],[0.0],[2.0]].
    assert_eq!(out[[0, 0]], 1.0, "cat -> index 1 (given order)");
    assert_eq!(out[[1, 0]], 0.0, "dog -> index 0 (given order)");
    assert_eq!(out[[2, 0]], 2.0, "bird -> index 2 (given order)");
}

// ---------------------------------------------------------------------------
// GREEN GUARD 18 (REQ-7) — UNSORTED explicit categories are ACCEPTED (no sort
// requirement on the String path).
//
// LIVE oracle (sklearn 1.5.2, run from /tmp):
//   python3 -c "from sklearn.preprocessing import OrdinalEncoder; \
//     e=OrdinalEncoder(categories=[['zebra','ant','moose']]).fit([['ant'],['zebra']]); \
//     print([c.tolist() for c in e.categories_])"
//   -> [['zebra', 'ant', 'moose']]   # accepted unsorted, given order preserved
// ---------------------------------------------------------------------------
#[test]
fn green_explicit_unsorted_accepted() {
    let enc = OrdinalEncoder::new().with_categories(cats(&[&["zebra", "ant", "moose"]]));
    let x = make_1col(&["ant", "zebra"]);
    let fitted = enc.fit(&x, &()).unwrap();
    assert_eq!(
        fitted.categories()[0],
        ["zebra", "ant", "moose"],
        "unsorted explicit accepted, order preserved (oracle)"
    );
}

// ---------------------------------------------------------------------------
// RED GUARD 10 (REQ-7) — explicit + handle_unknown='error' (default) + a data
// value not in the explicit list -> Err AT FIT (matches sklearn ValueError).
//
// LIVE oracle (sklearn 1.5.2, run from /tmp):
//   python3 -c "from sklearn.preprocessing import OrdinalEncoder; \
//     OrdinalEncoder(categories=[['cat','dog']]).fit([['cat'],['fish']])"
//   -> ValueError: Found unknown categories ['fish'] in column 0 during fit
// ---------------------------------------------------------------------------
#[test]
fn red_explicit_error_mode_data_not_in_cats_fits_err() {
    let enc = OrdinalEncoder::new().with_categories(cats(&[&["cat", "dog"]]));
    let x = make_1col(&["cat", "fish"]);
    assert!(
        enc.fit(&x, &()).is_err(),
        "sklearn ValueError 'Found unknown categories ... during fit'; ferrolearn must Err"
    );
}

// ---------------------------------------------------------------------------
// GREEN GUARD 19 (REQ-7) — explicit + use_encoded_value: out-of-set data is OK
// at fit (subset check SKIPPED) and is encoded to unknown_value at transform.
//
// LIVE oracle (sklearn 1.5.2, run from /tmp):
//   python3 -c "from sklearn.preprocessing import OrdinalEncoder; \
//     e=OrdinalEncoder(categories=[['cat','dog']], \
//       handle_unknown='use_encoded_value', unknown_value=-1)\
//       .fit([['cat'],['fish']]); \
//     print(e.transform([['fish'],['cat']]).tolist())"
//   -> [[-1.0], [0.0]]   # fit OK (no subset error); fish->-1, cat->0 (given order)
// ---------------------------------------------------------------------------
#[test]
fn green_explicit_use_encoded_value_out_of_set_ok() {
    let enc = OrdinalEncoder::new()
        .with_categories(cats(&[&["cat", "dog"]]))
        .with_handle_unknown(HandleUnknown::UseEncodedValue)
        .with_unknown_value(-1.0);
    let x_train = make_1col(&["cat", "fish"]);
    // fit must NOT error (subset check skipped under use_encoded_value).
    let fitted = enc.fit(&x_train, &()).unwrap();

    let probe = make_1col(&["fish", "cat"]);
    let out: Array2<f64> = fitted.transform(&probe).unwrap();
    // Oracle: [[-1.0],[0.0]].
    assert_eq!(out[[0, 0]], -1.0, "out-of-set 'fish' -> unknown_value -1");
    assert_eq!(out[[1, 0]], 0.0, "'cat' -> index 0 (given order)");
}

// ---------------------------------------------------------------------------
// RED GUARD 11 (REQ-7) — explicit list-count != n_features -> Err
// (ShapeMismatch, matches sklearn ValueError).
//
// LIVE oracle (sklearn 1.5.2, run from /tmp):
//   python3 -c "from sklearn.preprocessing import OrdinalEncoder; \
//     OrdinalEncoder(categories=[['cat','dog']]).fit([['cat','x'],['dog','y']])"
//   -> ValueError: Shape mismatch: if categories is an array, it has to be of
//      shape (n_features,).
// (1 category list provided for 2-feature data.)
// ---------------------------------------------------------------------------
#[test]
fn red_explicit_n_features_mismatch() {
    // 1 category list, but the data has 2 columns.
    let enc = OrdinalEncoder::new().with_categories(cats(&[&["cat", "dog"]]));
    let x = make_2col(&[("cat", "x"), ("dog", "y")]);
    assert!(
        enc.fit(&x, &()).is_err(),
        "1 cat-list for 2 features -> sklearn ValueError (shape mismatch); ferrolearn must Err"
    );
}

// ---------------------------------------------------------------------------
// GREEN GUARD 20 (REQ-7) — multi-feature explicit, each column in its OWN given
// order; transform indices follow the per-column order.
//
// LIVE oracle (sklearn 1.5.2, run from /tmp):
//   python3 -c "from sklearn.preprocessing import OrdinalEncoder; \
//     e=OrdinalEncoder(categories=[['dog','cat'],['z','y','x']])\
//       .fit([['cat','x'],['dog','y']]); \
//     print([c.tolist() for c in e.categories_]); \
//     print(e.transform([['cat','x'],['dog','z']]).tolist())"
//   -> [['dog', 'cat'], ['z', 'y', 'x']]
//      [[1.0, 2.0], [0.0, 0.0]]   # col0: cat->1,dog->0 ; col1: x->2,z->0
// ---------------------------------------------------------------------------
#[test]
fn green_explicit_multifeature_each_own_order() {
    let enc = OrdinalEncoder::new().with_categories(cats(&[&["dog", "cat"], &["z", "y", "x"]]));
    let x = make_2col(&[("cat", "x"), ("dog", "y")]);
    let fitted = enc.fit(&x, &()).unwrap();

    assert_eq!(fitted.categories()[0], ["dog", "cat"], "col0 given order");
    assert_eq!(fitted.categories()[1], ["z", "y", "x"], "col1 given order");

    let probe = make_2col(&[("cat", "x"), ("dog", "z")]);
    let out: Array2<f64> = fitted.transform(&probe).unwrap();
    // Oracle: [[1.0,2.0],[0.0,0.0]].
    assert_eq!(out[[0, 0]], 1.0, "col0 cat -> 1");
    assert_eq!(out[[0, 1]], 2.0, "col1 x -> 2");
    assert_eq!(out[[1, 0]], 0.0, "col0 dog -> 0");
    assert_eq!(out[[1, 1]], 0.0, "col1 z -> 0");
}

// ---------------------------------------------------------------------------
// RED GUARD 12 (REQ-7) — explicit list with DUPLICATE elements -> Err
// (matches sklearn ValueError).
//
// LIVE oracle (sklearn 1.5.2, run from /tmp):
//   python3 -c "from sklearn.preprocessing import OrdinalEncoder; \
//     OrdinalEncoder(categories=[['cat','cat','dog']]).fit([['cat'],['dog']])"
//   -> ValueError: In column 0, the predefined categories contain duplicate
//      elements.
// ---------------------------------------------------------------------------
#[test]
fn red_explicit_duplicate_categories() {
    let enc = OrdinalEncoder::new().with_categories(cats(&[&["cat", "cat", "dog"]]));
    let x = make_1col(&["cat", "dog"]);
    assert!(
        enc.fit(&x, &()).is_err(),
        "duplicate explicit categories -> sklearn ValueError; ferrolearn must Err"
    );
}

// ---------------------------------------------------------------------------
// GREEN GUARD 21 (REQ-7) — inverse_transform with explicit (given-order)
// categories roundtrips to the given-order strings.
//
// LIVE oracle (sklearn 1.5.2, run from /tmp):
//   python3 -c "from sklearn.preprocessing import OrdinalEncoder; \
//     e=OrdinalEncoder(categories=[['dog','cat','bird']]).fit([['cat'],['dog']]); \
//     print(e.inverse_transform([[1.],[0.],[2.]]).tolist())"
//   -> [['cat'], ['dog'], ['bird']]   # index 1->cat, 0->dog, 2->bird (given order)
// ---------------------------------------------------------------------------
#[test]
fn green_explicit_inverse_roundtrip_given_order() {
    let enc = OrdinalEncoder::new().with_categories(cats(&[&["dog", "cat", "bird"]]));
    let x = make_1col(&["cat", "dog"]);
    let fitted = enc.fit(&x, &()).unwrap();

    let probe = Array2::from_shape_vec((3, 1), vec![1.0_f64, 0.0, 2.0]).unwrap();
    let out = fitted.inverse_transform(&probe).unwrap();
    // Oracle: [['cat'],['dog'],['bird']].
    assert_eq!(out[[0, 0]], "cat", "index 1 -> 'cat' (given order)");
    assert_eq!(out[[1, 0]], "dog", "index 0 -> 'dog' (given order)");
    assert_eq!(out[[2, 0]], "bird", "index 2 -> 'bird' (given order)");
}

// ---------------------------------------------------------------------------
// GREEN GUARD 22 (REQ-7) — the DEFAULT categories='auto' path is UNCHANGED:
// sorted-unique categories_, matching the SHIPPED REQ-1 behavior.
//
// LIVE oracle (sklearn 1.5.2, run from /tmp):
//   python3 -c "from sklearn.preprocessing import OrdinalEncoder; \
//     e=OrdinalEncoder().fit([['dog'],['cat'],['bird']]); \
//     print([c.tolist() for c in e.categories_]); \
//     print(e.transform([['cat'],['dog'],['bird']]).tolist())"
//   -> [['bird', 'cat', 'dog']]          # AUTO -> sorted-unique
//      [[1.0], [2.0], [0.0]]
// ---------------------------------------------------------------------------
#[test]
fn green_explicit_auto_still_default() {
    // No with_categories() -> Categories::Auto (default).
    let enc = OrdinalEncoder::new();
    let x = make_1col(&["dog", "cat", "bird"]);
    let fitted = enc.fit(&x, &()).unwrap();
    // AUTO path: sorted-unique (UNCHANGED REQ-1).
    assert_eq!(
        fitted.categories()[0],
        ["bird", "cat", "dog"],
        "auto -> sorted-unique (oracle)"
    );
    let probe = make_1col(&["cat", "dog", "bird"]);
    let out: Array2<f64> = fitted.transform(&probe).unwrap();
    assert_eq!(out[[0, 0]], 1.0, "auto cat -> 1");
    assert_eq!(out[[1, 0]], 2.0, "auto dog -> 2");
    assert_eq!(out[[2, 0]], 0.0, "auto bird -> 0");
}

// ===========================================================================
// REQ-8 — min_frequency / max_categories infrequent grouping.
//
// The OrdinalEncoder ANALOG of the SHIPPED OneHotEncoder REQ-5b: the same
// `_identify_infrequent` algorithm, but the infrequent categories collapse to a
// single shared ORDINAL CODE (not a one-hot column). `categories_` keeps ALL
// categories; only the emitted code is folded. The inverse of the shared code
// is the REAL String `"infrequent_sklearn"` (not a NaN proxy).
//
// EVERY expected value below is grounded in a LIVE sklearn 1.5.2 oracle call
// (R-CHAR-3). The oracle commands are quoted inline above each test.
// ===========================================================================

/// Build an `n x 1` column by repeating each `(value, count)` pair.
fn make_1col_rep(spec: &[(&str, usize)]) -> Array2<String> {
    let mut vals: Vec<String> = Vec::new();
    for &(v, c) in spec {
        for _ in 0..c {
            vals.push(v.to_string());
        }
    }
    let n = vals.len();
    Array2::from_shape_vec((n, 1), vals).unwrap()
}

// ---------------------------------------------------------------------------
// REQ-8a: min_frequency=2.
//
// LIVE oracle (sklearn 1.5.2, run from /tmp):
//   >>> from sklearn.preprocessing import OrdinalEncoder
//   >>> X = [['a']]*5+[['b']]*5+[['c']]*1+[['d']]*1
//   >>> e = OrdinalEncoder(min_frequency=2).fit(X)
//   >>> [list(c) for c in e.categories_]            -> [['a','b','c','d']]
//   >>> [list(c) for c in e.infrequent_categories_] -> [['c','d']]
//   >>> e.transform([['a'],['b'],['c'],['d']]).tolist()
//                                                   -> [[0.],[1.],[2.],[2.]]
//   >>> e.inverse_transform([[0.],[1.],[2.]]).tolist()
//                                                   -> [['a'],['b'],['infrequent_sklearn']]
// ---------------------------------------------------------------------------
#[test]
fn req8_min_frequency_two_categories_transform_inverse() {
    let enc = OrdinalEncoder::new().with_min_frequency(2);
    let x = make_1col_rep(&[("a", 5), ("b", 5), ("c", 1), ("d", 1)]);
    let fitted = enc.fit(&x, &()).unwrap();

    // categories_ keeps ALL categories (oracle: [['a','b','c','d']]).
    assert_eq!(
        fitted.categories()[0],
        ["a", "b", "c", "d"],
        "categories_ keeps all (oracle)"
    );
    // infrequent_categories_ == [['c','d']] (oracle).
    assert_eq!(
        fitted.infrequent_categories()[0],
        ["c", "d"],
        "infrequent_categories_ (oracle)"
    );

    // transform: a->0, b->1, c&d->2 (shared trailing code; oracle).
    let probe = make_1col(&["a", "b", "c", "d"]);
    let out = fitted.transform(&probe).unwrap();
    assert_eq!(out[[0, 0]], 0.0, "a -> 0");
    assert_eq!(out[[1, 0]], 1.0, "b -> 1");
    assert_eq!(out[[2, 0]], 2.0, "c -> 2 (infrequent)");
    assert_eq!(out[[3, 0]], 2.0, "d -> 2 (infrequent, same code)");

    // inverse: 0->'a', 1->'b', 2->'infrequent_sklearn' (oracle).
    let inv = fitted
        .inverse_transform(&Array2::from_shape_vec((3, 1), vec![0.0, 1.0, 2.0]).unwrap())
        .unwrap();
    assert_eq!(inv[[0, 0]], "a", "inverse 0 -> 'a' (frequent)");
    assert_eq!(inv[[1, 0]], "b", "inverse 1 -> 'b' (frequent)");
    assert_eq!(
        inv[[2, 0]],
        "infrequent_sklearn",
        "inverse 2 -> 'infrequent_sklearn' (shared infrequent code)"
    );
}

// ---------------------------------------------------------------------------
// REQ-8b: max_categories=K keeps top (K-1) frequent + 1 infrequent group.
//
// LIVE oracle (sklearn 1.5.2):
//   >>> X = [['a']]*5+[['b']]*4+[['c']]*3+[['d']]*2+[['e']]*1
//   >>> e = OrdinalEncoder(max_categories=3).fit(X)
//   >>> [list(c) for c in e.categories_]            -> [['a','b','c','d','e']]
//   >>> [list(c) for c in e.infrequent_categories_] -> [['c','d','e']]
//   >>> e.transform([['a'],['b'],['c'],['d'],['e']]).tolist()
//                                            -> [[0.],[1.],[2.],[2.],[2.]]
//   >>> e.inverse_transform([[0.],[1.],[2.]]).tolist()
//                                            -> [['a'],['b'],['infrequent_sklearn']]
// ---------------------------------------------------------------------------
#[test]
fn req8_max_categories_keeps_top_k_minus_one() {
    let enc = OrdinalEncoder::new().with_max_categories(3);
    let x = make_1col_rep(&[("a", 5), ("b", 4), ("c", 3), ("d", 2), ("e", 1)]);
    let fitted = enc.fit(&x, &()).unwrap();

    assert_eq!(fitted.categories()[0], ["a", "b", "c", "d", "e"]);
    assert_eq!(
        fitted.infrequent_categories()[0],
        ["c", "d", "e"],
        "top-2 frequent (a,b), rest infrequent (oracle)"
    );

    let probe = make_1col(&["a", "b", "c", "d", "e"]);
    let out = fitted.transform(&probe).unwrap();
    assert_eq!(
        out.column(0).to_vec(),
        vec![0.0, 1.0, 2.0, 2.0, 2.0],
        "a->0 b->1 c,d,e->2 (oracle)"
    );

    let inv = fitted
        .inverse_transform(&Array2::from_shape_vec((3, 1), vec![0.0, 1.0, 2.0]).unwrap())
        .unwrap();
    assert_eq!(inv.column(0).to_vec(), vec!["a", "b", "infrequent_sklearn"]);
}

// ---------------------------------------------------------------------------
// REQ-8c: max_categories TIE-BREAK favors the LARGER index (stable argsort).
//
// LIVE oracle (sklearn 1.5.2):
//   >>> X = [['a']]*5+[['b']]*3+[['c']]*3+[['d']]*1   # b,c tie at count 3
//   >>> e = OrdinalEncoder(max_categories=3).fit(X)   # keep 2 frequent
//   >>> [list(c) for c in e.infrequent_categories_]   -> [['b','d']]
//   >>> e.transform([['a'],['b'],['c'],['d']]).tolist()
//                                            -> [[0.],[2.],[1.],[2.]]
//   >>> e.inverse_transform([[0.],[1.],[2.]]).tolist()
//                                            -> [['a'],['c'],['infrequent_sklearn']]
// The tie between b and c (both count 3) is broken in favor of the LARGER
// index: c (index 2) stays frequent, b (index 1) becomes infrequent.
// ---------------------------------------------------------------------------
#[test]
fn req8_max_categories_tiebreak_favors_larger_index() {
    let enc = OrdinalEncoder::new().with_max_categories(3);
    let x = make_1col_rep(&[("a", 5), ("b", 3), ("c", 3), ("d", 1)]);
    let fitted = enc.fit(&x, &()).unwrap();

    // Tie b=c=3: c (larger index) frequent, b infrequent (oracle).
    assert_eq!(
        fitted.infrequent_categories()[0],
        ["b", "d"],
        "tie favors larger index: b infrequent, c frequent (oracle)"
    );

    let probe = make_1col(&["a", "b", "c", "d"]);
    let out = fitted.transform(&probe).unwrap();
    assert_eq!(
        out.column(0).to_vec(),
        vec![0.0, 2.0, 1.0, 2.0],
        "a->0 c->1 (2nd frequent slot) b,d->2 (oracle)"
    );

    // inverse: slot 1 -> 'c' (the second frequent category in original order).
    let inv = fitted
        .inverse_transform(&Array2::from_shape_vec((3, 1), vec![0.0, 1.0, 2.0]).unwrap())
        .unwrap();
    assert_eq!(
        inv.column(0).to_vec(),
        vec!["a", "c", "infrequent_sklearn"],
        "inverse 1 -> 'c' (frequent), 2 -> infrequent_sklearn (oracle)"
    );
}

// ---------------------------------------------------------------------------
// REQ-8d: BOTH min_frequency AND max_categories set; multi-feature where only
// some features have infrequent categories.
//
// LIVE oracle (sklearn 1.5.2):
//   >>> X = [['a','p']]*5+[['b','q']]*5+[['c','p']]*1+[['d','q']]*1
//   >>> e = OrdinalEncoder(min_frequency=2, max_categories=10).fit(X)
//   >>> [list(c) for c in e.categories_]
//                                  -> [['a','b','c','d'], ['p','q']]
//   >>> [None if c is None else list(c) for c in e.infrequent_categories_]
//                                  -> [['c','d'], None]
//   >>> e.transform([['a','p'],['b','q'],['c','p'],['d','q']]).tolist()
//                                  -> [[0.,0.],[1.,1.],[2.,0.],[2.,1.]]
// Col 0: c,d infrequent (count 1 < 2). Col 1: p,q both count 6 -> no
// infrequent (the empty inner Vec is sklearn's `None`).
// ---------------------------------------------------------------------------
#[test]
fn req8_both_set_multifeature_some_without_infrequent() {
    let enc = OrdinalEncoder::new()
        .with_min_frequency(2)
        .with_max_categories(10);
    let x = make_2col(&[
        ("a", "p"),
        ("a", "p"),
        ("a", "p"),
        ("a", "p"),
        ("a", "p"),
        ("b", "q"),
        ("b", "q"),
        ("b", "q"),
        ("b", "q"),
        ("b", "q"),
        ("c", "p"),
        ("d", "q"),
    ]);
    let fitted = enc.fit(&x, &()).unwrap();

    assert_eq!(fitted.categories()[0], ["a", "b", "c", "d"]);
    assert_eq!(fitted.categories()[1], ["p", "q"]);
    // Col 0 has infrequent {c,d}; col 1 has NONE (empty == sklearn None).
    assert_eq!(fitted.infrequent_categories()[0], ["c", "d"]);
    assert!(
        fitted.infrequent_categories()[1].is_empty(),
        "col 1 has no infrequent categories (sklearn None == empty)"
    );

    let probe = make_2col(&[("a", "p"), ("b", "q"), ("c", "p"), ("d", "q")]);
    let out = fitted.transform(&probe).unwrap();
    assert_eq!(out[[0, 0]], 0.0);
    assert_eq!(out[[0, 1]], 0.0);
    assert_eq!(out[[1, 0]], 1.0);
    assert_eq!(out[[1, 1]], 1.0);
    assert_eq!(out[[2, 0]], 2.0, "c -> 2 (infrequent col 0)");
    assert_eq!(out[[2, 1]], 0.0, "p -> 0 (frequent col 1, unchanged)");
    assert_eq!(out[[3, 0]], 2.0, "d -> 2 (infrequent col 0)");
    assert_eq!(out[[3, 1]], 1.0, "q -> 1 (frequent col 1, unchanged)");
}

// ---------------------------------------------------------------------------
// REQ-8e: min_frequency=0 / max_categories=0 -> InvalidParameterError.
//
// LIVE oracle (sklearn 1.5.2):
//   >>> OrdinalEncoder(min_frequency=0).fit([['a'],['b']])
//        -> InvalidParameterError: The 'min_frequency' parameter ... must be an
//           int in the range [1, inf).
//   >>> OrdinalEncoder(max_categories=0).fit([['a'],['b']])
//        -> InvalidParameterError: The 'max_categories' parameter ... [1, inf).
// ---------------------------------------------------------------------------
#[test]
fn req8_zero_thresholds_rejected() {
    let x = make_1col(&["a", "b"]);
    let r_min = OrdinalEncoder::new().with_min_frequency(0).fit(&x, &());
    assert!(r_min.is_err(), "min_frequency=0 -> Err (oracle)");
    let r_max = OrdinalEncoder::new().with_max_categories(0).fit(&x, &());
    assert!(r_max.is_err(), "max_categories=0 -> Err (oracle)");
}

// ---------------------------------------------------------------------------
// REQ-8f: infrequent + handle_unknown='use_encoded_value' + unknown_value.
//
// LIVE oracle (sklearn 1.5.2):
//   >>> X = [['a']]*5+[['b']]*5+[['c']]*1
//   >>> e = OrdinalEncoder(min_frequency=2,
//   ...     handle_unknown='use_encoded_value', unknown_value=-1).fit(X)
//   >>> e.transform([['a'],['c'],['zzz']]).tolist()
//                                  -> [[0.],[2.],[-1.]]
// A known-but-infrequent value 'c' -> 2.0 (the trailing infrequent code); an
// UNKNOWN value 'zzz' -> -1.0 (unknown_value). The two are DISTINCT codes.
// ---------------------------------------------------------------------------
#[test]
fn req8_infrequent_plus_use_encoded_value_distinct_codes() {
    let enc = OrdinalEncoder::new()
        .with_min_frequency(2)
        .with_handle_unknown(HandleUnknown::UseEncodedValue)
        .with_unknown_value(-1.0);
    let x = make_1col_rep(&[("a", 5), ("b", 5), ("c", 1)]);
    let fitted = enc.fit(&x, &()).unwrap();

    let probe = make_1col(&["a", "c", "zzz"]);
    let out = fitted.transform(&probe).unwrap();
    assert_eq!(out[[0, 0]], 0.0, "a -> 0 (frequent)");
    assert_eq!(out[[1, 0]], 2.0, "c -> 2 (known infrequent)");
    assert_eq!(out[[2, 0]], -1.0, "zzz -> -1 (unknown_value, distinct)");
}

// ---------------------------------------------------------------------------
// REQ-8g: unknown_value collision keys off the EFFECTIVE code count.
//
// LIVE oracle (sklearn 1.5.2):
//   >>> X = [['a']]*5+[['b']]*5+[['c']]*1+[['d']]*1   # 4 cats, codes 0,1,2
//   >>> OrdinalEncoder(min_frequency=2,
//   ...     handle_unknown='use_encoded_value', unknown_value=3).fit(X)  # OK
//   >>> OrdinalEncoder(min_frequency=2,
//   ...     handle_unknown='use_encoded_value', unknown_value=2).fit(X)  # ValueError
// With min_frequency=2 the feature emits 3 codes (0,1,2-infrequent), so
// unknown_value=3 is fine but =2 collides with the infrequent code. (Without
// grouping, len(categories_)=4 so =3 would collide -- REQ-5 baseline below.)
// ---------------------------------------------------------------------------
#[test]
fn req8_unknown_value_collision_uses_effective_code_count() {
    let x = make_1col_rep(&[("a", 5), ("b", 5), ("c", 1), ("d", 1)]);
    // uv=3 accepted under infrequent (effective 3 codes: 0,1,2).
    let ok = OrdinalEncoder::new()
        .with_min_frequency(2)
        .with_handle_unknown(HandleUnknown::UseEncodedValue)
        .with_unknown_value(3.0)
        .fit(&x, &());
    assert!(ok.is_ok(), "uv=3 OK under infrequent (3 codes) (oracle)");
    // uv=2 collides with the infrequent code.
    let collide = OrdinalEncoder::new()
        .with_min_frequency(2)
        .with_handle_unknown(HandleUnknown::UseEncodedValue)
        .with_unknown_value(2.0)
        .fit(&x, &());
    assert!(collide.is_err(), "uv=2 collides infrequent code (oracle)");
    // REQ-5 baseline (no grouping): uv=3 collides (len(categories_)=4).
    let base = OrdinalEncoder::new()
        .with_handle_unknown(HandleUnknown::UseEncodedValue)
        .with_unknown_value(3.0)
        .fit(&x, &());
    assert!(base.is_err(), "uv=3 collides without grouping (REQ-5)");
}

// ---------------------------------------------------------------------------
// REQ-8h: None (default) -> REQ-1/2/3/5 UNCHANGED.
//
// LIVE oracle (sklearn 1.5.2): an OrdinalEncoder with no min_frequency /
// max_categories has NO `_infrequent_indices` attribute and behaves identically
// to the SHIPPED encoder.
//   >>> OrdinalEncoder().fit([['x'],['y'],['x']]).categories_  -> [['x','y']]
//   >>> hasattr(., '_infrequent_indices')                      -> False
// ---------------------------------------------------------------------------
#[test]
fn req8_disabled_default_unchanged() {
    let enc = OrdinalEncoder::new();
    let x = make_1col(&["x", "y", "x"]);
    let fitted = enc.fit(&x, &()).unwrap();
    assert_eq!(fitted.categories()[0], ["x", "y"]);
    // No infrequent categories when disabled (empty == sklearn None).
    assert!(
        fitted.infrequent_categories()[0].is_empty(),
        "disabled -> no infrequent (oracle: no _infrequent_indices)"
    );
    // transform is the plain idx as f64 (SHIPPED REQ-2).
    let out = fitted.transform(&x).unwrap();
    assert_eq!(out.column(0).to_vec(), vec![0.0, 1.0, 0.0]);
    // inverse is the plain SHIPPED REQ-9 roundtrip.
    let inv = fitted.inverse_transform(&out).unwrap();
    assert_eq!(inv.column(0).to_vec(), vec!["x", "y", "x"]);
}

// ---------------------------------------------------------------------------
// REQ-8i: inverse roundtrip where some values are infrequent -> the infrequent
// values do NOT round-trip to the original (they map to 'infrequent_sklearn'),
// matching sklearn's documented non-roundtrip.
//
// LIVE oracle (sklearn 1.5.2):
//   >>> X = [['a']]*5+[['b']]*5+[['c']]*1+[['d']]*1
//   >>> e = OrdinalEncoder(min_frequency=2).fit(X)
//   >>> t = e.transform([['a'],['c'],['d']])      -> [[0.],[2.],[2.]]
//   >>> e.inverse_transform(t).tolist()
//          -> [['a'],['infrequent_sklearn'],['infrequent_sklearn']]
// 'a' round-trips; 'c'/'d' collapse to 'infrequent_sklearn' (documented
// non-roundtrip, like sklearn).
// ---------------------------------------------------------------------------
#[test]
fn req8_inverse_infrequent_non_roundtrip() {
    let enc = OrdinalEncoder::new().with_min_frequency(2);
    let x = make_1col_rep(&[("a", 5), ("b", 5), ("c", 1), ("d", 1)]);
    let fitted = enc.fit(&x, &()).unwrap();

    let probe = make_1col(&["a", "c", "d"]);
    let t = fitted.transform(&probe).unwrap();
    assert_eq!(t.column(0).to_vec(), vec![0.0, 2.0, 2.0]);

    let inv = fitted.inverse_transform(&t).unwrap();
    assert_eq!(
        inv.column(0).to_vec(),
        vec!["a", "infrequent_sklearn", "infrequent_sklearn"],
        "frequent 'a' round-trips; infrequent 'c'/'d' -> 'infrequent_sklearn' (oracle)"
    );
}

// ===========================================================================
// REQ-8 (#1163) — INTERLEAVED infrequent fixture (the critic-flagged coverage
// gap): infrequent categories sit BETWEEN frequent ones by sort order, so the
// frequent ordinals must compact (c,e -> slots 1,2) and the inverse back-map
// must recover the RIGHT original category, not the categories_ index.
//
// Live oracle (sklearn 1.5.2, run from /tmp):
//   X = [['a']]*5 + [['b']]*1 + [['c']]*4 + [['d']]*1 + [['e']]*3
//   e = OrdinalEncoder(min_frequency=2).fit(X)   # b,d infrequent (count 1<2)
//   e.categories_            -> [['a','b','c','d','e']]
//   e.infrequent_categories_ -> [['b','d']]
//   e.transform([['a'],['b'],['c'],['d'],['e']]) -> [[0],[3],[1],[3],[2]]
//   e.inverse_transform([[0],[1],[2],[3]]) -> [['a'],['c'],['e'],['infrequent_sklearn']]
// ===========================================================================
#[test]
fn req8_interleaved_infrequent_remap_and_inverse() {
    use ferrolearn_core::traits::Fit;
    use ferrolearn_preprocess::OrdinalEncoder;

    let mut rows: Vec<&str> = Vec::new();
    rows.extend(std::iter::repeat_n("a", 5));
    rows.extend(std::iter::repeat_n("b", 1));
    rows.extend(std::iter::repeat_n("c", 4));
    rows.extend(std::iter::repeat_n("d", 1));
    rows.extend(std::iter::repeat_n("e", 3));
    let x = make_1col(&rows);

    let fitted = OrdinalEncoder::new()
        .with_min_frequency(2)
        .fit(&x, &())
        .unwrap();

    // infrequent_categories_ == [['b','d']]
    assert_eq!(fitted.infrequent_categories()[0], vec!["b", "d"]);

    // transform: a->0, b->3(infrequent), c->1, d->3, e->2
    let probe = make_1col(&["a", "b", "c", "d", "e"]);
    let out = fitted.transform(&probe).unwrap();
    let got: Vec<f64> = out.iter().copied().collect();
    assert_eq!(got, vec![0.0, 3.0, 1.0, 3.0, 2.0], "interleaved remap");

    // inverse: 0->a, 1->c, 2->e, 3->infrequent_sklearn (the back-map recovers
    // the RIGHT frequent category, not the categories_ index).
    let inv_in = ndarray::Array2::from_shape_vec((4, 1), vec![0.0_f64, 1.0, 2.0, 3.0]).unwrap();
    let inv = fitted.inverse_transform(&inv_in).unwrap();
    assert_eq!(inv[[0, 0]], "a");
    assert_eq!(inv[[1, 0]], "c");
    assert_eq!(inv[[2, 0]], "e");
    assert_eq!(inv[[3, 0]], "infrequent_sklearn");
}