rust-key-paths 3.0.0

Keypaths for Rust: Static dispatch implementation (rust-keypaths) and legacy dynamic dispatch (key-paths-core). Type-safe, composable access to nested data structures.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
// pub type KpType<R, V, Root, Value, MutRoot, MutValue, G, S>
// where
//     Root: ,
//     Value:    Borrow<V>,
//     MutRoot:  BorrowMut<R>,
//     MutValue: std::borrow::BorrowMut<V>,
//     G:        Fn(Root) -> Option<Value>,
//     S:        Fn(MutRoot) -> Option<MutValue> = Kp<R, V, Root, Value, MutRoot, MutValue, G, S>;

// type Getter<R, V, Root, Value> where Root: std::borrow::Borrow<R>, Value: std::borrow::Borrow<V> = fn(Root) -> Option<Value>;
// type Setter<R, V> = fn(&'r mut R) -> Option<&'r mut V>;

use std::fmt;
use std::sync::Arc;

// Export the sync_kp module
pub mod sync_kp;
pub mod prelude;

pub use sync_kp::{
    ArcMutexAccess, ArcRwLockAccess, LockAccess, SyncKp, SyncKpType, RcRefCellAccess,
    StdMutexAccess, StdRwLockAccess,
};

#[cfg(feature = "parking_lot")]
pub use sync_kp::{
    DirectParkingLotMutexAccess, DirectParkingLotRwLockAccess, ParkingLotMutexAccess,
    ParkingLotRwLockAccess,
};

#[cfg(feature = "arc-swap")]
pub use sync_kp::{ArcArcSwapAccess, ArcArcSwapOptionAccess};

// Export the async_lock module
pub mod async_lock;

pub mod kptrait;

pub use kptrait::{
    AccessorTrait, ChainExt, CoercionTrait, HofTrait, KeyPathValueTarget, KpReadable, KpTrait,
    KPWritable,
};

// pub struct KpStatic<R, V> {
//     pub get: fn(&R) -> Option<&V>,
//     pub set: fn(&mut R) -> Option<&mut V>,
// }
//
// // KpStatic holds only fn pointers; it is a functional component with no owned data.
// unsafe impl<R, V> Send for KpStatic<R, V> {}
// unsafe impl<R, V> Sync for KpStatic<R, V> {}
//
// impl<R, V> KpStatic<R, V> {
//     pub const fn new(
//         get: fn(&R) -> Option<&V>,
//         set: fn(&mut R) -> Option<&mut V>,
//     ) -> Self {
//         Self { get, set }
//     }
//
//     #[inline(always)]
//     pub fn get<'a>(&self, root: &'a R) -> Option<&'a V> {
//         (self.get)(root)
//     }
//
//     #[inline(always)]
//     pub fn set<'a>(&self, root: &'a mut R) -> Option<&'a mut V> {
//         (self.set)(root)
//     }
// }

// // Macro generates:
// #[inline(always)]
// fn __get_static_str_field(x: &AllContainersTest) -> Option<&'static str> {
//     Some(&x.static_str_field)
// }
//
// #[inline(always)]
// fn __set_static_str_field(x: &mut AllContainersTest) -> Option<&mut &'static str> {
//     Some(&mut x.static_str_field)
// }
//
// pub static STATIC_STR_FIELD_KP: KpStatic<AllContainersTest, &'static str> =
//     KpStatic::new(__get_static_str_field, __set_static_str_field);

#[cfg(feature = "pin_project")]
pub mod pin;

/// Build a keypath from `Type.field` segments. Use with types that have keypath accessors (e.g. `#[derive(Kp)]` from key-paths-derive).
#[macro_export]
macro_rules! keypath {
    { $root:ident . $field:ident } => { $root::$field() };
    { $root:ident . $field:ident . $($ty:ident . $f:ident).+ } => {
        $root::$field() $(.then($ty::$f()))+
    };
    ($root:ident . $field:ident) => { $root::$field() };
    ($root:ident . $field:ident . $($ty:ident . $f:ident).+) => {
        $root::$field() $(.then($ty::$f()))+
    };
}

/// Get value through a keypath or a default reference when the path returns `None`.
/// Use with `KpType`: `get_or!(User::name(), &user, &default)` where `default` is `&T` (same type as the path value). Returns `&T`.
/// Path syntax: `get_or!(&user => User.name, &default)`.
#[macro_export]
macro_rules! get_or {
    ($kp:expr, $root:expr, $default:expr) => {
        $kp.get($root).unwrap_or($default)
    };
    ($root:expr => $($path:tt)*, $default:expr) => {
        $crate::get_or!($crate::keypath!($($path)*), $root, $default)
    };
}

/// Get value through a keypath, or compute an owned fallback when the path returns `None`.
/// Use with `KpType`: `get_or_else!(User::name(), &user, || "default".to_string())`.
/// Returns `T` (owned). The keypath's value type must be `Clone`. The closure is only called when the path is `None`.
/// Path syntax: `get_or_else!(&user => (User.name), || "default".to_string())` — path in parentheses.
#[macro_export]
macro_rules! get_or_else {
    ($kp:expr, $root:expr, $closure:expr) => {
        $kp.get($root).map(|r| r.clone()).unwrap_or_else($closure)
    };
    ($root:expr => ($($path:tt)*), $closure:expr) => {
        $crate::get_or_else!($crate::keypath!($($path)*), $root, $closure)
    };
}

/// Zip multiple keypaths on the same root and apply a closure to the tuple of values.
/// Returns `Some(closure((v1, v2, ...)))` when all keypaths succeed, else `None`.
///
/// # Example
/// ```
/// use rust_key_paths::{Kp, KpType, zip_with_kp};
/// struct User { name: String, age: u32, city: String }
/// let name_kp = KpType::new(|u: &User| Some(&u.name), |u: &mut User| Some(&mut u.name));
/// let age_kp = KpType::new(|u: &User| Some(&u.age), |u: &mut User| Some(&mut u.age));
/// let city_kp = KpType::new(|u: &User| Some(&u.city), |u: &mut User| Some(&mut u.city));
/// let user = User { name: "Akash".into(), age: 30, city: "NYC".into() };
/// let summary = zip_with_kp!(
///     &user,
///     |(name, age, city)| format!("{}, {} from {}", name, age, city) =>
///     name_kp,
///     age_kp,
///     city_kp
/// );
/// assert_eq!(summary, Some("Akash, 30 from NYC".to_string()));
/// ```
#[macro_export]
macro_rules! zip_with_kp {
    ($root:expr, $closure:expr => $kp1:expr, $kp2:expr) => {
        match ($kp1.get($root), $kp2.get($root)) {
            (Some(__a), Some(__b)) => Some($closure((__a, __b))),
            _ => None,
        }
    };
    ($root:expr, $closure:expr => $kp1:expr, $kp2:expr, $kp3:expr) => {
        match ($kp1.get($root), $kp2.get($root), $kp3.get($root)) {
            (Some(__a), Some(__b), Some(__c)) => Some($closure((__a, __b, __c))),
            _ => None,
        }
    };
    ($root:expr, $closure:expr => $kp1:expr, $kp2:expr, $kp3:expr, $kp4:expr) => {
        match (
            $kp1.get($root),
            $kp2.get($root),
            $kp3.get($root),
            $kp4.get($root),
        ) {
            (Some(__a), Some(__b), Some(__c), Some(__d)) => Some($closure((__a, __b, __c, __d))),
            _ => None,
        }
    };
    ($root:expr, $closure:expr => $kp1:expr, $kp2:expr, $kp3:expr, $kp4:expr, $kp5:expr) => {
        match (
            $kp1.get($root),
            $kp2.get($root),
            $kp3.get($root),
            $kp4.get($root),
            $kp5.get($root),
        ) {
            (Some(__a), Some(__b), Some(__c), Some(__d), Some(__e)) => {
                Some($closure((__a, __b, __c, __d, __e)))
            }
            _ => None,
        }
    };
    ($root:expr, $closure:expr => $kp1:expr, $kp2:expr, $kp3:expr, $kp4:expr, $kp5:expr, $kp6:expr) => {
        match (
            $kp1.get($root),
            $kp2.get($root),
            $kp3.get($root),
            $kp4.get($root),
            $kp5.get($root),
            $kp6.get($root),
        ) {
            (Some(__a), Some(__b), Some(__c), Some(__d), Some(__e), Some(__f)) => {
                Some($closure((__a, __b, __c, __d, __e, __f)))
            }
            _ => None,
        }
    };
}

/// Kp will force dev to create get and set while value will be owned
pub type KpValue<'a, R, V> = Kp<
    R,
    V,
    &'a R,
    V, // Returns owned V, not &V
    &'a mut R,
    V, // Returns owned V, not &mut V
    for<'b> fn(&'b R) -> Option<V>,
    for<'b> fn(&'b mut R) -> Option<V>,
>;

/// Kp will force dev to create get and set while root and value both will be owned
pub type KpOwned<R, V> = Kp<
    R,
    V,
    R,
    V, // Returns owned V, not &V
    R,
    V, // Returns owned V, not &mut V
    fn(R) -> Option<V>,
    fn(R) -> Option<V>,
>;

/// Kp will force dev to create get and set while taking full ownership of the Root while returning Root as value.
pub type KpRoot<R> = Kp<
    R,
    R,
    R,
    R, // Returns owned V, not &V
    R,
    R, // Returns owned V, not &mut V
    fn(R) -> Option<R>,
    fn(R) -> Option<R>,
>;

/// Kp for void - experimental
pub type KpVoid = Kp<(), (), (), (), (), (), fn() -> Option<()>, fn() -> Option<()>>;

pub type KpDynamic<R, V> = Kp<
    R,
    V,
    &'static R,
    &'static V,
    &'static mut R,
    &'static mut V,
    Box<dyn for<'a> Fn(&'a R) -> Option<&'a V> + Send + Sync>,
    Box<dyn for<'a> Fn(&'a mut R) -> Option<&'a mut V> + Send + Sync>,
>;

pub type KpBox<'a, R, V> = Kp<
    R,
    V,
    &'a R,
    &'a V,
    &'a mut R,
    &'a mut V,
    Box<dyn Fn(&'a R) -> Option<&'a V> + 'a>,
    Box<dyn Fn(&'a mut R) -> Option<&'a mut V> + 'a>,
>;

pub type KpArc<'a, R, V> = Kp<
    R,
    V,
    &'a R,
    &'a V,
    &'a mut R,
    &'a mut V,
    Arc<dyn Fn(&'a R) -> Option<&'a V> + Send + Sync + 'a>,
    Arc<dyn Fn(&'a mut R) -> Option<&'a mut V> + Send + Sync + 'a>,
>;

pub type KpType<'a, R, V> = Kp<
    R,
    V,
    &'a R,
    &'a V,
    &'a mut R,
    &'a mut V,
    for<'b> fn(&'b R) -> Option<&'b V>,
    for<'b> fn(&'b mut R) -> Option<&'b mut V>,
>;

pub type KpTraitType<'a, R, V> = dyn KpTrait<
        R,
        V,
        &'a R,
        &'a V,
        &'a mut R,
        &'a mut V,
        for<'b> fn(&'b R) -> Option<&'b V>,
        for<'b> fn(&'b mut R) -> Option<&'b mut V>,
    >;

/// Keypath for `Option<RefCell<T>>`: `get` returns `Option<Ref<V>>` so the caller holds the guard.
/// Use `.get(root).as_ref().map(std::cell::Ref::deref)` to get `Option<&V>` while the `Ref` is in scope.
pub type KpOptionRefCellType<'a, R, V> = Kp<
    R,
    V,
    &'a R,
    std::cell::Ref<'a, V>,
    &'a mut R,
    std::cell::RefMut<'a, V>,
    for<'b> fn(&'b R) -> Option<std::cell::Ref<'b, V>>,
    for<'b> fn(&'b mut R) -> Option<std::cell::RefMut<'b, V>>,
>;

impl<'a, R, V> KpType<'a, R, V> {
    /// Converts this keypath to [KpDynamic] for dynamic dispatch and storage (e.g. in a struct field).
    #[inline]
    pub fn to_dynamic(self) -> KpDynamic<R, V> {
        self.into()
    }
}

impl<'a, R, V> From<KpType<'a, R, V>> for KpDynamic<R, V> {
    #[inline]
    fn from(kp: KpType<'a, R, V>) -> Self {
        let get_fn = kp.get;
        let set_fn = kp.set;
        Kp::new(
            Box::new(move |t: &R| get_fn(t)),
            Box::new(move |t: &mut R| set_fn(t)),
        )
    }
}

impl<R, V, Root, Value, MutRoot, MutValue, G, S> Kp<R, V, Root, Value, MutRoot, MutValue, G, S>
where
    Root: std::borrow::Borrow<R>,
    Value: std::borrow::Borrow<V>,
    MutRoot: std::borrow::BorrowMut<R>,
    MutValue: std::borrow::BorrowMut<V>,
    G: Fn(Root) -> Option<Value> + Send + Sync + 'static,
    S: Fn(MutRoot) -> Option<MutValue> + Send + Sync + 'static,
    R: 'static,
    V: 'static,
{
    /// Erases getter/setter type into [`KpDynamic`] so you can store composed paths (e.g. after [KpTrait::then]).
    ///
    /// `#[derive(Kp)]` methods return [`KpType`] (`fn` pointers); chaining with `.then()` produces opaque closures.
    /// Neither matches a fixed `KpType<…>` field type—use `KpDynamic<R, V>` and `.into_dynamic()` (or
    /// [KpType::to_dynamic] for a single segment).
    ///
    /// # Safety
    ///
    /// This uses a small amount of `unsafe` internally: it re-interprets `&R` / `&mut R` as `Root` / `MutRoot`.
    /// That matches every [`Kp`] built from this crate’s public API ([`Kp::new`] on reference-shaped handles,
    /// `#[derive(Kp)]`, and [KpTrait::then] / [Kp::then] on those paths). Do not call this on a custom [`Kp`]
    /// whose `Root` / `MutRoot` are not layout-compatible with `&R` / `&mut R` or whose getters keep borrows
    /// alive past the call.
    #[inline]
    pub fn into_dynamic(self) -> KpDynamic<R, V> {
        let g = self.get;
        let s = self.set;
        Kp::new(
            Box::new(move |t: &R| unsafe {
                // SAFETY: See `into_dynamic` rustdoc. `Root` is `&'_ R` for supported keypaths.
                // debug_assert_eq!(std::mem::size_of::<Root>(), std::mem::size_of::<&R>());
                let root: Root = std::mem::transmute_copy(&t);
                match g(root) {
                    None => None,
                    Some(v) => {
                        let r: &V = std::borrow::Borrow::borrow(&v);
                        // Well-behaved getters return a view into `*t`; re-attach to this call's `&R`.
                        Some(std::mem::transmute::<&V, &V>(r))
                    }
                }
            }),
            Box::new(move |t: &mut R| unsafe {
                // debug_assert_eq!(std::mem::size_of::<MutRoot>(), std::mem::size_of::<&mut R>());
                let root: MutRoot = std::mem::transmute_copy(&t);
                match s(root) {
                    None => None,
                    Some(mut v) => {
                        let r: &mut V = std::borrow::BorrowMut::borrow_mut(&mut v);
                        Some(std::mem::transmute::<&mut V, &mut V>(r))
                    }
                }
            }),
        )
    }
}

// pub type KpType<R, V> = Kp<
//     R,
//     V,
//     &'static R,
//     &'static V,
//     &'static mut R,
//     &'static mut V,
//     for<'a> fn(&'a R) -> Option<&'a V>,
//     for<'a> fn(&'a mut R) -> Option<&'a mut V>,
// >;

// struct A{
//     b: std::sync::Arc<std::sync::Mutex<B>>,
// }
// struct B{
//     c: C
// }
// struct C{
//     d: String
// }

// pub struct SyncKp {
//     first: KpType<'static, A, B>,
//     mid: KpType<'static, std::sync::Mutex<B>, B>,
//     second: KpType<'static, B, C>,
// }
//
// impl SyncKp {
//     fn then(&self, kp: KpType<'static, B, String>) {
//
//     }
//     fn then_sync() {}
// }

// New type alias for composed/transformed keypaths
pub type KpComposed<R, V> = Kp<
    R,
    V,
    &'static R,
    &'static V,
    &'static mut R,
    &'static mut V,
    Box<dyn for<'b> Fn(&'b R) -> Option<&'b V> + Send + Sync>,
    Box<dyn for<'b> Fn(&'b mut R) -> Option<&'b mut V> + Send + Sync>,
>;

impl<R, V>
    Kp<
        R,
        V,
        &'static R,
        &'static V,
        &'static mut R,
        &'static mut V,
        Box<dyn for<'b> Fn(&'b R) -> Option<&'b V> + Send + Sync>,
        Box<dyn for<'b> Fn(&'b mut R) -> Option<&'b mut V> + Send + Sync>,
    >
{
    /// Build a keypath from two closures (e.g. when they capture a variable like an index).
    /// Same pattern as `Kp::new` in lock.rs; use this when the keypath captures variables.
    pub fn from_closures<G, S>(get: G, set: S) -> Self
    where
        G: for<'b> Fn(&'b R) -> Option<&'b V> + Send + Sync + 'static,
        S: for<'b> Fn(&'b mut R) -> Option<&'b mut V> + Send + Sync + 'static,
    {
        Self::new(Box::new(get), Box::new(set))
    }
}

pub struct AKp {
    getter: Rc<dyn for<'r> Fn(&'r dyn Any) -> Option<&'r dyn Any>>,
    root_type_id: TypeId,
    value_type_id: TypeId,
}

impl AKp {
    /// Create a new AKp from a KpType (the common reference-based keypath)
    pub fn new<'a, R, V>(keypath: KpType<'a, R, V>) -> Self
    where
        R: Any + 'static,
        V: Any + 'static,
    {
        let root_type_id = TypeId::of::<R>();
        let value_type_id = TypeId::of::<V>();
        let getter_fn = keypath.get;

        Self {
            getter: Rc::new(move |any: &dyn Any| {
                if let Some(root) = any.downcast_ref::<R>() {
                    getter_fn(root).map(|value: &V| value as &dyn Any)
                } else {
                    None
                }
            }),
            root_type_id,
            value_type_id,
        }
    }

    /// Create an AKp from a KpType (alias for `new()`)
    pub fn from<'a, R, V>(keypath: KpType<'a, R, V>) -> Self
    where
        R: Any + 'static,
        V: Any + 'static,
    {
        Self::new(keypath)
    }

    /// Get the value as a trait object (with root type checking)
    pub fn get<'r>(&self, root: &'r dyn Any) -> Option<&'r dyn Any> {
        (self.getter)(root)
    }

    /// Get the TypeId of the Root type
    pub fn root_type_id(&self) -> TypeId {
        self.root_type_id
    }

    /// Get the TypeId of the Value type
    pub fn value_type_id(&self) -> TypeId {
        self.value_type_id
    }

    /// Try to get the value with full type checking
    pub fn get_as<'a, Root: Any, Value: Any>(&self, root: &'a Root) -> Option<Option<&'a Value>> {
        if self.root_type_id == TypeId::of::<Root>() && self.value_type_id == TypeId::of::<Value>()
        {
            Some(
                self.get(root as &dyn Any)
                    .and_then(|any| any.downcast_ref::<Value>()),
            )
        } else {
            None
        }
    }

    /// Get a human-readable name for the value type
    pub fn kind_name(&self) -> String {
        format!("{:?}", self.value_type_id)
    }

    /// Get a human-readable name for the root type
    pub fn root_kind_name(&self) -> String {
        format!("{:?}", self.root_type_id)
    }

    /// Adapt this keypath to work with Arc<Root> instead of Root
    pub fn for_arc<Root>(&self) -> AKp
    where
        Root: Any + 'static,
    {
        let value_type_id = self.value_type_id;
        let getter = self.getter.clone();

        AKp {
            getter: Rc::new(move |any: &dyn Any| {
                if let Some(arc) = any.downcast_ref::<Arc<Root>>() {
                    getter(arc.as_ref() as &dyn Any)
                } else {
                    None
                }
            }),
            root_type_id: TypeId::of::<Arc<Root>>(),
            value_type_id,
        }
    }

    /// Adapt this keypath to work with Box<Root> instead of Root
    pub fn for_box<Root>(&self) -> AKp
    where
        Root: Any + 'static,
    {
        let value_type_id = self.value_type_id;
        let getter = self.getter.clone();

        AKp {
            getter: Rc::new(move |any: &dyn Any| {
                if let Some(boxed) = any.downcast_ref::<Box<Root>>() {
                    getter(boxed.as_ref() as &dyn Any)
                } else {
                    None
                }
            }),
            root_type_id: TypeId::of::<Box<Root>>(),
            value_type_id,
        }
    }

    /// Adapt this keypath to work with Rc<Root> instead of Root
    pub fn for_rc<Root>(&self) -> AKp
    where
        Root: Any + 'static,
    {
        let value_type_id = self.value_type_id;
        let getter = self.getter.clone();

        AKp {
            getter: Rc::new(move |any: &dyn Any| {
                if let Some(rc) = any.downcast_ref::<Rc<Root>>() {
                    getter(rc.as_ref() as &dyn Any)
                } else {
                    None
                }
            }),
            root_type_id: TypeId::of::<Rc<Root>>(),
            value_type_id,
        }
    }

    /// Adapt this keypath to work with Option<Root> instead of Root
    pub fn for_option<Root>(&self) -> AKp
    where
        Root: Any + 'static,
    {
        let value_type_id = self.value_type_id;
        let getter = self.getter.clone();

        AKp {
            getter: Rc::new(move |any: &dyn Any| {
                if let Some(opt) = any.downcast_ref::<Option<Root>>() {
                    opt.as_ref().and_then(|root| getter(root as &dyn Any))
                } else {
                    None
                }
            }),
            root_type_id: TypeId::of::<Option<Root>>(),
            value_type_id,
        }
    }

    /// Adapt this keypath to work with Result<Root, E> instead of Root
    pub fn for_result<Root, E>(&self) -> AKp
    where
        Root: Any + 'static,
        E: Any + 'static,
    {
        let value_type_id = self.value_type_id;
        let getter = self.getter.clone();

        AKp {
            getter: Rc::new(move |any: &dyn Any| {
                if let Some(result) = any.downcast_ref::<Result<Root, E>>() {
                    result
                        .as_ref()
                        .ok()
                        .and_then(|root| getter(root as &dyn Any))
                } else {
                    None
                }
            }),
            root_type_id: TypeId::of::<Result<Root, E>>(),
            value_type_id,
        }
    }

    /// Map the value through a transformation function with type checking
    /// Both original and mapped values must implement Any
    ///
    /// # Example
    /// ```
    /// use rust_key_paths::{AKp, Kp, KpType};
    /// struct User { name: String }
    /// let user = User { name: "Akash".to_string() };
    /// let name_kp = KpType::new(|u: &User| Some(&u.name), |_| None);
    /// let name_akp = AKp::new(name_kp);
    /// let len_akp = name_akp.map::<User, String, _, _>(|s| s.len());
    /// ```
    pub fn map<Root, OrigValue, MappedValue, F>(&self, mapper: F) -> AKp
    where
        Root: Any + 'static,
        OrigValue: Any + 'static,
        MappedValue: Any + 'static,
        F: Fn(&OrigValue) -> MappedValue + 'static,
    {
        let orig_root_type_id = self.root_type_id;
        let orig_value_type_id = self.value_type_id;
        let getter = self.getter.clone();
        let mapped_type_id = TypeId::of::<MappedValue>();

        AKp {
            getter: Rc::new(move |any_root: &dyn Any| {
                // Check root type matches
                if any_root.type_id() == orig_root_type_id {
                    getter(any_root).and_then(|any_value| {
                        // Verify the original value type matches
                        if orig_value_type_id == TypeId::of::<OrigValue>() {
                            any_value.downcast_ref::<OrigValue>().map(|orig_val| {
                                let mapped = mapper(orig_val);
                                // Box the mapped value and return as &dyn Any
                                Box::leak(Box::new(mapped)) as &dyn Any
                            })
                        } else {
                            None
                        }
                    })
                } else {
                    None
                }
            }),
            root_type_id: orig_root_type_id,
            value_type_id: mapped_type_id,
        }
    }

    /// Filter the value based on a predicate with full type checking
    /// Returns None if types don't match or predicate fails
    ///
    /// # Example
    /// ```
    /// use rust_key_paths::{AKp, Kp, KpType};
    /// struct User { age: i32 }
    /// let user = User { age: 30 };
    /// let age_kp = KpType::new(|u: &User| Some(&u.age), |_| None);
    /// let age_akp = AKp::new(age_kp);
    /// let adult_akp = age_akp.filter::<User, i32, _>(|age| *age >= 18);
    /// ```
    pub fn filter<Root, Value, F>(&self, predicate: F) -> AKp
    where
        Root: Any + 'static,
        Value: Any + 'static,
        F: Fn(&Value) -> bool + 'static,
    {
        let orig_root_type_id = self.root_type_id;
        let orig_value_type_id = self.value_type_id;
        let getter = self.getter.clone();

        AKp {
            getter: Rc::new(move |any_root: &dyn Any| {
                // Check root type matches
                if any_root.type_id() == orig_root_type_id {
                    getter(any_root).filter(|any_value| {
                        // Type check value and apply predicate
                        if orig_value_type_id == TypeId::of::<Value>() {
                            any_value
                                .downcast_ref::<Value>()
                                .map(|val| predicate(val))
                                .unwrap_or(false)
                        } else {
                            false
                        }
                    })
                } else {
                    None
                }
            }),
            root_type_id: orig_root_type_id,
            value_type_id: orig_value_type_id,
        }
    }
}

impl fmt::Debug for AKp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AKp")
            .field("root_type_id", &self.root_type_id)
            .field("value_type_id", &self.value_type_id)
            .finish_non_exhaustive()
    }
}

impl fmt::Display for AKp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "AKp(root_type_id={:?}, value_type_id={:?})",
            self.root_type_id, self.value_type_id
        )
    }
}

pub struct PKp<Root> {
    getter: Rc<dyn for<'r> Fn(&'r Root) -> Option<&'r dyn Any>>,
    value_type_id: TypeId,
    _phantom: std::marker::PhantomData<Root>,
}

impl<Root> PKp<Root>
where
    Root: 'static,
{
    /// Create a new PKp from a KpType (the common reference-based keypath)
    pub fn new<'a, V>(keypath: KpType<'a, Root, V>) -> Self
    where
        V: Any + 'static,
    {
        let value_type_id = TypeId::of::<V>();
        let getter_fn = keypath.get;

        Self {
            getter: Rc::new(move |root: &Root| getter_fn(root).map(|val: &V| val as &dyn Any)),
            value_type_id,
            _phantom: std::marker::PhantomData,
        }
    }

    /// Create a PKp from a KpType (alias for `new()`)
    pub fn from<'a, V>(keypath: KpType<'a, Root, V>) -> Self
    where
        V: Any + 'static,
    {
        Self::new(keypath)
    }

    /// Get the value as a trait object
    pub fn get<'r>(&self, root: &'r Root) -> Option<&'r dyn Any> {
        (self.getter)(root)
    }

    /// Get the TypeId of the Value type
    pub fn value_type_id(&self) -> TypeId {
        self.value_type_id
    }

    /// Try to downcast the result to a specific type
    pub fn get_as<'a, Value: Any>(&self, root: &'a Root) -> Option<&'a Value> {
        if self.value_type_id == TypeId::of::<Value>() {
            self.get(root).and_then(|any| any.downcast_ref::<Value>())
        } else {
            None
        }
    }

    /// Get a human-readable name for the value type
    pub fn kind_name(&self) -> String {
        format!("{:?}", self.value_type_id)
    }

    /// Adapt this keypath to work with Arc<Root> instead of Root
    pub fn for_arc(&self) -> PKp<Arc<Root>> {
        let getter = self.getter.clone();
        let value_type_id = self.value_type_id;

        PKp {
            getter: Rc::new(move |arc: &Arc<Root>| getter(arc.as_ref())),
            value_type_id,
            _phantom: std::marker::PhantomData,
        }
    }

    /// Adapt this keypath to work with Box<Root> instead of Root
    pub fn for_box(&self) -> PKp<Box<Root>> {
        let getter = self.getter.clone();
        let value_type_id = self.value_type_id;

        PKp {
            getter: Rc::new(move |boxed: &Box<Root>| getter(boxed.as_ref())),
            value_type_id,
            _phantom: std::marker::PhantomData,
        }
    }

    /// Adapt this keypath to work with Rc<Root> instead of Root
    pub fn for_rc(&self) -> PKp<Rc<Root>> {
        let getter = self.getter.clone();
        let value_type_id = self.value_type_id;

        PKp {
            getter: Rc::new(move |rc: &Rc<Root>| getter(rc.as_ref())),
            value_type_id,
            _phantom: std::marker::PhantomData,
        }
    }

    /// Adapt this keypath to work with Option<Root> instead of Root
    pub fn for_option(&self) -> PKp<Option<Root>> {
        let getter = self.getter.clone();
        let value_type_id = self.value_type_id;

        PKp {
            getter: Rc::new(move |opt: &Option<Root>| opt.as_ref().and_then(|root| getter(root))),
            value_type_id,
            _phantom: std::marker::PhantomData,
        }
    }

    /// Adapt this keypath to work with Result<Root, E> instead of Root
    pub fn for_result<E>(&self) -> PKp<Result<Root, E>>
    where
        E: 'static,
    {
        let getter = self.getter.clone();
        let value_type_id = self.value_type_id;

        PKp {
            getter: Rc::new(move |result: &Result<Root, E>| {
                result.as_ref().ok().and_then(|root| getter(root))
            }),
            value_type_id,
            _phantom: std::marker::PhantomData,
        }
    }

    /// Map the value through a transformation function
    /// The mapped value must also implement Any for type erasure
    ///
    /// # Example
    /// ```
    /// use rust_key_paths::{Kp, KpType, PKp};
    /// struct User { name: String }
    /// let user = User { name: "Akash".to_string() };
    /// let name_kp = KpType::new(|u: &User| Some(&u.name), |_| None);
    /// let name_pkp = PKp::new(name_kp);
    /// let len_pkp = name_pkp.map::<String, _, _>(|s| s.len());
    /// assert_eq!(len_pkp.get_as::<usize>(&user), Some(&5));
    /// ```
    pub fn map<OrigValue, MappedValue, F>(&self, mapper: F) -> PKp<Root>
    where
        OrigValue: Any + 'static,
        MappedValue: Any + 'static,
        F: Fn(&OrigValue) -> MappedValue + 'static,
    {
        let orig_type_id = self.value_type_id;
        let getter = self.getter.clone();
        let mapped_type_id = TypeId::of::<MappedValue>();

        PKp {
            getter: Rc::new(move |root: &Root| {
                getter(root).and_then(|any_value| {
                    // Verify the original type matches
                    if orig_type_id == TypeId::of::<OrigValue>() {
                        any_value.downcast_ref::<OrigValue>().map(|orig_val| {
                            let mapped = mapper(orig_val);
                            // Box the mapped value and return as &dyn Any
                            // Note: This creates a new allocation
                            Box::leak(Box::new(mapped)) as &dyn Any
                        })
                    } else {
                        None
                    }
                })
            }),
            value_type_id: mapped_type_id,
            _phantom: std::marker::PhantomData,
        }
    }

    /// Filter the value based on a predicate with type checking
    /// Returns None if the type doesn't match or predicate fails
    ///
    /// # Example
    /// ```
    /// use rust_key_paths::{Kp, KpType, PKp};
    /// struct User { age: i32 }
    /// let user = User { age: 30 };
    /// let age_kp = KpType::new(|u: &User| Some(&u.age), |_| None);
    /// let age_pkp = PKp::new(age_kp);
    /// let adult_pkp = age_pkp.filter::<i32, _>(|age| *age >= 18);
    /// assert_eq!(adult_pkp.get_as::<i32>(&user), Some(&30));
    /// ```
    pub fn filter<Value, F>(&self, predicate: F) -> PKp<Root>
    where
        Value: Any + 'static,
        F: Fn(&Value) -> bool + 'static,
    {
        let orig_type_id = self.value_type_id;
        let getter = self.getter.clone();

        PKp {
            getter: Rc::new(move |root: &Root| {
                getter(root).filter(|any_value| {
                    // Type check and apply predicate
                    if orig_type_id == TypeId::of::<Value>() {
                        any_value
                            .downcast_ref::<Value>()
                            .map(|val| predicate(val))
                            .unwrap_or(false)
                    } else {
                        false
                    }
                })
            }),
            value_type_id: orig_type_id,
            _phantom: std::marker::PhantomData,
        }
    }
}

impl<Root> fmt::Debug for PKp<Root> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PKp")
            .field("root_ty", &std::any::type_name::<Root>())
            .field("value_type_id", &self.value_type_id)
            .finish_non_exhaustive()
    }
}

impl<Root> fmt::Display for PKp<Root> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "PKp<{}, value_type_id={:?}>",
            std::any::type_name::<Root>(),
            self.value_type_id
        )
    }
}

/// `Kp` — typed keypath with getter/setter closures. See also [AKp] for type-erased keypaths.
///
/// # Mutation: get vs get_mut (setter path)
///
/// - **[get](Kp::get)** uses the `get` closure (getter): `Fn(Root) -> Option<Value>`
/// - **[get_mut](Kp::get_mut)** uses the `set` closure (setter): `Fn(MutRoot) -> Option<MutValue>`
///
/// When mutating through a Kp, the **setter path** is used—`get_mut` invokes the `set` closure,
/// not the `get` closure. The getter is for read-only access only.
///
/// For manual reference-shaped paths, [`constrain_get`] and [`constrain_set`] help closures satisfy
/// `for<'b> Fn(&'b R) -> Option<&'b V>`; use [`Kp::get_ref`] / [`Kp::get_mut_ref`] to call them explicitly.
#[derive(Clone)]
pub struct Kp<R, V, Root, Value, MutRoot, MutValue, G, S>
where
    Root: std::borrow::Borrow<R>,
    MutRoot: std::borrow::BorrowMut<R>,
    MutValue: std::borrow::BorrowMut<V>,
    G: Fn(Root) -> Option<Value>,
    S: Fn(MutRoot) -> Option<MutValue>,
{
    /// Getter closure: used by [`Kp::get`] for read-only access when `G` satisfies the HRTB.
    get: G,
    /// Setter closure: used by [`Kp::get_mut`] for mutation when `S` satisfies the HRTB.
    set: S,
    _p: std::marker::PhantomData<(R, V, Root, Value, MutRoot, MutValue)>,
}

/// Forces the compiler to treat a closure as `for<'b> Fn(&'b R) -> Option<&'b V>`.
#[inline]
pub fn constrain_get<R, V, F>(f: F) -> F
where
    F: for<'b> Fn(&'b R) -> Option<&'b V>,
{
    f
}

/// Forces the compiler to treat a closure as `for<'b> Fn(&'b mut R) -> Option<&'b mut V>`.
#[inline]
pub fn constrain_set<R, V, F>(f: F) -> F
where
    F: for<'b> Fn(&'b mut R) -> Option<&'b mut V>,
{
    f
}

impl<R, V, Root, Value, MutRoot, MutValue, G, S> Kp<R, V, Root, Value, MutRoot, MutValue, G, S>
where
    Root: std::borrow::Borrow<R>,
    Value: std::borrow::Borrow<V>,
    MutRoot: std::borrow::BorrowMut<R>,
    MutValue: std::borrow::BorrowMut<V>,
    G: Fn(Root) -> Option<Value>,
    S: Fn(MutRoot) -> Option<MutValue>,
{
    pub fn new(get: G, set: S) -> Self {
        Self {
            get,
            set,
            _p: std::marker::PhantomData,
        }
    }

    /// Read through the getter closure. For reference-shaped keypaths built with [`constrain_get`]
    /// / [`constrain_set`], you can also call this as `kp.get(root)` with `root: Root` (often `&R`).
    #[inline]
    pub fn get(&self, root: Root) -> Option<Value> {
        (self.get)(root)
    }

    /// Mutate through the setter closure.
    #[inline]
    pub fn get_mut(&self, root: MutRoot) -> Option<MutValue> {
        (self.set)(root)
    }

    /// Higher-ranked read when `G: for<'b> Fn(&'b R) -> Option<&'b V>` (e.g. manual keypaths using
    /// [`constrain_get`]). Prefer [`get`](Kp::get) for generic [`Kp`] including mapped values.
    #[inline]
    pub fn get_ref<'a>(&self, root: &'a R) -> Option<&'a V>
    where
        G: for<'b> Fn(&'b R) -> Option<&'b V>,
    {
        (self.get)(root)
    }

    /// Higher-ranked write when `S: for<'b> Fn(&'b mut R) -> Option<&'b mut V>`.
    #[inline]
    pub fn get_mut_ref<'a>(&self, root: &'a mut R) -> Option<&'a mut V>
    where
        S: for<'b> Fn(&'b mut R) -> Option<&'b mut V>,
    {
        (self.set)(root)
    }

    #[inline]
    pub fn then<SV, G2, S2>(
        self,
        next: Kp<
            V,
            SV,
            &'static V, // ← concrete ref types, not free Value/SubValue/MutSubValue
            &'static SV,
            &'static mut V,
            &'static mut SV,
            G2,
            S2,
        >,
    ) -> Kp<
        R,
        SV,
        &'static R,
        &'static SV,
        &'static mut R,
        &'static mut SV,
        impl for<'b> Fn(&'b R) -> Option<&'b SV>,
        impl for<'b> Fn(&'b mut R) -> Option<&'b mut SV>,
    >
    where
        G: for<'b> Fn(&'b R) -> Option<&'b V>,
        S: for<'b> Fn(&'b mut R) -> Option<&'b mut V>,
        G2: for<'b> Fn(&'b V) -> Option<&'b SV>,
        S2: for<'b> Fn(&'b mut V) -> Option<&'b mut SV>,
    {
        let first_get = self.get;
        let first_set = self.set;
        let second_get = next.get;
        let second_set = next.set;

        Kp::new(
            constrain_get(move |root: &R| first_get(root).and_then(|value| second_get(value))),
            constrain_set(move |root: &mut R| first_set(root).and_then(|value| second_set(value))),
        )
    }

}

impl<R, V, Root, Value, MutRoot, MutValue, G, S> fmt::Debug
    for Kp<R, V, Root, Value, MutRoot, MutValue, G, S>
where
    Root: std::borrow::Borrow<R>,
    Value: std::borrow::Borrow<V>,
    MutRoot: std::borrow::BorrowMut<R>,
    MutValue: std::borrow::BorrowMut<V>,
    G: Fn(Root) -> Option<Value>,
    S: Fn(MutRoot) -> Option<MutValue>,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Kp")
            .field("root_ty", &std::any::type_name::<R>())
            .field("value_ty", &std::any::type_name::<V>())
            .finish_non_exhaustive()
    }
}

impl<R, V, Root, Value, MutRoot, MutValue, G, S> fmt::Display
    for Kp<R, V, Root, Value, MutRoot, MutValue, G, S>
where
    Root: std::borrow::Borrow<R>,
    Value: std::borrow::Borrow<V>,
    MutRoot: std::borrow::BorrowMut<R>,
    MutValue: std::borrow::BorrowMut<V>,
    G: Fn(Root) -> Option<Value>,
    S: Fn(MutRoot) -> Option<MutValue>,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Kp<{}, {}>",
            std::any::type_name::<R>(),
            std::any::type_name::<V>()
        )
    }
}

/// Zip two keypaths together to create a tuple
/// Works only with KpType (reference-based keypaths)
///
/// # Example
/// ```
/// use rust_key_paths::{KpType, zip_kps};
/// struct User { name: String, age: i32 }
/// let user = User { name: "Akash".to_string(), age: 30 };
/// let name_kp = KpType::new(|u: &User| Some(&u.name), |_| None);
/// let age_kp = KpType::new(|u: &User| Some(&u.age), |_| None);
/// let zipped_fn = zip_kps(&name_kp, &age_kp);
/// assert_eq!(zipped_fn(&user), Some((&"Akash".to_string(), &30)));
/// ```
pub fn zip_kps<'a, RootType, Value1, Value2>(
    kp1: &'a KpType<'a, RootType, Value1>,
    kp2: &'a KpType<'a, RootType, Value2>,
) -> impl Fn(&'a RootType) -> Option<(&'a Value1, &'a Value2)> + 'a
where
    RootType: 'a,
    Value1: 'a,
    Value2: 'a,
{
    move |root: &'a RootType| {
        let val1 = (kp1.get)(root)?;
        let val2 = (kp2.get)(root)?;
        Some((val1, val2))
    }
}

impl<R, Root, MutRoot, G, S> Kp<R, R, Root, Root, MutRoot, MutRoot, G, S>
where
    Root: std::borrow::Borrow<R>,
    MutRoot: std::borrow::BorrowMut<R>,
    G: Fn(Root) -> Option<Root>,
    S: Fn(MutRoot) -> Option<MutRoot>,
{
    pub fn identity_typed() -> Kp<
        R,
        R,
        Root,
        Root,
        MutRoot,
        MutRoot,
        fn(Root) -> Option<Root>,
        fn(MutRoot) -> Option<MutRoot>,
    > {
        Kp::new(|r: Root| Some(r), |r: MutRoot| Some(r))
    }

    pub fn identity<'a>() -> KpType<'a, R, R> {
        KpType::new(|r| Some(r), |r| Some(r))
    }
}

// ========== ENUM KEYPATHS ==========

/// EnumKp - A keypath for enum variants that supports both extraction and embedding
/// Leverages the existing Kp architecture where optionals are built-in via Option<Value>
///
/// This struct serves dual purposes:
/// 1. As a concrete keypath instance for extracting and embedding enum variants
/// 2. As a namespace for static factory methods: `EnumKp::for_ok()`, `EnumKp::for_some()`, etc.
pub struct EnumKp<Enum, Variant, Root, Value, MutRoot, MutValue, G, S, E>
where
    Root: std::borrow::Borrow<Enum>,
    Value: std::borrow::Borrow<Variant>,
    MutRoot: std::borrow::BorrowMut<Enum>,
    MutValue: std::borrow::BorrowMut<Variant>,
    G: Fn(Root) -> Option<Value>,
    S: Fn(MutRoot) -> Option<MutValue>,
    E: Fn(Variant) -> Enum,
{
    extractor: Kp<Enum, Variant, Root, Value, MutRoot, MutValue, G, S>,
    embedder: E,
}

// EnumKp is a functional component; Send/Sync follow from extractor and embedder.
unsafe impl<Enum, Variant, Root, Value, MutRoot, MutValue, G, S, E> Send
    for EnumKp<Enum, Variant, Root, Value, MutRoot, MutValue, G, S, E>
where
    Root: std::borrow::Borrow<Enum>,
    Value: std::borrow::Borrow<Variant>,
    MutRoot: std::borrow::BorrowMut<Enum>,
    MutValue: std::borrow::BorrowMut<Variant>,
    G: Fn(Root) -> Option<Value> + Send,
    S: Fn(MutRoot) -> Option<MutValue> + Send,
    E: Fn(Variant) -> Enum + Send,
{
}
unsafe impl<Enum, Variant, Root, Value, MutRoot, MutValue, G, S, E> Sync
    for EnumKp<Enum, Variant, Root, Value, MutRoot, MutValue, G, S, E>
where
    Root: std::borrow::Borrow<Enum>,
    Value: std::borrow::Borrow<Variant>,
    MutRoot: std::borrow::BorrowMut<Enum>,
    MutValue: std::borrow::BorrowMut<Variant>,
    G: Fn(Root) -> Option<Value> + Sync,
    S: Fn(MutRoot) -> Option<MutValue> + Sync,
    E: Fn(Variant) -> Enum + Sync,
{
}

impl<Enum, Variant, Root, Value, MutRoot, MutValue, G, S, E>
    EnumKp<Enum, Variant, Root, Value, MutRoot, MutValue, G, S, E>
where
    Root: std::borrow::Borrow<Enum>,
    Value: std::borrow::Borrow<Variant>,
    MutRoot: std::borrow::BorrowMut<Enum>,
    MutValue: std::borrow::BorrowMut<Variant>,
    G: Fn(Root) -> Option<Value>,
    S: Fn(MutRoot) -> Option<MutValue>,
    E: Fn(Variant) -> Enum,
{
    /// Create a new EnumKp with extractor and embedder functions
    pub fn new(
        extractor: Kp<Enum, Variant, Root, Value, MutRoot, MutValue, G, S>,
        embedder: E,
    ) -> Self {
        Self {
            extractor,
            embedder,
        }
    }

    /// Extract the variant from an enum (returns None if wrong variant)
    pub fn get(&self, enum_value: Root) -> Option<Value> {
        (self.extractor.get)(enum_value)
    }

    /// Extract the variant mutably from an enum (returns None if wrong variant)
    pub fn get_mut(&self, enum_value: MutRoot) -> Option<MutValue> {
        (self.extractor.set)(enum_value)
    }

    /// Embed a value into the enum variant
    pub fn embed(&self, value: Variant) -> Enum {
        (self.embedder)(value)
    }

    /// Get the underlying Kp for composition with other keypaths
    pub fn as_kp(&self) -> &Kp<Enum, Variant, Root, Value, MutRoot, MutValue, G, S> {
        &self.extractor
    }

    /// Convert to Kp (loses embedding capability but gains composition)
    pub fn into_kp(self) -> Kp<Enum, Variant, Root, Value, MutRoot, MutValue, G, S> {
        self.extractor
    }

    /// Map the variant value through a transformation function
    ///
    /// # Example
    /// ```
    /// use rust_key_paths::enum_ok;
    /// let result: Result<String, i32> = Ok("hello".to_string());
    /// let ok_kp = enum_ok();
    /// let len_kp = ok_kp.map(|s: &String| s.len());
    /// assert_eq!(len_kp.get(&result), Some(5));
    /// ```
    pub fn map<MappedValue, F>(
        &self,
        mapper: F,
    ) -> EnumKp<
        Enum,
        MappedValue,
        Root,
        MappedValue,
        MutRoot,
        MappedValue,
        impl Fn(Root) -> Option<MappedValue>,
        impl Fn(MutRoot) -> Option<MappedValue>,
        impl Fn(MappedValue) -> Enum,
    >
    where
        // Copy: Required because mapper is used via extractor.map() which needs it
        // 'static: Required because the returned EnumKp must own its closures
        F: Fn(&Variant) -> MappedValue + Copy + 'static,
        Variant: 'static,
        MappedValue: 'static,
        // Copy: Required for embedder to be captured in the panic closure
        E: Fn(Variant) -> Enum + Copy + 'static,
    {
        let mapped_extractor = self.extractor.map(mapper);

        // Create a new embedder that maps back
        // Note: This is a limitation - we can't reverse the map for embedding
        // So we create a placeholder that panics
        let new_embedder = move |_value: MappedValue| -> Enum {
            panic!(
                "Cannot embed mapped values back into enum. Use the original EnumKp for embedding."
            )
        };

        EnumKp::new(mapped_extractor, new_embedder)
    }

    /// Filter the variant value based on a predicate
    /// Returns None if the predicate fails or if wrong variant
    ///
    /// # Example
    /// ```
    /// use rust_key_paths::enum_ok;
    /// let result: Result<i32, String> = Ok(42);
    /// let ok_kp = enum_ok();
    /// let positive_kp = ok_kp.filter(|x: &i32| *x > 0);
    /// assert_eq!(positive_kp.get(&result), Some(&42));
    /// ```
    pub fn filter<F>(
        &self,
        predicate: F,
    ) -> EnumKp<
        Enum,
        Variant,
        Root,
        Value,
        MutRoot,
        MutValue,
        impl Fn(Root) -> Option<Value>,
        impl Fn(MutRoot) -> Option<MutValue>,
        E,
    >
    where
        // Copy: Required because predicate is used via extractor.filter() which needs it
        // 'static: Required because the returned EnumKp must own its closures
        F: Fn(&Variant) -> bool + Copy + 'static,
        Variant: 'static,
        // Copy: Required to clone embedder into the new EnumKp
        E: Copy,
    {
        let filtered_extractor = self.extractor.filter(predicate);
        EnumKp::new(filtered_extractor, self.embedder)
    }
}

impl<Enum, Variant, Root, Value, MutRoot, MutValue, G, S, E> fmt::Debug
    for EnumKp<Enum, Variant, Root, Value, MutRoot, MutValue, G, S, E>
where
    Root: std::borrow::Borrow<Enum>,
    Value: std::borrow::Borrow<Variant>,
    MutRoot: std::borrow::BorrowMut<Enum>,
    MutValue: std::borrow::BorrowMut<Variant>,
    G: Fn(Root) -> Option<Value>,
    S: Fn(MutRoot) -> Option<MutValue>,
    E: Fn(Variant) -> Enum,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("EnumKp")
            .field("enum_ty", &std::any::type_name::<Enum>())
            .field("variant_ty", &std::any::type_name::<Variant>())
            .finish_non_exhaustive()
    }
}

impl<Enum, Variant, Root, Value, MutRoot, MutValue, G, S, E> fmt::Display
    for EnumKp<Enum, Variant, Root, Value, MutRoot, MutValue, G, S, E>
where
    Root: std::borrow::Borrow<Enum>,
    Value: std::borrow::Borrow<Variant>,
    MutRoot: std::borrow::BorrowMut<Enum>,
    MutValue: std::borrow::BorrowMut<Variant>,
    G: Fn(Root) -> Option<Value>,
    S: Fn(MutRoot) -> Option<MutValue>,
    E: Fn(Variant) -> Enum,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "EnumKp<{}, {}>",
            std::any::type_name::<Enum>(),
            std::any::type_name::<Variant>()
        )
    }
}

// Type alias for the common case with references
pub type EnumKpType<'a, Enum, Variant> = EnumKp<
    Enum,
    Variant,
    &'a Enum,
    &'a Variant,
    &'a mut Enum,
    &'a mut Variant,
    for<'b> fn(&'b Enum) -> Option<&'b Variant>,
    for<'b> fn(&'b mut Enum) -> Option<&'b mut Variant>,
    fn(Variant) -> Enum,
>;

// Static factory functions for creating EnumKp instances
/// Create an enum keypath with both extraction and embedding for a specific variant
///
/// # Example
/// ```
/// use rust_key_paths::enum_variant;
/// enum MyEnum {
///     A(String),
///     B(i32),
/// }
///
/// let kp = enum_variant(
///     |e: &MyEnum| match e { MyEnum::A(s) => Some(s), _ => None },
///     |e: &mut MyEnum| match e { MyEnum::A(s) => Some(s), _ => None },
///     |s: String| MyEnum::A(s)
/// );
/// ```
pub fn enum_variant<'a, Enum, Variant>(
    getter: for<'b> fn(&'b Enum) -> Option<&'b Variant>,
    setter: for<'b> fn(&'b mut Enum) -> Option<&'b mut Variant>,
    embedder: fn(Variant) -> Enum,
) -> EnumKpType<'a, Enum, Variant> {
    EnumKp::new(Kp::new(getter, setter), embedder)
}

/// Extract from Result<T, E> - Ok variant
///
/// # Example
/// ```
/// use rust_key_paths::enum_ok;
/// let result: Result<String, i32> = Ok("success".to_string());
/// let ok_kp = enum_ok();
/// assert_eq!(ok_kp.get(&result), Some(&"success".to_string()));
/// ```
pub fn enum_ok<'a, T, E>() -> EnumKpType<'a, Result<T, E>, T> {
    EnumKp::new(
        Kp::new(
            |r: &Result<T, E>| r.as_ref().ok(),
            |r: &mut Result<T, E>| r.as_mut().ok(),
        ),
        |t: T| Ok(t),
    )
}

/// Extract from Result<T, E> - Err variant
///
/// # Example
/// ```
/// use rust_key_paths::enum_err;
/// let result: Result<String, i32> = Err(42);
/// let err_kp = enum_err();
/// assert_eq!(err_kp.get(&result), Some(&42));
/// ```
pub fn enum_err<'a, T, E>() -> EnumKpType<'a, Result<T, E>, E> {
    EnumKp::new(
        Kp::new(
            |r: &Result<T, E>| r.as_ref().err(),
            |r: &mut Result<T, E>| r.as_mut().err(),
        ),
        |e: E| Err(e),
    )
}

/// Extract from Option<T> - Some variant
///
/// # Example
/// ```
/// use rust_key_paths::enum_some;
/// let opt = Some("value".to_string());
/// let some_kp = enum_some();
/// assert_eq!(some_kp.get(&opt), Some(&"value".to_string()));
/// ```
pub fn enum_some<'a, T>() -> EnumKpType<'a, Option<T>, T> {
    EnumKp::new(
        Kp::new(|o: &Option<T>| o.as_ref(), |o: &mut Option<T>| o.as_mut()),
        |t: T| Some(t),
    )
}

// Helper functions for creating enum keypaths with type inference
/// Create an enum keypath for a specific variant with type inference
///
/// # Example
/// ```
/// use rust_key_paths::variant_of;
/// enum MyEnum {
///     A(String),
///     B(i32),
/// }
///
/// let kp_a = variant_of(
///     |e: &MyEnum| match e { MyEnum::A(s) => Some(s), _ => None },
///     |e: &mut MyEnum| match e { MyEnum::A(s) => Some(s), _ => None },
///     |s: String| MyEnum::A(s)
/// );
/// ```
pub fn variant_of<'a, Enum, Variant>(
    getter: for<'b> fn(&'b Enum) -> Option<&'b Variant>,
    setter: for<'b> fn(&'b mut Enum) -> Option<&'b mut Variant>,
    embedder: fn(Variant) -> Enum,
) -> EnumKpType<'a, Enum, Variant> {
    enum_variant(getter, setter, embedder)
}

// ========== CONTAINER KEYPATHS ==========

// Helper functions for working with standard containers (Box, Arc, Rc)
/// Create a keypath for unwrapping Box<T> -> T
///
/// # Example
/// ```
/// use rust_key_paths::kp_box;
/// let boxed = Box::new("value".to_string());
/// let kp = kp_box();
/// assert_eq!(kp.get(&boxed), Some(&"value".to_string()));
/// ```
pub fn kp_box<'a, T>() -> KpType<'a, Box<T>, T> {
    Kp::new(
        |b: &Box<T>| Some(b.as_ref()),
        |b: &mut Box<T>| Some(b.as_mut()),
    )
}

/// Create a keypath for unwrapping Arc<T> -> T (read-only)
///
/// # Example
/// ```
/// use std::sync::Arc;
/// use rust_key_paths::kp_arc;
/// let arc = Arc::new("value".to_string());
/// let kp = kp_arc();
/// assert_eq!(kp.get(&arc), Some(&"value".to_string()));
/// ```
pub fn kp_arc<'a, T>() -> Kp<
    Arc<T>,
    T,
    &'a Arc<T>,
    &'a T,
    &'a mut Arc<T>,
    &'a mut T,
    for<'b> fn(&'b Arc<T>) -> Option<&'b T>,
    for<'b> fn(&'b mut Arc<T>) -> Option<&'b mut T>,
> {
    Kp::new(
        |arc: &Arc<T>| Some(arc.as_ref()),
        |arc: &mut Arc<T>| Arc::get_mut(arc),
    )
}

/// Create a keypath for unwrapping Rc<T> -> T (read-only)
///
/// # Example
/// ```
/// use std::rc::Rc;
/// use rust_key_paths::kp_rc;
/// let rc = Rc::new("value".to_string());
/// let kp = kp_rc();
/// assert_eq!(kp.get(&rc), Some(&"value".to_string()));
/// ```
pub fn kp_rc<'a, T>() -> Kp<
    std::rc::Rc<T>,
    T,
    &'a std::rc::Rc<T>,
    &'a T,
    &'a mut std::rc::Rc<T>,
    &'a mut T,
    for<'b> fn(&'b std::rc::Rc<T>) -> Option<&'b T>,
    for<'b> fn(&'b mut std::rc::Rc<T>) -> Option<&'b mut T>,
> {
    Kp::new(
        |rc: &std::rc::Rc<T>| Some(rc.as_ref()),
        |rc: &mut std::rc::Rc<T>| std::rc::Rc::get_mut(rc),
    )
}

// ========== PARTIAL KEYPATHS (Hide Value Type) ==========

use std::any::{Any, TypeId};
use std::rc::Rc;