eventkit-rs 0.5.6

A Rust library and CLI for managing macOS Calendar events and Reminders via EventKit
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
use block2::RcBlock;
use chrono::{DateTime, Datelike, Duration, Local, TimeZone, Timelike};
use objc2::Message;
use objc2::rc::Retained;
use objc2::runtime::Bool;
use objc2_event_kit::{
    EKAlarm, EKAlarmProximity, EKAlarmType, EKAuthorizationStatus, EKCalendar,
    EKCalendarEventAvailabilityMask, EKCalendarItem, EKEntityType, EKEvent, EKEventAvailability,
    EKEventStatus, EKEventStore, EKRecurrenceDayOfWeek, EKRecurrenceEnd, EKRecurrenceFrequency,
    EKRecurrenceRule, EKReminder, EKSource, EKSpan, EKStructuredLocation, EKWeekday,
};
use objc2_foundation::{
    NSArray, NSCalendar, NSDate, NSDateComponents, NSError, NSNumber, NSString,
};
use std::sync::{Arc, Condvar, Mutex};
use thiserror::Error;

#[cfg(feature = "location")]
#[path = "location.rs"]
pub mod location;

#[cfg(feature = "mcp")]
#[path = "mcp.rs"]
pub mod mcp;

/// Errors that can occur when working with EventKit
#[derive(Error, Debug)]
pub enum EventKitError {
    #[error("Authorization denied")]
    AuthorizationDenied,

    #[error("Authorization restricted by system policy")]
    AuthorizationRestricted,

    #[error("Authorization not determined")]
    AuthorizationNotDetermined,

    #[error("Failed to request authorization: {0}")]
    AuthorizationRequestFailed(String),

    #[error("No default calendar")]
    NoDefaultCalendar,

    #[error("Calendar not found: {0}")]
    CalendarNotFound(String),

    #[error("Item not found: {0}")]
    ItemNotFound(String),

    #[error("Failed to save: {0}")]
    SaveFailed(String),

    #[error("Failed to delete: {0}")]
    DeleteFailed(String),

    #[error("Failed to fetch: {0}")]
    FetchFailed(String),

    #[error("EventKit error: {0}")]
    EventKitError(String),

    #[error("Invalid date range")]
    InvalidDateRange,

    /// Returned when a string passed as a URL fails strict RFC 3986
    /// validation (`+[NSURL URLWithString:encodingInvalidCharacters:NO]`
    /// returned nil — invalid scheme, illegal characters, etc.).
    #[error("Invalid URL: {0}")]
    InvalidURL(String),
}

/// Backward compatibility alias
pub type RemindersError = EventKitError;

/// Result type for EventKit operations
pub type Result<T> = std::result::Result<T, EventKitError>;

/// Represents a reminder item with its properties
#[derive(Debug, Clone)]
#[allow(non_snake_case)]
pub struct ReminderItem {
    /// Unique identifier for the reminder
    pub identifier: String,
    /// Title of the reminder
    pub title: String,
    /// Optional notes/description
    pub notes: Option<String>,
    /// Whether the reminder is completed
    pub completed: bool,
    /// Priority (0 = none, 1-4 = high, 5 = medium, 6-9 = low)
    pub priority: usize,
    /// Calendar/list the reminder belongs to
    pub calendar_title: Option<String>,
    /// Calendar/list identifier
    pub calendar_id: Option<String>,
    /// Due date for the reminder
    pub due_date: Option<DateTime<Local>>,
    /// Start date (when to start working on it)
    pub start_date: Option<DateTime<Local>>,
    /// Completion date (when it was completed)
    pub completion_date: Option<DateTime<Local>>,
    /// External identifier for the reminder (server-provided)
    pub external_identifier: Option<String>,
    /// Location associated with the reminder
    pub location: Option<String>,
    /// URL associated with the reminder
    #[allow(non_snake_case)]
    pub URL: Option<String>,
    /// Creation date of the reminder
    pub creation_date: Option<DateTime<Local>>,
    /// Last modified date of the reminder
    pub last_modified_date: Option<DateTime<Local>>,
    /// Timezone of the reminder
    pub timezone: Option<String>,
    /// Timezone applied specifically to the due date — distinct from
    /// `timezone`, which is the item-level zone. EventKit lets these differ
    /// so a reminder can be "due at 9am New York time" regardless of the
    /// item's own zone or the device zone.
    pub due_date_timezone: Option<String>,
    /// Geofence attached to the reminder via a location-based alarm.
    /// `Some` when at least one alarm has a `structuredLocation` and
    /// non-`None` proximity. EventKit has no `structuredLocation` property
    /// directly on `EKReminder` / `EKCalendarItem` — it lives on the alarm.
    pub structured_location: Option<StructuredLocation>,
    /// Identifier of the parent reminder (when this reminder is a subtask).
    /// Read via KVC because the underlying type is the private `EKObjectID`.
    pub parent_id: Option<String>,
    /// Number of file attachments. Full metadata is not yet surfaced.
    pub attachments_count: usize,
    /// Whether the reminder has alarms
    pub has_alarms: bool,
    /// Whether the reminder has recurrence rules
    pub has_recurrence_rules: bool,
    /// Whether the reminder has attendees
    pub has_attendees: bool,
    /// Whether the reminder has notes
    pub has_notes: bool,
    /// Attendees on this reminder (usually empty, possible on shared lists)
    pub attendees: Vec<ParticipantInfo>,
}

/// Input for `RemindersManager::create_reminder`. All fields except `title`
/// are optional. Use `..Default::default()` for the unset ones.
#[derive(Debug, Clone, Default)]
#[allow(non_snake_case)]
pub struct ReminderDraft<'a> {
    pub title: &'a str,
    pub notes: Option<&'a str>,
    pub calendar_title: Option<&'a str>,
    pub priority: Option<usize>,
    pub due_date: Option<DateTime<Local>>,
    pub start_date: Option<DateTime<Local>>,
    #[allow(non_snake_case)]
    pub URL: Option<&'a str>,
    pub location: Option<&'a str>,
    /// Rich location for Reminders.app's location chip — writes
    /// `EKReminder.structuredLocation`. This is the field iCloud Reminders
    /// actually persists; the plain-string `location` above is a legacy
    /// CalDAV field that iCloud silently drops.
    pub structured_location: Option<&'a StructuredLocation>,
    /// IANA zone identifier for the due date, e.g. `"America/Los_Angeles"`.
    pub due_date_timezone: Option<&'a str>,
}

/// Input for `RemindersManager::update_reminder`. Each field uses one of:
/// `None` (don't touch), `Some(value)` (set), and for `Option<Option<T>>`
/// fields, `Some(None)` (clear). Build with `..Default::default()`.
#[derive(Debug, Clone, Default)]
#[allow(non_snake_case)]
pub struct ReminderPatch<'a> {
    pub title: Option<&'a str>,
    pub notes: Option<&'a str>,
    pub completed: Option<bool>,
    pub priority: Option<usize>,
    pub due_date: Option<Option<DateTime<Local>>>,
    pub start_date: Option<Option<DateTime<Local>>>,
    pub calendar_title: Option<&'a str>,
    #[allow(non_snake_case)]
    pub URL: Option<Option<&'a str>>,
    pub location: Option<Option<&'a str>>,
    /// Rich location (the iCloud-persisted chip). `Some(Some(loc))` sets,
    /// `Some(None)` clears, `None` leaves untouched.
    pub structured_location: Option<Option<&'a StructuredLocation>>,
    /// Same `Option<Option<...>>` semantics: `Some(Some("America/LA"))` sets,
    /// `Some(None)` clears, `None` leaves untouched.
    pub due_date_timezone: Option<Option<&'a str>>,
    /// Explicit completion date. Apple's `setCompletionDate:` is the
    /// authoritative completion toggle — a non-nil value implies
    /// `isCompleted = YES` and a nil value implies `NO`. We apply this
    /// **after** `completed` in `update_reminder`, so when both are
    /// provided the date wins.
    pub completion_date: Option<Option<DateTime<Local>>>,
}

/// Type of calendar/source.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CalendarType {
    Local,
    CalDAV,
    Exchange,
    Subscription,
    Birthday,
    Unknown,
}

/// An account source (iCloud, Local, Exchange, etc.)
#[derive(Debug, Clone)]
pub struct SourceInfo {
    pub identifier: String,
    pub title: String,
    pub source_type: String,
}

/// Represents a calendar (reminder list or event calendar).
#[derive(Debug, Clone)]
pub struct CalendarInfo {
    /// Unique identifier
    pub identifier: String,
    /// Title of the calendar
    pub title: String,
    /// Source name (e.g., iCloud, Local)
    pub source: Option<String>,
    /// Source identifier
    pub source_id: Option<String>,
    /// Calendar type
    pub calendar_type: CalendarType,
    /// Whether items can be added/modified/deleted
    pub allows_modifications: bool,
    /// Whether the calendar itself can be modified (renamed/deleted)
    pub is_immutable: bool,
    /// Whether this is a URL-subscribed read-only calendar
    pub is_subscribed: bool,
    /// Calendar color as RGBA (0.0-1.0)
    pub color: Option<(f64, f64, f64, f64)>,
    /// Entity types this calendar supports ("event", "reminder")
    pub allowed_entity_types: Vec<String>,
    /// Which `EventAvailability` values this calendar accepts on its events
    /// — string forms of `EKCalendarEventAvailabilityMask`: e.g.
    /// `["busy", "free", "tentative"]`. Empty when none are supported
    /// (`EKCalendarEventAvailabilityNone`, common on reminder-only calendars).
    /// Useful pre-flight check before `EventsManager::set_event_availability`.
    pub supported_event_availabilities: Vec<String>,
}

/// Proximity trigger for a location-based alarm.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AlarmProximity {
    /// No proximity trigger.
    #[default]
    None,
    /// Trigger when entering the location.
    Enter,
    /// Trigger when leaving the location.
    Leave,
}

/// A structured location for geofenced alarms.
#[derive(Debug, Clone)]
pub struct StructuredLocation {
    /// Display title for the location.
    pub title: String,
    /// Latitude of the location.
    pub latitude: f64,
    /// Longitude of the location.
    pub longitude: f64,
    /// Geofence radius in meters.
    pub radius: f64,
}

/// An alarm attached to a reminder or event.
#[derive(Debug, Clone, Default)]
pub struct AlarmInfo {
    /// Offset in seconds before the due date (negative = before).
    pub relative_offset: Option<f64>,
    /// Absolute date for the alarm (ISO 8601 string).
    pub absolute_date: Option<DateTime<Local>>,
    /// Proximity trigger (enter/leave geofence).
    pub proximity: AlarmProximity,
    /// Location for geofenced alarms.
    pub location: Option<StructuredLocation>,
    /// Email address for email-type alarms (CalDAV server-side notification).
    pub email_address: Option<String>,
    /// Custom alarm sound name (audio-type alarms).
    pub sound_name: Option<String>,
    /// URL opened when the alarm fires (procedure-type alarm). Distinct
    /// from `EKCalendarItem.URL` — that's lowercase `url` on `EKAlarm`.
    /// Apple deprecated this property in macOS 10.9 but the API still
    /// functions; we surface it for parity with the framework.
    pub url: Option<String>,
    /// Derived alarm type — Display/Audio/Procedure/Email. Apple infers
    /// this from which of the optional fields above are set. Read-only on
    /// output; ignored on input.
    pub alarm_type: AlarmType,
}

/// EKAlarm.type — derived by Apple from which optional fields are set:
/// `soundName` → Audio, `url` → Procedure, `emailAddress` → Email, else Display.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AlarmType {
    #[default]
    Display,
    Audio,
    Procedure,
    Email,
    Unknown,
}

/// How often a recurrence repeats.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum RecurrenceFrequency {
    #[default]
    Daily,
    Weekly,
    Monthly,
    Yearly,
}

/// When a recurrence ends.
#[derive(Debug, Clone, Default)]
pub enum RecurrenceEndCondition {
    /// Repeats forever.
    #[default]
    Never,
    /// Ends after a number of occurrences.
    AfterCount(usize),
    /// Ends on a specific date.
    OnDate(DateTime<Local>),
}

/// A recurrence rule describing how a reminder or event repeats.
#[derive(Debug, Clone, Default)]
pub struct RecurrenceRule {
    /// How often it repeats (daily, weekly, monthly, yearly).
    pub frequency: RecurrenceFrequency,
    /// Repeat every N intervals (e.g., every 2 weeks).
    pub interval: usize,
    /// When the recurrence ends.
    pub end: RecurrenceEndCondition,
    /// Days of the week (1=Sun..7=Sat) for weekly/monthly rules.
    pub days_of_week: Option<Vec<u8>>,
    /// Days of the month (1-31, negatives count from end) for monthly rules.
    pub days_of_month: Option<Vec<i32>>,
    /// Months of the year (1=Jan..12=Dec) for yearly rules.
    pub months_of_year: Option<Vec<i32>>,
    /// Weeks of the year (1..=53, negatives count from end). Yearly rules only.
    pub weeks_of_year: Option<Vec<i32>>,
    /// Days of the year (1..=366, negatives count from end). Yearly rules only.
    pub days_of_year: Option<Vec<i32>>,
    /// Set positions — filter applied after the other fields. E.g. with
    /// `frequency = Monthly`, `days_of_week = [2]` (Monday), and
    /// `set_positions = [1]` you get "the first Monday of every month".
    /// Negative values count from the end.
    pub set_positions: Option<Vec<i32>>,
}

/// The main reminders manager providing access to EventKit functionality
pub struct RemindersManager {
    store: Retained<EKEventStore>,
}

impl RemindersManager {
    /// Creates a new RemindersManager instance
    pub fn new() -> Self {
        let store = unsafe { EKEventStore::new() };
        Self { store }
    }

    /// Gets the current authorization status for reminders
    pub fn authorization_status() -> AuthorizationStatus {
        let status =
            unsafe { EKEventStore::authorizationStatusForEntityType(EKEntityType::Reminder) };
        status.into()
    }

    /// Requests full access to reminders (blocking)
    ///
    /// Returns Ok(true) if access was granted, Ok(false) if denied
    pub fn request_access(&self) -> Result<bool> {
        let result = Arc::new((Mutex::new(None::<(bool, Option<String>)>), Condvar::new()));
        let result_clone = Arc::clone(&result);

        let completion = RcBlock::new(move |granted: Bool, error: *mut NSError| {
            let error_msg = if !error.is_null() {
                let error_ref = unsafe { &*error };
                Some(format!("{:?}", error_ref))
            } else {
                None
            };

            let (lock, cvar) = &*result_clone;
            let mut res = lock.lock().unwrap();
            *res = Some((granted.as_bool(), error_msg));
            cvar.notify_one();
        });

        unsafe {
            // Convert RcBlock to raw pointer for the API
            let block_ptr = &*completion as *const _ as *mut _;
            self.store
                .requestFullAccessToRemindersWithCompletion(block_ptr);
        }

        let (lock, cvar) = &*result;
        let mut res = lock.lock().unwrap();
        while res.is_none() {
            res = cvar.wait(res).unwrap();
        }

        match res.take() {
            Some((granted, None)) => Ok(granted),
            Some((_, Some(error))) => Err(RemindersError::AuthorizationRequestFailed(error)),
            None => Err(RemindersError::AuthorizationRequestFailed(
                "Unknown error".to_string(),
            )),
        }
    }

    /// Ensures we have authorization, requesting if needed
    pub fn ensure_authorized(&self) -> Result<()> {
        match Self::authorization_status() {
            AuthorizationStatus::FullAccess => Ok(()),
            AuthorizationStatus::NotDetermined => {
                if self.request_access()? {
                    Ok(())
                } else {
                    Err(RemindersError::AuthorizationDenied)
                }
            }
            AuthorizationStatus::Denied => Err(RemindersError::AuthorizationDenied),
            AuthorizationStatus::Restricted => Err(RemindersError::AuthorizationRestricted),
            AuthorizationStatus::WriteOnly => Ok(()), // Can still read with write-only in some cases
        }
    }

    /// Lists all reminder calendars (lists)
    pub fn list_calendars(&self) -> Result<Vec<CalendarInfo>> {
        self.ensure_authorized()?;

        let calendars = unsafe { self.store.calendarsForEntityType(EKEntityType::Reminder) };

        let mut result = Vec::new();
        for calendar in calendars.iter() {
            result.push(calendar_to_info(&calendar));
        }

        Ok(result)
    }

    /// Lists all available sources (iCloud, Local, Exchange, etc.)
    pub fn list_sources(&self) -> Result<Vec<SourceInfo>> {
        self.ensure_authorized()?;
        let sources = unsafe { self.store.sources() };
        let mut result = Vec::new();
        for source in sources.iter() {
            result.push(source_to_info(&source));
        }
        Ok(result)
    }

    /// Gets the default calendar for new reminders
    pub fn default_calendar(&self) -> Result<CalendarInfo> {
        self.ensure_authorized()?;

        let calendar = unsafe { self.store.defaultCalendarForNewReminders() };

        match calendar {
            Some(cal) => Ok(calendar_to_info(&cal)),
            None => Err(RemindersError::NoDefaultCalendar),
        }
    }

    /// Fetches all reminders (blocking)
    pub fn fetch_all_reminders(&self) -> Result<Vec<ReminderItem>> {
        self.fetch_reminders(None)
    }

    /// Fetches reminders from specific calendars (blocking)
    pub fn fetch_reminders(&self, calendar_titles: Option<&[&str]>) -> Result<Vec<ReminderItem>> {
        self.ensure_authorized()?;

        let calendars: Option<Retained<NSArray<EKCalendar>>> = match calendar_titles {
            Some(titles) => {
                let all_calendars =
                    unsafe { self.store.calendarsForEntityType(EKEntityType::Reminder) };
                let mut matching: Vec<Retained<EKCalendar>> = Vec::new();

                for cal in all_calendars.iter() {
                    let title = unsafe { cal.title() };
                    let title_str = title.to_string();
                    if titles.iter().any(|t| *t == title_str) {
                        matching.push(cal.retain());
                    }
                }

                if matching.is_empty() {
                    return Err(RemindersError::CalendarNotFound(titles.join(", ")));
                }

                Some(NSArray::from_retained_slice(&matching))
            }
            None => None,
        };

        let predicate = unsafe {
            self.store
                .predicateForRemindersInCalendars(calendars.as_deref())
        };

        let result = Arc::new((Mutex::new(None::<Vec<ReminderItem>>), Condvar::new()));
        let result_clone = Arc::clone(&result);

        let completion = RcBlock::new(move |reminders: *mut NSArray<EKReminder>| {
            let items = if reminders.is_null() {
                Vec::new()
            } else {
                let reminders = unsafe { Retained::retain(reminders).unwrap() };
                reminders.iter().map(|r| reminder_to_item(&r)).collect()
            };
            let (lock, cvar) = &*result_clone;
            let mut guard = lock.lock().unwrap();
            *guard = Some(items);
            cvar.notify_one();
        });

        unsafe {
            self.store
                .fetchRemindersMatchingPredicate_completion(&predicate, &completion);
        }

        let (lock, cvar) = &*result;
        let mut guard = lock.lock().unwrap();
        while guard.is_none() {
            guard = cvar.wait(guard).unwrap();
        }

        guard
            .take()
            .ok_or_else(|| RemindersError::FetchFailed("Unknown error".to_string()))
    }

    /// Fetches incomplete reminders (no due-date filter, all calendars).
    pub fn fetch_incomplete_reminders(&self) -> Result<Vec<ReminderItem>> {
        self.fetch_incomplete_reminders_in_due_range(None, None, None)
    }

    /// Fetches incomplete reminders whose due date falls within the optional
    /// `starting`..`ending` window. Either bound may be `None` to leave it
    /// open-ended. `calendar_titles` filters to specific lists (passing
    /// `None` searches all reminder calendars).
    pub fn fetch_incomplete_reminders_in_due_range(
        &self,
        starting: Option<DateTime<Local>>,
        ending: Option<DateTime<Local>>,
        calendar_titles: Option<&[&str]>,
    ) -> Result<Vec<ReminderItem>> {
        self.ensure_authorized()?;
        let calendars = self.resolve_reminder_calendars(calendar_titles)?;
        let start_ns = starting.map(datetime_to_nsdate);
        let end_ns = ending.map(datetime_to_nsdate);
        let predicate = unsafe {
            self.store
                .predicateForIncompleteRemindersWithDueDateStarting_ending_calendars(
                    start_ns.as_deref(),
                    end_ns.as_deref(),
                    calendars.as_deref(),
                )
        };
        self.fetch_by_predicate(&predicate)
    }

    /// Fetches completed reminders whose completion date falls within the
    /// optional `starting`..`ending` window. Either bound may be `None`.
    /// `calendar_titles` filters to specific lists.
    pub fn fetch_completed_reminders_in_range(
        &self,
        starting: Option<DateTime<Local>>,
        ending: Option<DateTime<Local>>,
        calendar_titles: Option<&[&str]>,
    ) -> Result<Vec<ReminderItem>> {
        self.ensure_authorized()?;
        let calendars = self.resolve_reminder_calendars(calendar_titles)?;
        let start_ns = starting.map(datetime_to_nsdate);
        let end_ns = ending.map(datetime_to_nsdate);
        let predicate = unsafe {
            self.store
                .predicateForCompletedRemindersWithCompletionDateStarting_ending_calendars(
                    start_ns.as_deref(),
                    end_ns.as_deref(),
                    calendars.as_deref(),
                )
        };
        self.fetch_by_predicate(&predicate)
    }

    /// Resolves `calendar_titles` (`Some(&["A", "B"])` etc.) to an NSArray
    /// of `EKCalendar` references restricted to reminder calendars. `None`
    /// → `Ok(None)` meaning "all calendars". Unknown title → error.
    fn resolve_reminder_calendars(
        &self,
        calendar_titles: Option<&[&str]>,
    ) -> Result<Option<Retained<NSArray<EKCalendar>>>> {
        let Some(titles) = calendar_titles else {
            return Ok(None);
        };
        let all_calendars = unsafe { self.store.calendarsForEntityType(EKEntityType::Reminder) };
        let mut matching: Vec<Retained<EKCalendar>> = Vec::new();
        for cal in all_calendars.iter() {
            let title_str = unsafe { cal.title() }.to_string();
            if titles.iter().any(|t| *t == title_str) {
                matching.push(cal.retain());
            }
        }
        if matching.is_empty() {
            return Err(RemindersError::CalendarNotFound(titles.join(", ")));
        }
        Ok(Some(NSArray::from_retained_slice(&matching)))
    }

    /// Runs the standard block-completion fetch dance against any predicate
    /// and converts the returned EKReminders to ReminderItems. Used by all
    /// `fetch_*` methods.
    fn fetch_by_predicate(
        &self,
        predicate: &objc2_foundation::NSPredicate,
    ) -> Result<Vec<ReminderItem>> {
        let result = Arc::new((Mutex::new(None::<Vec<ReminderItem>>), Condvar::new()));
        let result_clone = Arc::clone(&result);

        let completion = RcBlock::new(move |reminders: *mut NSArray<EKReminder>| {
            let items = if reminders.is_null() {
                Vec::new()
            } else {
                let reminders = unsafe { Retained::retain(reminders).unwrap() };
                reminders.iter().map(|r| reminder_to_item(&r)).collect()
            };
            let (lock, cvar) = &*result_clone;
            let mut guard = lock.lock().unwrap();
            *guard = Some(items);
            cvar.notify_one();
        });

        unsafe {
            self.store
                .fetchRemindersMatchingPredicate_completion(predicate, &completion);
        }

        let (lock, cvar) = &*result;
        let mut guard = lock.lock().unwrap();
        while guard.is_none() {
            guard = cvar.wait(guard).unwrap();
        }
        guard
            .take()
            .ok_or_else(|| RemindersError::FetchFailed("Unknown error".to_string()))
    }

    /// Creates a new reminder. Build the input with `ReminderDraft` —
    /// only `title` is required; spread `..Default::default()` for the rest.
    pub fn create_reminder(&self, draft: &ReminderDraft<'_>) -> Result<ReminderItem> {
        self.ensure_authorized()?;

        let reminder = unsafe { EKReminder::reminderWithEventStore(&self.store) };

        let ns_title = NSString::from_str(draft.title);
        unsafe { reminder.setTitle(Some(&ns_title)) };

        if let Some(notes_text) = draft.notes {
            let ns_notes = NSString::from_str(notes_text);
            unsafe { reminder.setNotes(Some(&ns_notes)) };
        }

        if let Some(p) = draft.priority {
            unsafe { reminder.setPriority(p) };
        }

        if let Some(due) = draft.due_date {
            let components = datetime_to_date_components(due);
            unsafe { reminder.setDueDateComponents(Some(&components)) };
        }

        if let Some(start) = draft.start_date {
            let components = datetime_to_date_components(start);
            unsafe { reminder.setStartDateComponents(Some(&components)) };
        }

        if draft.URL.is_some() {
            set_item_URL(&reminder, draft.URL)?;
        }
        if draft.location.is_some() {
            set_item_location(&reminder, draft.location);
        }
        if let Some(sl) = draft.structured_location {
            set_reminder_structured_location(&reminder, Some(sl));
        }
        if draft.due_date_timezone.is_some() {
            set_reminder_due_date_timezone(&reminder, draft.due_date_timezone);
        }

        let calendar = if let Some(cal_title) = draft.calendar_title {
            self.find_calendar_by_title(cal_title)?
        } else {
            unsafe { self.store.defaultCalendarForNewReminders() }
                .ok_or(RemindersError::NoDefaultCalendar)?
        };
        unsafe { reminder.setCalendar(Some(&calendar)) };

        self.save_reminder_and_refresh(&reminder)?;

        Ok(reminder_to_item(&reminder))
    }

    /// Updates an existing reminder. Build the changeset with `ReminderPatch`
    /// — only set the fields you want to touch. For nullable string/timezone
    /// fields, `Some(Some(v))` writes `v` and `Some(None)` clears.
    pub fn update_reminder(
        &self,
        identifier: &str,
        patch: &ReminderPatch<'_>,
    ) -> Result<ReminderItem> {
        self.ensure_authorized()?;

        let reminder = self.find_reminder_by_id(identifier)?;

        if let Some(t) = patch.title {
            let ns_title = NSString::from_str(t);
            unsafe { reminder.setTitle(Some(&ns_title)) };
        }

        if let Some(n) = patch.notes {
            let ns_notes = NSString::from_str(n);
            unsafe { reminder.setNotes(Some(&ns_notes)) };
        }

        if let Some(c) = patch.completed {
            unsafe { reminder.setCompleted(c) };
        }

        if let Some(p) = patch.priority {
            unsafe { reminder.setPriority(p) };
        }

        if let Some(due_opt) = patch.due_date {
            match due_opt {
                Some(due) => {
                    let components = datetime_to_date_components(due);
                    unsafe { reminder.setDueDateComponents(Some(&components)) };
                }
                None => unsafe { reminder.setDueDateComponents(None) },
            }
        }

        if let Some(start_opt) = patch.start_date {
            match start_opt {
                Some(start) => {
                    let components = datetime_to_date_components(start);
                    unsafe { reminder.setStartDateComponents(Some(&components)) };
                }
                None => unsafe { reminder.setStartDateComponents(None) },
            }
        }

        if let Some(url_opt) = patch.URL {
            set_item_URL(&reminder, url_opt)?;
        }
        if let Some(loc_opt) = patch.location {
            set_item_location(&reminder, loc_opt);
        }
        if let Some(sl_opt) = patch.structured_location {
            set_reminder_structured_location(&reminder, sl_opt);
        }
        if let Some(tz_opt) = patch.due_date_timezone {
            set_reminder_due_date_timezone(&reminder, tz_opt);
        }

        // Apply completion_date AFTER `completed` so Apple's "completionDate
        // is authoritative" semantics win when both are provided.
        if let Some(cd_opt) = patch.completion_date {
            match cd_opt {
                Some(d) => {
                    let nsdate = datetime_to_nsdate(d);
                    unsafe { reminder.setCompletionDate(Some(&nsdate)) };
                }
                None => unsafe { reminder.setCompletionDate(None) },
            }
        }

        if let Some(cal_title) = patch.calendar_title {
            let calendar = self.find_calendar_by_title(cal_title)?;
            unsafe { reminder.setCalendar(Some(&calendar)) };
        }

        self.save_reminder_and_refresh(&reminder)?;

        Ok(reminder_to_item(&reminder))
    }

    /// Marks a reminder as complete
    pub fn complete_reminder(&self, identifier: &str) -> Result<ReminderItem> {
        self.update_reminder(
            identifier,
            &ReminderPatch {
                completed: Some(true),
                ..Default::default()
            },
        )
    }

    /// Marks a reminder as incomplete
    pub fn uncomplete_reminder(&self, identifier: &str) -> Result<ReminderItem> {
        self.update_reminder(
            identifier,
            &ReminderPatch {
                completed: Some(false),
                ..Default::default()
            },
        )
    }

    /// Deletes a reminder
    pub fn delete_reminder(&self, identifier: &str) -> Result<()> {
        self.ensure_authorized()?;

        let reminder = self.find_reminder_by_id(identifier)?;

        unsafe {
            self.store
                .removeReminder_commit_error(&reminder, true)
                .map_err(|e| EventKitError::DeleteFailed(format!("{:?}", e)))?;
        }

        Ok(())
    }

    /// Gets a reminder by its identifier
    pub fn get_reminder(&self, identifier: &str) -> Result<ReminderItem> {
        self.ensure_authorized()?;
        let reminder = self.find_reminder_by_id(identifier)?;
        Ok(reminder_to_item(&reminder))
    }

    /// Dumps every Objective-C `@property` declared on the reminder, its
    /// EKCalendar, and that calendar's EKSource — using runtime reflection
    /// (`class_copyPropertyList`). Intended for figuring out which native
    /// fields are not yet surfaced by [`ReminderItem`].
    ///
    /// If `read_values` is true, also reads each property via KVC
    /// (`valueForKey:`). Some properties in EventKit are backed by Core Data
    /// internals and hit C-level assertions when read this way — see the
    /// hardcoded denylist in `reflect_object_full`. Use `false` for a fully
    /// safe schema-only listing.
    pub fn dump_reminder_raw(&self, identifier: &str, read_values: bool) -> Result<String> {
        self.ensure_authorized()?;
        let reminder = self.find_reminder_by_id(identifier)?;

        let mut out = String::new();
        out.push_str(&reflect_object_full(
            "EKReminder (instance)",
            &*reminder,
            read_values,
        ));

        if let Some(calendar) = unsafe { reminder.calendar() } {
            out.push('\n');
            out.push_str(&reflect_object_full(
                "EKCalendar (reminder.calendar)",
                &*calendar,
                read_values,
            ));

            if let Some(source) = unsafe { calendar.source() } {
                out.push('\n');
                out.push_str(&reflect_object_full(
                    "EKSource (calendar.source)",
                    &*source,
                    read_values,
                ));
            }
        }

        Ok(out)
    }

    /// Probes a hardcoded list of suspected-private selectors on the reminder
    /// — the kind of accessors that aren't generated by `objc2-event-kit`
    /// and reject KVC `valueForKey:` (e.g. `structuredData`, `tags`,
    /// `richLink`). Each call is wrapped in an Objective-C exception catch.
    /// Read-only — never invokes any setter.
    pub fn dump_reminder_private(&self, identifier: &str) -> Result<String> {
        self.ensure_authorized()?;
        let reminder = self.find_reminder_by_id(identifier)?;
        Ok(probe_private_selectors(&reminder))
    }

    // ========================================================================
    // Alarm Management
    // ========================================================================

    /// Lists all alarms on a reminder.
    pub fn get_alarms(&self, identifier: &str) -> Result<Vec<AlarmInfo>> {
        self.ensure_authorized()?;
        let reminder = self.find_reminder_by_id(identifier)?;
        Ok(get_item_alarms(&reminder))
    }

    /// Adds an alarm to a reminder.
    pub fn add_alarm(&self, identifier: &str, alarm: &AlarmInfo) -> Result<()> {
        self.ensure_authorized()?;
        let reminder = self.find_reminder_by_id(identifier)?;
        add_item_alarm(&reminder, alarm)?;
        self.save_reminder_and_refresh(&reminder)?;
        Ok(())
    }

    /// Removes all alarms from a reminder.
    pub fn remove_all_alarms(&self, identifier: &str) -> Result<()> {
        self.ensure_authorized()?;
        let reminder = self.find_reminder_by_id(identifier)?;
        clear_item_alarms(&reminder);
        self.save_reminder_and_refresh(&reminder)?;
        Ok(())
    }

    /// Removes a specific alarm from a reminder by index.
    pub fn remove_alarm(&self, identifier: &str, index: usize) -> Result<()> {
        self.ensure_authorized()?;
        let reminder = self.find_reminder_by_id(identifier)?;
        remove_item_alarm(&reminder, index)?;
        self.save_reminder_and_refresh(&reminder)?;
        Ok(())
    }

    // ========================================================================
    // URL Management
    // ========================================================================

    /// Set or clear the URL on a reminder.
    #[allow(non_snake_case)]
    pub fn set_URL(&self, identifier: &str, url: Option<&str>) -> Result<()> {
        self.ensure_authorized()?;
        let reminder = self.find_reminder_by_id(identifier)?;
        set_item_URL(&reminder, url)?;
        self.save_reminder_and_refresh(&reminder)?;
        Ok(())
    }

    /// Set or clear the free-text `location` on a reminder.
    pub fn set_location(&self, identifier: &str, location: Option<&str>) -> Result<()> {
        self.ensure_authorized()?;
        let reminder = self.find_reminder_by_id(identifier)?;
        set_item_location(&reminder, location);
        self.save_reminder_and_refresh(&reminder)?;
        Ok(())
    }

    /// Set or clear `EKReminder.dueDateTimeZone`. `tz_name` must be an
    /// IANA zone identifier (e.g. `"America/Los_Angeles"`).
    pub fn set_due_date_timezone(&self, identifier: &str, tz_name: Option<&str>) -> Result<()> {
        self.ensure_authorized()?;
        let reminder = self.find_reminder_by_id(identifier)?;
        set_reminder_due_date_timezone(&reminder, tz_name);
        self.save_reminder_and_refresh(&reminder)?;
        Ok(())
    }

    /// Set (or clear) the reminder's rich location — `EKReminder.structuredLocation`
    /// (not in `objc2-event-kit` 0.3 generated bindings — accessed via
    /// `msg_send!`).
    ///
    /// **iCloud caveat:** verified empirically — iCloud silently drops this
    /// mutation on reminder objects even though the save returns success.
    /// Use [`set_geofence`](Self::set_geofence) instead for iCloud-synced
    /// reminders; it writes the structured location on a proximity alarm,
    /// which iCloud does persist. This method remains correct for local /
    /// non-iCloud reminder sources.
    pub fn set_structured_location(
        &self,
        identifier: &str,
        loc: Option<&StructuredLocation>,
    ) -> Result<()> {
        self.ensure_authorized()?;
        let reminder = self.find_reminder_by_id(identifier)?;
        set_reminder_structured_location(&reminder, loc);
        self.save_reminder_and_refresh(&reminder)?;
        Ok(())
    }

    /// Attach (or clear) a geofence on the reminder. Implemented as a
    /// location-based `EKAlarm` since EventKit has no `structuredLocation`
    /// directly on `EKReminder` / `EKCalendarItem`. When `geofence` is
    /// `Some`, also requests WhenInUse location authorization so the alarm
    /// actually has permission to fire — if the user denies, the save is
    /// aborted with an authorization error.
    pub fn set_geofence(
        &self,
        identifier: &str,
        geofence: Option<(&StructuredLocation, AlarmProximity)>,
    ) -> Result<()> {
        self.ensure_authorized()?;

        // Prompt for location auth before saving a geofence. Without this we
        // would silently create a reminder whose proximity trigger can't fire.
        #[cfg(feature = "location")]
        if geofence.is_some() {
            use crate::location::{LocationAuthorizationStatus as L, LocationManager};
            let loc_mgr = LocationManager::new();
            if loc_mgr.authorization_status() == L::NotDetermined {
                loc_mgr.request_when_in_use_authorization();
                // CLLocationManager delivers the result asynchronously on the
                // run loop. Match the polling pattern get_current_location uses.
                std::thread::sleep(std::time::Duration::from_millis(500));
            }
            match loc_mgr.authorization_status() {
                L::Authorized => {}
                L::Denied => return Err(EventKitError::AuthorizationDenied),
                L::Restricted => return Err(EventKitError::AuthorizationRestricted),
                L::NotDetermined => return Err(EventKitError::AuthorizationNotDetermined),
            }
        }

        let reminder = self.find_reminder_by_id(identifier)?;
        set_reminder_geofence(&reminder, geofence);
        self.save_reminder_and_refresh(&reminder)?;
        Ok(())
    }

    // ========================================================================
    // Recurrence Rule Management
    // ========================================================================

    /// Gets recurrence rules on a reminder.
    pub fn get_recurrence_rules(&self, identifier: &str) -> Result<Vec<RecurrenceRule>> {
        self.ensure_authorized()?;
        let reminder = self.find_reminder_by_id(identifier)?;
        Ok(get_item_recurrence_rules(&reminder))
    }

    /// Sets a recurrence rule on a reminder (replaces any existing rules).
    pub fn set_recurrence_rule(&self, identifier: &str, rule: &RecurrenceRule) -> Result<()> {
        self.ensure_authorized()?;
        let reminder = self.find_reminder_by_id(identifier)?;
        set_item_recurrence_rule(&reminder, rule);
        self.save_reminder_and_refresh(&reminder)?;
        Ok(())
    }

    /// Removes all recurrence rules from a reminder.
    pub fn remove_recurrence_rules(&self, identifier: &str) -> Result<()> {
        self.ensure_authorized()?;
        let reminder = self.find_reminder_by_id(identifier)?;
        clear_item_recurrence_rules(&reminder);
        self.save_reminder_and_refresh(&reminder)?;
        Ok(())
    }

    // ========================================================================
    // Calendar (Reminder List) Management
    // ========================================================================

    /// Creates a new reminder list (calendar)
    ///
    /// The list will be created in the default source (usually iCloud or Local).
    pub fn create_calendar(&self, title: &str) -> Result<CalendarInfo> {
        self.ensure_authorized()?;

        // Create a new calendar for reminders
        let calendar = unsafe {
            EKCalendar::calendarForEntityType_eventStore(EKEntityType::Reminder, &self.store)
        };

        // Set the title
        let ns_title = NSString::from_str(title);
        unsafe { calendar.setTitle(&ns_title) };

        // Find a suitable source (prefer iCloud, fall back to local)
        let source = self.find_best_source_for_reminders()?;
        unsafe { calendar.setSource(Some(&source)) };

        // Save the calendar
        unsafe {
            self.store
                .saveCalendar_commit_error(&calendar, true)
                .map_err(|e| EventKitError::SaveFailed(format!("{:?}", e)))?;
        }

        Ok(calendar_to_info(&calendar))
    }

    /// Renames an existing reminder list (calendar)
    /// Rename a reminder list (backward compat wrapper).
    pub fn rename_calendar(&self, identifier: &str, new_title: &str) -> Result<CalendarInfo> {
        self.update_calendar(identifier, Some(new_title), None)
    }

    /// Update a reminder list — name, color, or both.
    pub fn update_calendar(
        &self,
        identifier: &str,
        new_title: Option<&str>,
        color_rgba: Option<(f64, f64, f64, f64)>,
    ) -> Result<CalendarInfo> {
        self.ensure_authorized()?;
        let calendar = self.find_calendar_by_id(identifier)?;

        if !unsafe { calendar.allowsContentModifications() } {
            return Err(EventKitError::SaveFailed(
                "Calendar does not allow modifications".to_string(),
            ));
        }

        if let Some(title) = new_title {
            let ns_title = NSString::from_str(title);
            unsafe { calendar.setTitle(&ns_title) };
        }

        if let Some((r, g, b, a)) = color_rgba {
            let cg = objc2_core_graphics::CGColor::new_srgb(r, g, b, a);
            unsafe { calendar.setCGColor(Some(&cg)) };
        }

        unsafe {
            self.store
                .saveCalendar_commit_error(&calendar, true)
                .map_err(|e| EventKitError::SaveFailed(format!("{:?}", e)))?;
        }

        Ok(calendar_to_info(&calendar))
    }

    /// Deletes a reminder list (calendar)
    ///
    /// Warning: This will delete all reminders in the list!
    pub fn delete_calendar(&self, identifier: &str) -> Result<()> {
        self.ensure_authorized()?;

        let calendar = self.find_calendar_by_id(identifier)?;

        // Check if modifications are allowed
        if !unsafe { calendar.allowsContentModifications() } {
            return Err(EventKitError::DeleteFailed(
                "Calendar does not allow modifications".to_string(),
            ));
        }

        unsafe {
            self.store
                .removeCalendar_commit_error(&calendar, true)
                .map_err(|e| EventKitError::DeleteFailed(format!("{:?}", e)))?;
        }

        Ok(())
    }

    /// Gets a calendar by its identifier
    pub fn get_calendar(&self, identifier: &str) -> Result<CalendarInfo> {
        self.ensure_authorized()?;
        let calendar = self.find_calendar_by_id(identifier)?;
        Ok(calendar_to_info(&calendar))
    }

    // Helper to find the best source for creating new reminder calendars
    fn find_best_source_for_reminders(&self) -> Result<Retained<objc2_event_kit::EKSource>> {
        // Try to get the source from the default calendar first
        if let Some(default_cal) = unsafe { self.store.defaultCalendarForNewReminders() }
            && let Some(source) = unsafe { default_cal.source() }
        {
            return Ok(source);
        }

        // Fall back to finding any source that supports reminders
        let sources = unsafe { self.store.sources() };
        for source in sources.iter() {
            // Check if this source supports reminder calendars
            let calendars = unsafe { source.calendarsForEntityType(EKEntityType::Reminder) };
            if !calendars.is_empty() {
                return Ok(source.retain());
            }
        }

        Err(EventKitError::SaveFailed(
            "No suitable source found for creating reminder calendar".to_string(),
        ))
    }

    // Helper to find a calendar by identifier
    fn find_calendar_by_id(&self, identifier: &str) -> Result<Retained<EKCalendar>> {
        let ns_id = NSString::from_str(identifier);
        let calendar = unsafe { self.store.calendarWithIdentifier(&ns_id) };

        match calendar {
            Some(cal) => Ok(cal),
            None => Err(EventKitError::CalendarNotFound(identifier.to_string())),
        }
    }

    // Helper to find a calendar by title
    fn find_calendar_by_title(&self, title: &str) -> Result<Retained<EKCalendar>> {
        let calendars = unsafe { self.store.calendarsForEntityType(EKEntityType::Reminder) };

        for cal in calendars.iter() {
            let cal_title = unsafe { cal.title() };
            if cal_title.to_string() == title {
                return Ok(cal.retain());
            }
        }

        Err(RemindersError::CalendarNotFound(title.to_string()))
    }

    // Helper to find a reminder by identifier
    /// Commit a reminder to the store and refresh sources, so a subsequent
    /// `find_reminder_by_id` or fetch sees the just-saved state without
    /// waiting for the daemon to notice. All `pub fn` save paths on
    /// `RemindersManager` route through this helper.
    fn save_reminder_and_refresh(&self, reminder: &EKReminder) -> Result<()> {
        unsafe {
            self.store
                .saveReminder_commit_error(reminder, true)
                .map_err(|e| EventKitError::SaveFailed(format!("{:?}", e)))?;
            self.store.refreshSourcesIfNecessary();
        }
        Ok(())
    }

    fn find_reminder_by_id(&self, identifier: &str) -> Result<Retained<EKReminder>> {
        // Pick up any changes the user made in Reminders.app since the
        // store was created — without this, iCloud edits made on the same
        // machine may not be visible until next process launch.
        unsafe { self.store.refreshSourcesIfNecessary() };

        let ns_id = NSString::from_str(identifier);
        let item = unsafe { self.store.calendarItemWithIdentifier(&ns_id) };

        match item {
            Some(item) => {
                // Try to downcast to EKReminder
                if let Some(reminder) = item.downcast_ref::<EKReminder>() {
                    Ok(reminder.retain())
                } else {
                    Err(EventKitError::ItemNotFound(identifier.to_string()))
                }
            }
            None => Err(EventKitError::ItemNotFound(identifier.to_string())),
        }
    }
}

impl Default for RemindersManager {
    fn default() -> Self {
        Self::new()
    }
}

/// Authorization status for reminders access
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AuthorizationStatus {
    /// User has not yet made a choice
    NotDetermined,
    /// Access restricted by system policy
    Restricted,
    /// User explicitly denied access
    Denied,
    /// Full access granted
    FullAccess,
    /// Write-only access granted
    WriteOnly,
}

impl From<EKAuthorizationStatus> for AuthorizationStatus {
    fn from(status: EKAuthorizationStatus) -> Self {
        if status == EKAuthorizationStatus::NotDetermined {
            AuthorizationStatus::NotDetermined
        } else if status == EKAuthorizationStatus::Restricted {
            AuthorizationStatus::Restricted
        } else if status == EKAuthorizationStatus::Denied {
            AuthorizationStatus::Denied
        } else if status == EKAuthorizationStatus::FullAccess {
            AuthorizationStatus::FullAccess
        } else if status == EKAuthorizationStatus::WriteOnly {
            AuthorizationStatus::WriteOnly
        } else {
            AuthorizationStatus::NotDetermined
        }
    }
}

impl std::fmt::Display for AuthorizationStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AuthorizationStatus::NotDetermined => write!(f, "Not Determined"),
            AuthorizationStatus::Restricted => write!(f, "Restricted"),
            AuthorizationStatus::Denied => write!(f, "Denied"),
            AuthorizationStatus::FullAccess => write!(f, "Full Access"),
            AuthorizationStatus::WriteOnly => write!(f, "Write Only"),
        }
    }
}

// Helper function to convert EKReminder to ReminderItem
/// Walks the class chain of `obj` and lists every declared `@property`,
/// reading each one via KVC (`-[NSObject valueForKey:]`). The returned string
/// is multi-section human-readable text — one section per class in the chain.
///
/// Only intended for diagnostics: KVC dispatch is slower than direct method
/// calls and may throw NSException for very unusual property declarations.
// Properties whose KVC read path hits a C-level assertion (CADObjectID etc.)
// and aborts the process. Skip these unconditionally when `read_values` is on.
// Discovered empirically — add to this list when a new abort is found.
const REFLECT_VALUE_DENYLIST: &[&str] =
    &["objectID", "objectIDURIRepresentation", "URIRepresentation"];

fn reflect_object_full<T: Message>(header: &str, obj: &T, read_values: bool) -> String {
    use objc2::ffi::{class_copyPropertyList, free, property_getAttributes, property_getName};
    use objc2::msg_send;
    use objc2::rc::Retained;
    use objc2::runtime::{AnyClass, AnyObject};
    use std::ffi::CStr;

    // Cast to AnyObject for runtime introspection. `T: Message` guarantees
    // this is an Objective-C object with a valid isa pointer.
    let obj: &AnyObject = unsafe { &*(obj as *const T as *const AnyObject) };

    let mut out = String::new();
    out.push_str(&format!("=== {header} ===\n"));

    // Build the class chain (most-derived first).
    let mut chain: Vec<&'static AnyClass> = Vec::new();
    let mut current = Some(obj.class());
    while let Some(cls) = current {
        chain.push(cls);
        current = cls.superclass();
    }
    out.push_str("Class chain: ");
    out.push_str(
        &chain
            .iter()
            .map(|c| c.name().to_string_lossy().into_owned())
            .collect::<Vec<_>>()
            .join(" -> "),
    );
    out.push_str("\n\n");

    for cls in &chain {
        let cls_name = cls.name().to_string_lossy().into_owned();
        // Stop at NSObject — its properties are noise (hash, description, ...).
        if cls_name == "NSObject" {
            continue;
        }

        let mut count: u32 = 0;
        let props_ptr =
            unsafe { class_copyPropertyList(*cls as *const AnyClass, &mut count as *mut u32) };
        if props_ptr.is_null() || count == 0 {
            if !props_ptr.is_null() {
                unsafe { free(props_ptr as *mut _) };
            }
            continue;
        }

        let mut entries: Vec<(String, String, String)> = Vec::new();
        for i in 0..count as isize {
            let prop = unsafe { *props_ptr.offset(i) };
            if prop.is_null() {
                continue;
            }
            let name_ptr = unsafe { property_getName(prop) };
            let attrs_ptr = unsafe { property_getAttributes(prop) };
            let name = if name_ptr.is_null() {
                String::from("<?>")
            } else {
                unsafe { CStr::from_ptr(name_ptr) }
                    .to_string_lossy()
                    .into_owned()
            };
            let attrs = if attrs_ptr.is_null() {
                String::new()
            } else {
                unsafe { CStr::from_ptr(attrs_ptr) }
                    .to_string_lossy()
                    .into_owned()
            };

            // Anything typed `EKObjectID` / `NSManagedObjectID` / `CADObjectID`
            // hits a CoreData `__assert_rtn` on KVC read and will SIGABRT.
            // Filter by type encoding rather than name — safer as new
            // properties are added in future SDKs.
            let type_is_objectid = attrs.contains("ObjectID");

            let value_str = if !read_values {
                String::from("<value read skipped (pass --values to attempt)>")
            } else if REFLECT_VALUE_DENYLIST.contains(&name.as_str()) || type_is_objectid {
                String::from("<skipped: type/name denylisted (would abort process)>")
            } else {
                // Read via KVC, catching any NSException. Note: this catches
                // ObjC exceptions but NOT C-level assertions (`__assert_rtn`),
                // which abort the process directly — hence the denylist above.
                let name_for_closure = name.clone();
                let obj_ptr = obj as *const AnyObject;
                match objc2::exception::catch(std::panic::AssertUnwindSafe(move || {
                    let key = NSString::from_str(&name_for_closure);
                    let obj_ref: &AnyObject = unsafe { &*obj_ptr };
                    let value_obj: Option<Retained<AnyObject>> =
                        unsafe { msg_send![obj_ref, valueForKey: &*key] };
                    match value_obj {
                        None => String::from("(null)"),
                        Some(v) => describe_object(&v),
                    }
                })) {
                    Ok(s) => s,
                    Err(Some(exc)) => {
                        format!("<NSException: {}>", describe_object(&**exc as &AnyObject))
                    }
                    Err(None) => String::from("<unknown ObjC exception>"),
                }
            };

            entries.push((name, attrs, value_str));
        }
        unsafe { free(props_ptr as *mut _) };

        if entries.is_empty() {
            continue;
        }
        entries.sort_by(|a, b| a.0.cmp(&b.0));

        out.push_str(&format!("[{cls_name}]\n"));
        for (name, attrs, value) in entries {
            out.push_str(&format!("  {name}\n"));
            out.push_str(&format!("    attrs: {attrs}\n"));
            // Indent multi-line values so they don't break the layout.
            let indented = value.replace('\n', "\n      ");
            out.push_str(&format!("    value: {indented}\n"));
        }
        out.push('\n');
    }

    out
}

/// Probes a curated list of selectors that are not generated by
/// `objc2-event-kit` and that KVC rejects on `EKReminder`. Each call is
/// wrapped in `objc2::exception::catch` so a missing selector ("unrecognized
/// selector sent to instance") becomes a printable line instead of an abort.
///
/// This is a fishing expedition — the selector names are educated guesses
/// based on Apple's public naming patterns and what Reminders.app surfaces.
/// Add entries as new candidates come up; the cost of an extra probe is one
/// caught NSException.
fn probe_private_selectors(reminder: &EKReminder) -> String {
    use objc2::msg_send;
    use objc2::rc::Retained;
    use objc2::runtime::{AnyObject, Sel};
    use std::ffi::CString;

    const PROBES: &[&str] = &[
        // Rich-link / preview URL candidates
        "appLink",      // <- confirmed exists on EKCalendarItem (method dump)
        "URLString",    // <- confirmed exists on EKCalendarItem
        "externalData", // <- confirmed exists on EKCalendarItem
        "externalModificationTag",
        "richLink",
        "richLinkData",
        "URLWithPreview",
        "urlPreview",
        "linkPreview",
        "siriSuggestedURL",
        "displayURL",
        "flaggedURL",
        "_richLink",
        "_url",
        "primaryLink",
        // Structured-location candidates on the reminder itself
        "structuredLocation",
        "geoLocation",
        "place",
        "placemark",
        // Tag candidates
        "tags",
        "tagDictionaries",
        "tagNames",
        "userTags",
        "_tags",
        "_tagDictionaries",
        "hashtags",
        // Backing structured-data blobs (KVC-blocked, try typed accessor)
        "structuredData",
        "localStructuredData",
        "_structuredData",
        // "Melted" (mutable) vs frozen reminder layer
        "meltedObject",
        "unfrozen",
        "unfrozenObject",
        "writableInstance",
        // Misc EventKit private surfaces
        "flags",
        "flags2",
        "isFlagged",
        "image",
        "imageData",
        "thumbnail",
        "color",
        "creatorBundleID",
        // Subtask / parent
        "parentReminder",
        "subreminders",
        "subtasks",
        "childReminders",
    ];

    let obj: &AnyObject = unsafe { &*(reminder as *const EKReminder as *const AnyObject) };
    let mut out = String::from("=== Private-selector probe on EKReminder ===\n");
    out.push_str("(each call wrapped in @try/@catch — caught exceptions mean the selector doesn't exist on this class)\n\n");

    for name in PROBES {
        let c_name = CString::new(*name).expect("selector name has no NUL");
        let sel = Sel::register(&c_name);
        let name_owned = name.to_string();
        let obj_ptr = obj as *const AnyObject;
        let line = match objc2::exception::catch(std::panic::AssertUnwindSafe(move || {
            // Confirm the object responds before we send, so we get a clean
            // "doesn't respond" instead of an NSException for the common case.
            let obj_ref: &AnyObject = unsafe { &*obj_ptr };
            let responds: bool = unsafe { msg_send![obj_ref, respondsToSelector: sel] };
            if !responds {
                return format!("{name_owned}: <does not respond>");
            }
            let result: Option<Retained<AnyObject>> =
                unsafe { msg_send![obj_ref, performSelector: sel] };
            match result {
                None => format!("{name_owned}: (null)"),
                Some(v) => {
                    let cls: &objc2::runtime::AnyClass = (*v).class();
                    let cls_name = cls.name().to_string_lossy().into_owned();
                    let desc = describe_object(&v);
                    let one_line = desc.replace('\n', "\\n");
                    format!("{name_owned}: [{cls_name}] {one_line}")
                }
            }
        })) {
            Ok(s) => s,
            Err(Some(exc)) => format!(
                "{name}: <NSException: {}>",
                describe_object(&**exc as &AnyObject)
            ),
            Err(None) => format!("{name}: <unknown ObjC exception>"),
        };
        out.push_str(&line);
        out.push('\n');
    }

    // Drill into the underlying persistent object — `backingObject` is the
    // EKPersistentObject the frozen wrapper proxies. If a method is
    // KVC-blocked on the frozen wrapper it may work on the backing object.
    let backing: Option<Retained<AnyObject>> = unsafe { msg_send![obj, backingObject] };
    if let Some(backing) = backing {
        let bcls = (*backing).class().name().to_string_lossy().into_owned();
        out.push_str(&format!("\n--- backingObject ({bcls}) probe ---\n"));
        for name in PROBES {
            let c_name = std::ffi::CString::new(*name).expect("no NUL");
            let sel = objc2::runtime::Sel::register(&c_name);
            let name_owned = name.to_string();
            let backing_ptr = &*backing as *const AnyObject;
            let line = match objc2::exception::catch(std::panic::AssertUnwindSafe(move || {
                let bref: &AnyObject = unsafe { &*backing_ptr };
                let responds: bool = unsafe { msg_send![bref, respondsToSelector: sel] };
                if !responds {
                    return format!("{name_owned}: <does not respond>");
                }
                let result: Option<Retained<AnyObject>> =
                    unsafe { msg_send![bref, performSelector: sel] };
                match result {
                    None => format!("{name_owned}: (null)"),
                    Some(v) => {
                        let cls = (*v).class().name().to_string_lossy().into_owned();
                        format!(
                            "{name_owned}: [{cls}] {}",
                            describe_object(&v).replace('\n', "\\n")
                        )
                    }
                }
            })) {
                Ok(s) => s,
                Err(Some(exc)) => format!(
                    "{name}: <NSException: {}>",
                    describe_object(&**exc as &AnyObject)
                ),
                Err(None) => format!("{name}: <unknown ObjC exception>"),
            };
            out.push_str(&line);
            out.push('\n');
        }
    }

    // Bonus: enumerate every instance method via the runtime, filtered to
    // names that look URL/tag/link/data-related. This catches selectors we
    // didn't guess in PROBES.
    out.push_str(
        "\n--- All zero-arg instance methods on EKReminder containing url/tag/link/data ---\n",
    );
    out.push_str(&list_interesting_methods(obj.class()));
    out
}

/// Lists every instance method on `cls` (walking up the class chain to EKObject)
/// whose selector name contains `url`, `tag`, `link`, `data`, `flag`, `image`,
/// `preview`, or `attachment`. Doesn't call them — just shows what exists.
fn list_interesting_methods(start: &objc2::runtime::AnyClass) -> String {
    use objc2::ffi::{class_copyMethodList, free, method_getName};
    use objc2::runtime::AnyClass;
    use std::ffi::CStr;

    let needles = [
        "url",
        "tag",
        "link",
        "data",
        "flag",
        "image",
        "preview",
        "attachment",
        "rich",
        "location",
        "structured",
        "place",
        "address",
        "geo",
    ];
    let mut hits: Vec<(String, String)> = Vec::new();

    let mut current: Option<&AnyClass> = Some(start);
    while let Some(cls) = current {
        let cls_name = cls.name().to_string_lossy().into_owned();
        if cls_name == "NSObject" {
            break;
        }
        let mut count: u32 = 0;
        let ptr = unsafe { class_copyMethodList(cls as *const AnyClass, &mut count as *mut u32) };
        if !ptr.is_null() {
            for i in 0..count as isize {
                let m = unsafe { *ptr.offset(i) };
                if m.is_null() {
                    continue;
                }
                let Some(sel) = (unsafe { method_getName(m) }) else {
                    continue;
                };
                let name_cstr_ptr = unsafe { objc2::ffi::sel_getName(sel) };
                if name_cstr_ptr.is_null() {
                    continue;
                }
                let name = unsafe { CStr::from_ptr(name_cstr_ptr) }
                    .to_string_lossy()
                    .into_owned();
                let lower = name.to_lowercase();
                if needles.iter().any(|n| lower.contains(n)) {
                    hits.push((cls_name.clone(), name));
                }
            }
            unsafe { free(ptr as *mut _) };
        }
        current = cls.superclass();
    }
    hits.sort();
    hits.dedup();
    if hits.is_empty() {
        return String::from("(none)\n");
    }
    let mut out = String::new();
    for (cls, sel) in hits {
        out.push_str(&format!("  [{cls}] {sel}\n"));
    }
    out
}

/// `-[NSObject description]` as a Rust string. Returns `<nil>` for null,
/// `<no description>` if the object doesn't respond to description.
fn describe_object(obj: &objc2::runtime::AnyObject) -> String {
    use objc2::msg_send;
    use objc2::rc::Retained;
    use objc2::runtime::AnyObject;

    let desc: Option<Retained<AnyObject>> = unsafe { msg_send![obj, description] };
    match desc {
        None => String::from("<no description>"),
        Some(d) => {
            // description always returns NSString — cast pointer-wise.
            let any: &AnyObject = &d;
            let ns: &NSString = unsafe { &*(any as *const AnyObject as *const NSString) };
            ns.to_string()
        }
    }
}

fn reminder_to_item(reminder: &EKReminder) -> ReminderItem {
    let identifier = unsafe { reminder.calendarItemIdentifier() }.to_string();
    let title = unsafe { reminder.title() }.to_string();
    let notes = unsafe { reminder.notes() }.map(|n| n.to_string());
    let completed = unsafe { reminder.isCompleted() };
    let priority = unsafe { reminder.priority() };
    let cal = unsafe { reminder.calendar() };
    let calendar_title = cal.as_ref().map(|c| unsafe { c.title() }.to_string());
    let calendar_id = cal
        .as_ref()
        .map(|c| unsafe { c.calendarIdentifier() }.to_string());

    // Extract due date from dueDateComponents
    let due_date = unsafe { reminder.dueDateComponents() }
        .and_then(|components| date_components_to_datetime(&components));

    // Extract start date from startDateComponents
    let start_date = unsafe { reminder.startDateComponents() }
        .and_then(|components| date_components_to_datetime(&components));

    // Extract completion date
    let completion_date =
        unsafe { reminder.completionDate() }.map(|date| nsdate_to_datetime(&date));

    // Extract additional fields from EKCalendarItem parent class
    let external_identifier =
        unsafe { reminder.calendarItemExternalIdentifier() }.map(|id| id.to_string());
    let location = unsafe { reminder.location() }.map(|loc| loc.to_string());
    #[allow(non_snake_case)]
    let URL = unsafe { reminder.URL() }
        .as_ref()
        .and_then(|url_ref| url_ref.absoluteString())
        .map(|abs_str| abs_str.to_string());
    let creation_date = unsafe { reminder.creationDate() }.map(|date| nsdate_to_datetime(&date));
    let last_modified_date =
        unsafe { reminder.lastModifiedDate() }.map(|date| nsdate_to_datetime(&date));
    let timezone = unsafe { reminder.timeZone() }.map(|tz| tz.name().to_string());
    let due_date_timezone = get_reminder_due_date_timezone(reminder);
    let structured_location = get_reminder_structured_location(reminder);
    let parent_id = get_reminder_parent_id(reminder);
    let attachments_count = get_item_attachments_count(reminder);
    let has_alarms = unsafe { reminder.hasAlarms() };
    let has_recurrence_rules = unsafe { reminder.hasRecurrenceRules() };
    let has_attendees = unsafe { reminder.hasAttendees() };
    let has_notes = unsafe { reminder.hasNotes() };

    ReminderItem {
        identifier,
        title,
        notes,
        completed,
        priority,
        calendar_title,
        calendar_id,
        due_date,
        start_date,
        completion_date,
        external_identifier,
        location,
        URL,
        creation_date,
        last_modified_date,
        timezone,
        due_date_timezone,
        structured_location,
        parent_id,
        attachments_count,
        has_alarms,
        has_recurrence_rules,
        has_attendees,
        has_notes,
        attendees: get_item_attendees(reminder),
    }
}

/// Read `EKReminder.dueDateTimeZone` via msg_send — not exposed in
/// `objc2-event-kit` 0.3 generated bindings.
fn get_reminder_due_date_timezone(reminder: &EKReminder) -> Option<String> {
    use objc2::msg_send;
    use objc2::rc::Retained;
    let tz: Option<Retained<objc2_foundation::NSTimeZone>> =
        unsafe { msg_send![reminder, dueDateTimeZone] };
    tz.map(|tz| tz.name().to_string())
}

/// Reads `EKReminder.structuredLocation` — the iCloud-native location chip
/// that Reminders.app displays. Apple shipped this on `EKCalendarItem` but
/// `objc2-event-kit` 0.3 doesn't generate bindings for it on reminders
/// (only on `EKEvent`/`EKAlarm`), so we go through `msg_send!`.
///
/// Falls back to the alarm-based geofence path for older reminders whose
/// location is only attached via a proximity alarm.
fn get_reminder_structured_location(reminder: &EKReminder) -> Option<StructuredLocation> {
    if let Some(sl) = direct_structured_location(reminder) {
        return Some(sl);
    }
    // Legacy fallback: scan alarms for proximity-bearing structured location.
    let alarms = unsafe { reminder.alarms() }?;
    for i in 0..alarms.len() {
        let alarm = alarms.objectAtIndex(i);
        let prox = unsafe { alarm.proximity() };
        if prox == EKAlarmProximity::None {
            continue;
        }
        let Some(structured) = (unsafe { alarm.structuredLocation() }) else {
            continue;
        };
        return Some(structured_to_plain(&structured));
    }
    None
}

fn direct_structured_location(reminder: &EKReminder) -> Option<StructuredLocation> {
    use objc2::msg_send;
    use objc2::rc::Retained;
    let sl: Option<Retained<EKStructuredLocation>> =
        unsafe { msg_send![reminder, structuredLocation] };
    sl.map(|s| structured_to_plain(&s))
}

fn structured_to_plain(structured: &EKStructuredLocation) -> StructuredLocation {
    let title = unsafe { structured.title() }
        .map(|t| t.to_string())
        .unwrap_or_default();
    let radius = unsafe { structured.radius() };
    let (latitude, longitude) = read_geo_location_coords(structured);
    StructuredLocation {
        title,
        latitude,
        longitude,
        radius,
    }
}

/// Pull lat/lng off an `EKStructuredLocation`'s `geoLocation` (CLLocation).
/// Returns (0.0, 0.0) when the `location` feature is disabled — coordinates
/// require CoreLocation bindings.
#[cfg(feature = "location")]
fn read_geo_location_coords(structured: &EKStructuredLocation) -> (f64, f64) {
    let cl = unsafe { structured.geoLocation() };
    let Some(cl) = cl else { return (0.0, 0.0) };
    let coord = unsafe { cl.coordinate() };
    (coord.latitude, coord.longitude)
}

#[cfg(not(feature = "location"))]
fn read_geo_location_coords(_structured: &EKStructuredLocation) -> (f64, f64) {
    (0.0, 0.0)
}

/// Read `EKReminder.parentID` via KVC. The underlying type is the private
/// `EKObjectID`; we stringify via `-[description]`. Returns `None` if the
/// reminder has no parent or if the KVC read throws.
fn get_reminder_parent_id(reminder: &EKReminder) -> Option<String> {
    use objc2::msg_send;
    use objc2::rc::Retained;
    use objc2::runtime::AnyObject;
    let reminder_obj: &AnyObject = unsafe { &*(reminder as *const EKReminder as *const AnyObject) };
    let reminder_ptr = reminder_obj as *const AnyObject;
    let value = objc2::exception::catch(std::panic::AssertUnwindSafe(move || {
        let key = NSString::from_str("parentID");
        let obj_ref: &AnyObject = unsafe { &*reminder_ptr };
        let v: Option<Retained<AnyObject>> = unsafe { msg_send![obj_ref, valueForKey: &*key] };
        v
    }))
    .ok()
    .flatten()?;
    let desc: Retained<AnyObject> = unsafe { msg_send![&*value, description] };
    let ns: &NSString = unsafe { &*(&*desc as *const AnyObject as *const NSString) };
    Some(ns.to_string())
}

/// Number of file attachments on the item. EventKit doesn't expose the
/// attachment objects via the public Rust bindings; we just count them.
fn get_item_attachments_count(item: &EKCalendarItem) -> usize {
    use objc2::msg_send;
    use objc2::rc::Retained;
    use objc2_foundation::NSArray;
    let attachments: Option<Retained<NSArray>> = unsafe { msg_send![item, attachments] };
    attachments.map(|a| a.len()).unwrap_or(0)
}

// Helper function to convert EKCalendar to CalendarInfo
fn source_to_info(source: &EKSource) -> SourceInfo {
    let identifier = unsafe { source.sourceIdentifier() }.to_string();
    let title = unsafe { source.title() }.to_string();
    // EKSourceType: 0=Local, 1=Exchange, 2=CalDAV, 3=MobileMe, 4=Subscribed, 5=Birthdays
    let source_type = unsafe { source.sourceType() };
    let source_type = match source_type.0 {
        0 => "local",
        1 => "exchange",
        2 => "caldav",
        3 => "mobileme",
        4 => "subscribed",
        5 => "birthdays",
        _ => "unknown",
    }
    .to_string();

    SourceInfo {
        identifier,
        title,
        source_type,
    }
}

fn calendar_to_info(calendar: &EKCalendar) -> CalendarInfo {
    let identifier = unsafe { calendar.calendarIdentifier() }.to_string();
    let title = unsafe { calendar.title() }.to_string();
    let source = unsafe { calendar.source() }.map(|s| unsafe { s.title() }.to_string());
    let source_id =
        unsafe { calendar.source() }.map(|s| unsafe { s.sourceIdentifier() }.to_string());
    let allows_modifications = unsafe { calendar.allowsContentModifications() };
    let is_immutable = unsafe { calendar.isImmutable() };
    let is_subscribed = unsafe { calendar.isSubscribed() };

    // Calendar type: Local=0, CalDAV=1, Exchange=2, Subscription=3, Birthday=4
    let cal_type = unsafe { calendar.r#type() };
    let calendar_type = match cal_type.0 {
        0 => CalendarType::Local,
        1 => CalendarType::CalDAV,
        2 => CalendarType::Exchange,
        3 => CalendarType::Subscription,
        4 => CalendarType::Birthday,
        _ => CalendarType::Unknown,
    };

    // Read RGBA from CGColor
    let color: Option<(f64, f64, f64, f64)> = unsafe {
        calendar.CGColor().and_then(|cg| {
            use objc2_core_graphics::CGColor as CG;
            let n = CG::number_of_components(Some(&cg));
            if n >= 3 {
                let ptr = CG::components(Some(&cg));
                let r = *ptr;
                let g = *ptr.add(1);
                let b = *ptr.add(2);
                let a = if n >= 4 { *ptr.add(3) } else { 1.0 };
                Some((r, g, b, a))
            } else {
                None
            }
        })
    };

    // Allowed entity types
    let entity_mask = unsafe { calendar.allowedEntityTypes() };
    let mut allowed_entity_types = Vec::new();
    if entity_mask.0 & 1 != 0 {
        allowed_entity_types.push("event".to_string());
    }
    if entity_mask.0 & 2 != 0 {
        allowed_entity_types.push("reminder".to_string());
    }

    // EKCalendarEventAvailabilityMask: bitfield of which availability values
    // this calendar accepts on events. Bits: Busy=1, Free=2, Tentative=4,
    // Unavailable=8. Empty Vec = `EKCalendarEventAvailabilityNone`.
    let avail_mask = unsafe { calendar.supportedEventAvailabilities() };
    let mut supported_event_availabilities = Vec::new();
    if avail_mask.contains(EKCalendarEventAvailabilityMask::Busy) {
        supported_event_availabilities.push("busy".to_string());
    }
    if avail_mask.contains(EKCalendarEventAvailabilityMask::Free) {
        supported_event_availabilities.push("free".to_string());
    }
    if avail_mask.contains(EKCalendarEventAvailabilityMask::Tentative) {
        supported_event_availabilities.push("tentative".to_string());
    }
    if avail_mask.contains(EKCalendarEventAvailabilityMask::Unavailable) {
        supported_event_availabilities.push("unavailable".to_string());
    }

    CalendarInfo {
        identifier,
        title,
        source,
        source_id,
        calendar_type,
        allows_modifications,
        is_immutable,
        is_subscribed,
        color,
        allowed_entity_types,
        supported_event_availabilities,
    }
}

// ============================================================================
// Calendar Events Support
// ============================================================================

/// Event availability for scheduling.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum EventAvailability {
    NotSupported,
    #[default]
    Busy,
    Free,
    Tentative,
    Unavailable,
}

impl EventAvailability {
    /// Convert to the raw `EKEventAvailability` for writing.
    pub fn to_ek(self) -> EKEventAvailability {
        match self {
            Self::NotSupported => EKEventAvailability::NotSupported,
            Self::Busy => EKEventAvailability::Busy,
            Self::Free => EKEventAvailability::Free,
            Self::Tentative => EKEventAvailability::Tentative,
            Self::Unavailable => EKEventAvailability::Unavailable,
        }
    }

    /// Map an `EKEventAvailability` back to our enum. Unknown raw values
    /// (future Apple additions) fall back to `NotSupported`.
    pub fn from_ek(raw: EKEventAvailability) -> Self {
        match raw {
            EKEventAvailability::NotSupported => Self::NotSupported,
            EKEventAvailability::Busy => Self::Busy,
            EKEventAvailability::Free => Self::Free,
            EKEventAvailability::Tentative => Self::Tentative,
            EKEventAvailability::Unavailable => Self::Unavailable,
            _ => Self::NotSupported,
        }
    }
}

/// Event status.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum EventStatus {
    #[default]
    None,
    Confirmed,
    Tentative,
    Canceled,
}

impl EventStatus {
    pub fn from_ek(raw: EKEventStatus) -> Self {
        match raw {
            EKEventStatus::None => Self::None,
            EKEventStatus::Confirmed => Self::Confirmed,
            EKEventStatus::Tentative => Self::Tentative,
            EKEventStatus::Canceled => Self::Canceled,
            _ => Self::None,
        }
    }
}

/// Scope of a recurring-event edit or delete — mirrors Apple's `EKSpan`.
///
/// - `This`: only the specific occurrence you have a reference to.
/// - `Future`: this occurrence and every later occurrence in the same series.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum EventSpan {
    #[default]
    This,
    Future,
}

impl EventSpan {
    pub(crate) fn to_ek(self) -> EKSpan {
        match self {
            Self::This => EKSpan::ThisEvent,
            Self::Future => EKSpan::FutureEvents,
        }
    }
}

/// Participant role in an event.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ParticipantRole {
    Unknown,
    Required,
    Optional,
    Chair,
    NonParticipant,
}

/// Participant RSVP status.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ParticipantStatus {
    Unknown,
    Pending,
    Accepted,
    Declined,
    Tentative,
    Delegated,
    Completed,
    InProcess,
}

/// A participant (attendee) on an event or reminder.
#[derive(Debug, Clone)]
#[allow(non_snake_case)]
pub struct ParticipantInfo {
    pub name: Option<String>,
    pub URL: Option<String>,
    pub role: ParticipantRole,
    pub status: ParticipantStatus,
    pub is_current_user: bool,
}

/// Represents a calendar event with its properties.
#[derive(Debug, Clone)]
#[allow(non_snake_case)]
pub struct EventItem {
    /// Unique identifier for the event
    pub identifier: String,
    /// Title of the event
    pub title: String,
    /// Optional notes/description
    pub notes: Option<String>,
    /// Optional location (string)
    pub location: Option<String>,
    /// Start date/time
    pub start_date: DateTime<Local>,
    /// End date/time
    pub end_date: DateTime<Local>,
    /// Whether this is an all-day event
    pub all_day: bool,
    /// Calendar the event belongs to
    pub calendar_title: Option<String>,
    /// Calendar identifier
    pub calendar_id: Option<String>,
    /// URL associated with the event
    #[allow(non_snake_case)]
    pub URL: Option<String>,
    /// Availability for scheduling
    pub availability: EventAvailability,
    /// Event status (read-only)
    pub status: EventStatus,
    /// Whether this occurrence was modified from its recurring series
    pub is_detached: bool,
    /// Original date in a recurring series
    pub occurrence_date: Option<DateTime<Local>>,
    /// Geo-coordinate location
    pub structured_location: Option<StructuredLocation>,
    /// Date the event was first created (`EKCalendarItem.creationDate`).
    pub creation_date: Option<DateTime<Local>>,
    /// Date the event was last modified (`EKCalendarItem.lastModifiedDate`).
    pub last_modified_date: Option<DateTime<Local>>,
    /// Server-provided external identifier (`EKCalendarItem.calendarItemExternalIdentifier`).
    pub external_identifier: Option<String>,
    /// Item-level timezone (`EKCalendarItem.timeZone`). Distinct from the
    /// start/end date timezones — this is the event's own zone hint.
    pub timezone: Option<String>,
    /// Number of file attachments on the event (bound-less today — just the count).
    pub attachments_count: usize,
    /// Attendees
    pub attendees: Vec<ParticipantInfo>,
    /// Event organizer
    pub organizer: Option<ParticipantInfo>,
}

/// Input for `EventsManager::create_event`. Only `title`, `start`, and `end`
/// are required; spread `..Default::default()` for the rest. Mirrors
/// `ReminderDraft` for consistency.
#[derive(Debug, Clone, Default)]
#[allow(non_snake_case)]
pub struct EventDraft<'a> {
    pub title: &'a str,
    pub start: Option<DateTime<Local>>,
    pub end: Option<DateTime<Local>>,
    pub notes: Option<&'a str>,
    pub location: Option<&'a str>,
    pub calendar_title: Option<&'a str>,
    pub all_day: bool,
    pub URL: Option<&'a str>,
    pub availability: Option<EventAvailability>,
    pub structured_location: Option<&'a StructuredLocation>,
}

/// Input for `EventsManager::update_event`. Each field uses one of:
/// `None` (don't touch), `Some(value)` (set). Nullable fields use
/// `Option<Option<T>>` so `Some(None)` clears the value. `span` controls
/// whether the edit applies to just this occurrence or all future ones in
/// a recurring series.
#[derive(Debug, Clone, Default)]
#[allow(non_snake_case)]
pub struct EventPatch<'a> {
    pub title: Option<&'a str>,
    pub notes: Option<Option<&'a str>>,
    pub location: Option<Option<&'a str>>,
    pub start: Option<DateTime<Local>>,
    pub end: Option<DateTime<Local>>,
    pub all_day: Option<bool>,
    /// Move to a different calendar by title.
    pub calendar_title: Option<&'a str>,
    pub URL: Option<Option<&'a str>>,
    pub availability: Option<EventAvailability>,
    pub structured_location: Option<Option<&'a StructuredLocation>>,
    /// `This` (default) edits only this occurrence; `Future` propagates.
    pub span: EventSpan,
}

/// The events manager providing access to Calendar events via EventKit
pub struct EventsManager {
    store: Retained<EKEventStore>,
}

impl EventsManager {
    /// Creates a new EventsManager instance
    pub fn new() -> Self {
        let store = unsafe { EKEventStore::new() };
        Self { store }
    }

    /// Gets the current authorization status for calendar events
    pub fn authorization_status() -> AuthorizationStatus {
        let status = unsafe { EKEventStore::authorizationStatusForEntityType(EKEntityType::Event) };
        status.into()
    }

    /// Requests full access to calendar events (blocking)
    ///
    /// Returns Ok(true) if access was granted, Ok(false) if denied
    pub fn request_access(&self) -> Result<bool> {
        let result = Arc::new((Mutex::new(None::<(bool, Option<String>)>), Condvar::new()));
        let result_clone = Arc::clone(&result);

        let completion = RcBlock::new(move |granted: Bool, error: *mut NSError| {
            let error_msg = if !error.is_null() {
                let error_ref = unsafe { &*error };
                Some(format!("{:?}", error_ref))
            } else {
                None
            };

            let (lock, cvar) = &*result_clone;
            let mut res = lock.lock().unwrap();
            *res = Some((granted.as_bool(), error_msg));
            cvar.notify_one();
        });

        unsafe {
            let block_ptr = &*completion as *const _ as *mut _;
            self.store
                .requestFullAccessToEventsWithCompletion(block_ptr);
        }

        let (lock, cvar) = &*result;
        let mut res = lock.lock().unwrap();
        while res.is_none() {
            res = cvar.wait(res).unwrap();
        }

        match res.take() {
            Some((granted, None)) => Ok(granted),
            Some((_, Some(error))) => Err(EventKitError::AuthorizationRequestFailed(error)),
            None => Err(EventKitError::AuthorizationRequestFailed(
                "Unknown error".to_string(),
            )),
        }
    }

    /// Ensures we have authorization, requesting if needed
    pub fn ensure_authorized(&self) -> Result<()> {
        match Self::authorization_status() {
            AuthorizationStatus::FullAccess => Ok(()),
            AuthorizationStatus::NotDetermined => {
                if self.request_access()? {
                    Ok(())
                } else {
                    Err(EventKitError::AuthorizationDenied)
                }
            }
            AuthorizationStatus::Denied => Err(EventKitError::AuthorizationDenied),
            AuthorizationStatus::Restricted => Err(EventKitError::AuthorizationRestricted),
            AuthorizationStatus::WriteOnly => Ok(()),
        }
    }

    /// Lists all event calendars
    pub fn list_calendars(&self) -> Result<Vec<CalendarInfo>> {
        self.ensure_authorized()?;

        let calendars = unsafe { self.store.calendarsForEntityType(EKEntityType::Event) };

        let mut result = Vec::new();
        for calendar in calendars.iter() {
            result.push(calendar_to_info(&calendar));
        }

        Ok(result)
    }

    /// Gets the default calendar for new events
    pub fn default_calendar(&self) -> Result<CalendarInfo> {
        self.ensure_authorized()?;

        let calendar = unsafe { self.store.defaultCalendarForNewEvents() };

        match calendar {
            Some(cal) => Ok(calendar_to_info(&cal)),
            None => Err(EventKitError::NoDefaultCalendar),
        }
    }

    /// Fetches events for today
    pub fn fetch_today_events(&self) -> Result<Vec<EventItem>> {
        let now = Local::now();
        let start = now.date_naive().and_hms_opt(0, 0, 0).unwrap();
        let end = now.date_naive().and_hms_opt(23, 59, 59).unwrap();

        self.fetch_events(
            Local.from_local_datetime(&start).unwrap(),
            Local.from_local_datetime(&end).unwrap(),
            None,
        )
    }

    /// Fetches events for the next N days
    pub fn fetch_upcoming_events(&self, days: i64) -> Result<Vec<EventItem>> {
        let now = Local::now();
        let end = now + Duration::days(days);
        self.fetch_events(now, end, None)
    }

    /// Fetches events in a date range
    pub fn fetch_events(
        &self,
        start: DateTime<Local>,
        end: DateTime<Local>,
        calendar_titles: Option<&[&str]>,
    ) -> Result<Vec<EventItem>> {
        self.ensure_authorized()?;

        if start >= end {
            return Err(EventKitError::InvalidDateRange);
        }

        let calendars: Option<Retained<NSArray<EKCalendar>>> = match calendar_titles {
            Some(titles) => {
                let all_calendars =
                    unsafe { self.store.calendarsForEntityType(EKEntityType::Event) };
                let mut matching: Vec<Retained<EKCalendar>> = Vec::new();

                for cal in all_calendars.iter() {
                    let title = unsafe { cal.title() };
                    let title_str = title.to_string();
                    if titles.iter().any(|t| *t == title_str) {
                        matching.push(cal.retain());
                    }
                }

                if matching.is_empty() {
                    return Err(EventKitError::CalendarNotFound(titles.join(", ")));
                }

                Some(NSArray::from_retained_slice(&matching))
            }
            None => None,
        };

        let start_date = datetime_to_nsdate(start);
        let end_date = datetime_to_nsdate(end);

        let predicate = unsafe {
            self.store
                .predicateForEventsWithStartDate_endDate_calendars(
                    &start_date,
                    &end_date,
                    calendars.as_deref(),
                )
        };

        let events = unsafe { self.store.eventsMatchingPredicate(&predicate) };

        let mut items = Vec::new();
        for event in events.iter() {
            items.push(event_to_item(&event));
        }

        // Sort by start date
        items.sort_by_key(|a| a.start_date);

        Ok(items)
    }

    /// Creates a new event. Build the input with `EventDraft` — only
    /// `title`, `start`, and `end` are required; spread `..Default::default()`
    /// for the rest.
    pub fn create_event(&self, draft: &EventDraft<'_>) -> Result<EventItem> {
        self.ensure_authorized()?;

        let start = draft.start.ok_or(EventKitError::InvalidDateRange)?;
        let end = draft.end.ok_or(EventKitError::InvalidDateRange)?;

        let event = unsafe { EKEvent::eventWithEventStore(&self.store) };

        let ns_title = NSString::from_str(draft.title);
        unsafe { event.setTitle(Some(&ns_title)) };

        let start_date = datetime_to_nsdate(start);
        let end_date = datetime_to_nsdate(end);
        unsafe {
            event.setStartDate(Some(&start_date));
            event.setEndDate(Some(&end_date));
            event.setAllDay(draft.all_day);
        }

        if let Some(notes_text) = draft.notes {
            let ns_notes = NSString::from_str(notes_text);
            unsafe { event.setNotes(Some(&ns_notes)) };
        }

        if let Some(loc) = draft.location {
            let ns_location = NSString::from_str(loc);
            unsafe { event.setLocation(Some(&ns_location)) };
        }

        if draft.URL.is_some() {
            set_item_URL(&event, draft.URL)?;
        }

        if let Some(av) = draft.availability {
            unsafe { event.setAvailability(av.to_ek()) };
        }

        if let Some(sl) = draft.structured_location {
            let built = build_ek_structured_location(sl);
            unsafe { event.setStructuredLocation(Some(&built)) };
        }

        let calendar = if let Some(cal_title) = draft.calendar_title {
            self.find_calendar_by_title(cal_title)?
        } else {
            unsafe { self.store.defaultCalendarForNewEvents() }
                .ok_or(EventKitError::NoDefaultCalendar)?
        };
        unsafe { event.setCalendar(Some(&calendar)) };

        self.save_event_and_refresh(&event, EKSpan::ThisEvent)?;

        Ok(event_to_item(&event))
    }

    /// Updates an existing event
    /// Updates an existing event. Build the changeset with `EventPatch` —
    /// only the fields you set are written. For nullable fields,
    /// `Some(Some(v))` writes, `Some(None)` clears. `span` controls
    /// whether the edit applies to just this occurrence or all future
    /// occurrences in a recurring series.
    pub fn update_event(&self, identifier: &str, patch: &EventPatch<'_>) -> Result<EventItem> {
        self.ensure_authorized()?;

        let event = self.find_event_by_id(identifier)?;

        if let Some(t) = patch.title {
            let ns_title = NSString::from_str(t);
            unsafe { event.setTitle(Some(&ns_title)) };
        }

        if let Some(notes_opt) = patch.notes {
            let ns = notes_opt.map(NSString::from_str);
            unsafe { event.setNotes(ns.as_deref()) };
        }

        if let Some(loc_opt) = patch.location {
            let ns = loc_opt.map(NSString::from_str);
            unsafe { event.setLocation(ns.as_deref()) };
        }

        if let Some(s) = patch.start {
            let start_date = datetime_to_nsdate(s);
            unsafe { event.setStartDate(Some(&start_date)) };
        }

        if let Some(e) = patch.end {
            let end_date = datetime_to_nsdate(e);
            unsafe { event.setEndDate(Some(&end_date)) };
        }

        if let Some(ad) = patch.all_day {
            unsafe { event.setAllDay(ad) };
        }

        if let Some(url_opt) = patch.URL {
            set_item_URL(&event, url_opt)?;
        }

        if let Some(av) = patch.availability {
            unsafe { event.setAvailability(av.to_ek()) };
        }

        if let Some(sl_opt) = patch.structured_location {
            let built = sl_opt.map(build_ek_structured_location);
            unsafe { event.setStructuredLocation(built.as_deref()) };
        }

        if let Some(cal_title) = patch.calendar_title {
            let calendar = self.find_calendar_by_title(cal_title)?;
            unsafe { event.setCalendar(Some(&calendar)) };
        }

        self.save_event_and_refresh(&event, patch.span.to_ek())?;

        Ok(event_to_item(&event))
    }

    /// Deletes an event
    pub fn delete_event(&self, identifier: &str, affect_future: bool) -> Result<()> {
        self.ensure_authorized()?;

        let event = self.find_event_by_id(identifier)?;
        let span = if affect_future {
            EKSpan::FutureEvents
        } else {
            EKSpan::ThisEvent
        };

        unsafe {
            self.store
                .removeEvent_span_commit_error(&event, span, true)
                .map_err(|e| EventKitError::DeleteFailed(format!("{:?}", e)))?;
        }

        Ok(())
    }

    /// Gets an event by its identifier
    pub fn get_event(&self, identifier: &str) -> Result<EventItem> {
        self.ensure_authorized()?;
        let event = self.find_event_by_id(identifier)?;
        Ok(event_to_item(&event))
    }

    // ========================================================================
    // Event Calendar Management
    // ========================================================================

    /// Creates a new event calendar.
    pub fn create_event_calendar(&self, title: &str) -> Result<CalendarInfo> {
        self.ensure_authorized()?;
        let calendar = unsafe {
            EKCalendar::calendarForEntityType_eventStore(EKEntityType::Event, &self.store)
        };
        let ns_title = NSString::from_str(title);
        unsafe { calendar.setTitle(&ns_title) };

        // Use the default source
        if let Some(default_cal) = unsafe { self.store.defaultCalendarForNewEvents() }
            && let Some(source) = unsafe { default_cal.source() }
        {
            unsafe { calendar.setSource(Some(&source)) };
        }

        unsafe {
            self.store
                .saveCalendar_commit_error(&calendar, true)
                .map_err(|e| EventKitError::SaveFailed(format!("{:?}", e)))?;
        }
        Ok(calendar_to_info(&calendar))
    }

    /// Renames an event calendar.
    /// Rename an event calendar (backward compat wrapper).
    pub fn rename_event_calendar(&self, identifier: &str, new_title: &str) -> Result<CalendarInfo> {
        self.update_event_calendar(identifier, Some(new_title), None)
    }

    /// Update an event calendar — name, color, or both.
    pub fn update_event_calendar(
        &self,
        identifier: &str,
        new_title: Option<&str>,
        color_rgba: Option<(f64, f64, f64, f64)>,
    ) -> Result<CalendarInfo> {
        self.ensure_authorized()?;
        let calendar = unsafe {
            self.store
                .calendarWithIdentifier(&NSString::from_str(identifier))
        }
        .ok_or_else(|| EventKitError::CalendarNotFound(identifier.to_string()))?;

        if let Some(title) = new_title {
            let ns_title = NSString::from_str(title);
            unsafe { calendar.setTitle(&ns_title) };
        }

        if let Some((r, g, b, a)) = color_rgba {
            let cg = objc2_core_graphics::CGColor::new_srgb(r, g, b, a);
            unsafe { calendar.setCGColor(Some(&cg)) };
        }

        unsafe {
            self.store
                .saveCalendar_commit_error(&calendar, true)
                .map_err(|e| EventKitError::SaveFailed(format!("{:?}", e)))?;
        }
        Ok(calendar_to_info(&calendar))
    }

    /// Deletes an event calendar.
    pub fn delete_event_calendar(&self, identifier: &str) -> Result<()> {
        self.ensure_authorized()?;
        let calendar = unsafe {
            self.store
                .calendarWithIdentifier(&NSString::from_str(identifier))
        }
        .ok_or_else(|| EventKitError::CalendarNotFound(identifier.to_string()))?;

        unsafe {
            self.store
                .removeCalendar_commit_error(&calendar, true)
                .map_err(|e| EventKitError::DeleteFailed(format!("{:?}", e)))?;
        }
        Ok(())
    }

    // ========================================================================
    // Event Alarm Management (shared via EKCalendarItem)
    // ========================================================================

    /// Lists all alarms on an event.
    pub fn get_event_alarms(&self, identifier: &str) -> Result<Vec<AlarmInfo>> {
        self.ensure_authorized()?;
        let event = self.find_event_by_id(identifier)?;
        Ok(get_item_alarms(&event))
    }

    /// Adds an alarm to an event.
    pub fn add_event_alarm(&self, identifier: &str, alarm: &AlarmInfo) -> Result<()> {
        self.ensure_authorized()?;
        let event = self.find_event_by_id(identifier)?;
        add_item_alarm(&event, alarm)?;
        self.save_event_and_refresh(&event, EKSpan::ThisEvent)?;
        Ok(())
    }

    // ========================================================================
    // Event Recurrence Management (shared via EKCalendarItem)
    // ========================================================================

    /// Gets recurrence rules on an event.
    pub fn get_event_recurrence_rules(&self, identifier: &str) -> Result<Vec<RecurrenceRule>> {
        self.ensure_authorized()?;
        let event = self.find_event_by_id(identifier)?;
        Ok(get_item_recurrence_rules(&event))
    }

    /// Sets a recurrence rule on an event (replaces any existing rules).
    pub fn set_event_recurrence_rule(&self, identifier: &str, rule: &RecurrenceRule) -> Result<()> {
        self.ensure_authorized()?;
        let event = self.find_event_by_id(identifier)?;
        set_item_recurrence_rule(&event, rule);
        self.save_event_and_refresh(&event, EKSpan::ThisEvent)?;
        Ok(())
    }

    /// Removes all recurrence rules from an event.
    pub fn remove_event_recurrence_rules(&self, identifier: &str) -> Result<()> {
        self.ensure_authorized()?;
        let event = self.find_event_by_id(identifier)?;
        clear_item_recurrence_rules(&event);
        self.save_event_and_refresh(&event, EKSpan::ThisEvent)?;
        Ok(())
    }

    /// Removes a specific alarm from an event by index.
    pub fn remove_event_alarm(&self, identifier: &str, index: usize) -> Result<()> {
        self.ensure_authorized()?;
        let event = self.find_event_by_id(identifier)?;
        remove_item_alarm(&event, index)?;
        self.save_event_and_refresh(&event, EKSpan::ThisEvent)?;
        Ok(())
    }

    /// Set or clear the URL on an event.
    #[allow(non_snake_case)]
    pub fn set_event_URL(&self, identifier: &str, url: Option<&str>) -> Result<()> {
        self.ensure_authorized()?;
        let event = self.find_event_by_id(identifier)?;
        set_item_URL(&event, url)?;
        self.save_event_and_refresh(&event, EKSpan::ThisEvent)?;
        Ok(())
    }

    /// Set the event's `availability` field. Controls how the event shows
    /// on the timeline (Busy/Free/Tentative/Unavailable). Always uses
    /// `EKSpan::ThisEvent` since availability is typically per-instance.
    pub fn set_event_availability(
        &self,
        identifier: &str,
        availability: EventAvailability,
    ) -> Result<()> {
        self.ensure_authorized()?;
        let event = self.find_event_by_id(identifier)?;
        unsafe { event.setAvailability(availability.to_ek()) };
        self.save_event_and_refresh(&event, EKSpan::ThisEvent)
    }

    // Helper to find a calendar by title
    fn find_calendar_by_title(&self, title: &str) -> Result<Retained<EKCalendar>> {
        let calendars = unsafe { self.store.calendarsForEntityType(EKEntityType::Event) };

        for cal in calendars.iter() {
            let cal_title = unsafe { cal.title() };
            if cal_title.to_string() == title {
                return Ok(cal.retain());
            }
        }

        Err(EventKitError::CalendarNotFound(title.to_string()))
    }

    // Helper to find an event by identifier. Refreshes sources first so we
    // pick up edits made elsewhere (mirrors `RemindersManager::find_reminder_by_id`).
    fn find_event_by_id(&self, identifier: &str) -> Result<Retained<EKEvent>> {
        unsafe { self.store.refreshSourcesIfNecessary() };
        let ns_id = NSString::from_str(identifier);
        let event = unsafe { self.store.eventWithIdentifier(&ns_id) };

        match event {
            Some(e) => Ok(e),
            None => Err(EventKitError::ItemNotFound(identifier.to_string())),
        }
    }

    /// Save an event under the given span + refresh sources so subsequent
    /// reads see the just-committed state. All `pub fn` event save paths
    /// route through here, mirroring `RemindersManager::save_reminder_and_refresh`.
    fn save_event_and_refresh(&self, event: &EKEvent, span: EKSpan) -> Result<()> {
        unsafe {
            self.store
                .saveEvent_span_commit_error(event, span, true)
                .map_err(|e| EventKitError::SaveFailed(format!("{:?}", e)))?;
            self.store.refreshSourcesIfNecessary();
        }
        Ok(())
    }
}

impl Default for EventsManager {
    fn default() -> Self {
        Self::new()
    }
}

// Helper function to convert EKEvent to EventItem
fn event_to_item(event: &EKEvent) -> EventItem {
    let identifier = unsafe { event.eventIdentifier() }
        .map(|s| s.to_string())
        .unwrap_or_default();
    let title = unsafe { event.title() }.to_string();
    let notes = unsafe { event.notes() }.map(|n| n.to_string());
    let location = unsafe { event.location() }.map(|l| l.to_string());
    let all_day = unsafe { event.isAllDay() };
    let cal = unsafe { event.calendar() };
    let calendar_title = cal.as_ref().map(|c| unsafe { c.title() }.to_string());
    let calendar_id = cal
        .as_ref()
        .map(|c| unsafe { c.calendarIdentifier() }.to_string());

    let start_ns: Retained<NSDate> = unsafe { event.startDate() };
    let end_ns: Retained<NSDate> = unsafe { event.endDate() };
    let start_date = nsdate_to_datetime(&start_ns);
    let end_date = nsdate_to_datetime(&end_ns);

    #[allow(non_snake_case)]
    let URL = get_item_URL(event);

    let availability = EventAvailability::from_ek(unsafe { event.availability() });
    let status = EventStatus::from_ek(unsafe { event.status() });

    let is_detached = unsafe { event.isDetached() };
    let occurrence_date = unsafe { event.occurrenceDate() }.map(|d| nsdate_to_datetime(&d));

    // Structured location
    let structured_location = unsafe { event.structuredLocation() }.map(|loc| {
        let title = unsafe { loc.title() }
            .map(|t| t.to_string())
            .unwrap_or_default();
        let radius = unsafe { loc.radius() };
        let (latitude, longitude) = unsafe { loc.geoLocation() }
            .map(|geo| {
                let coord = unsafe { geo.coordinate() };
                (coord.latitude, coord.longitude)
            })
            .unwrap_or((0.0, 0.0));
        StructuredLocation {
            title,
            latitude,
            longitude,
            radius,
        }
    });

    // Attendees (shared via EKCalendarItem)
    let attendees = get_item_attendees(event);

    // Organizer (event-only)
    let organizer = unsafe { event.organizer() }.map(|p| participant_to_info(&p));

    // EKCalendarItem-inherited read fields (parity with ReminderItem)
    let creation_date = unsafe { event.creationDate() }.map(|d| nsdate_to_datetime(&d));
    let last_modified_date = unsafe { event.lastModifiedDate() }.map(|d| nsdate_to_datetime(&d));
    let external_identifier =
        unsafe { event.calendarItemExternalIdentifier() }.map(|s| s.to_string());
    let timezone = unsafe { event.timeZone() }.map(|tz| tz.name().to_string());
    let attachments_count = get_item_attachments_count(event);

    EventItem {
        identifier,
        title,
        notes,
        location,
        start_date,
        end_date,
        all_day,
        calendar_title,
        calendar_id,
        URL,
        availability,
        status,
        is_detached,
        occurrence_date,
        structured_location,
        creation_date,
        last_modified_date,
        external_identifier,
        timezone,
        attachments_count,
        attendees,
        organizer,
    }
}

// Read attendees from an EKCalendarItem (shared by events and reminders)
fn get_item_attendees(item: &EKCalendarItem) -> Vec<ParticipantInfo> {
    let attendees = unsafe { item.attendees() };
    let Some(attendees) = attendees else {
        return Vec::new();
    };
    let mut result = Vec::new();
    for i in 0..attendees.len() {
        let p = attendees.objectAtIndex(i);
        result.push(participant_to_info(&p));
    }
    result
}

// Convert an EKParticipant to ParticipantInfo
fn participant_to_info(p: &objc2_event_kit::EKParticipant) -> ParticipantInfo {
    let name = unsafe { p.name() }.map(|n| n.to_string());
    #[allow(non_snake_case)]
    let URL = unsafe { p.URL() }.absoluteString().map(|s| s.to_string());

    // Role: 0=Unknown, 1=Required, 2=Optional, 3=Chair, 4=NonParticipant
    let role = unsafe { p.participantRole() };
    let role = match role.0 {
        1 => ParticipantRole::Required,
        2 => ParticipantRole::Optional,
        3 => ParticipantRole::Chair,
        4 => ParticipantRole::NonParticipant,
        _ => ParticipantRole::Unknown,
    };

    // Status: 0=Unknown, 1=Pending, 2=Accepted, 3=Declined, 4=Tentative,
    //         5=Delegated, 6=Completed, 7=InProcess
    let status = unsafe { p.participantStatus() };
    let status = match status.0 {
        1 => ParticipantStatus::Pending,
        2 => ParticipantStatus::Accepted,
        3 => ParticipantStatus::Declined,
        4 => ParticipantStatus::Tentative,
        5 => ParticipantStatus::Delegated,
        6 => ParticipantStatus::Completed,
        7 => ParticipantStatus::InProcess,
        _ => ParticipantStatus::Unknown,
    };

    let is_current_user = unsafe { p.isCurrentUser() };

    ParticipantInfo {
        name,
        URL,
        role,
        status,
        is_current_user,
    }
}

// Helper to convert chrono DateTime to NSDate
fn datetime_to_nsdate(dt: DateTime<Local>) -> Retained<NSDate> {
    let timestamp = dt.timestamp() as f64;
    NSDate::dateWithTimeIntervalSince1970(timestamp)
}

// Helper to convert NSDate to chrono DateTime
fn nsdate_to_datetime(date: &NSDate) -> DateTime<Local> {
    let timestamp = date.timeIntervalSince1970();
    Local.timestamp_opt(timestamp as i64, 0).unwrap()
}

// Helper to convert NSDateComponents to chrono DateTime
fn date_components_to_datetime(components: &NSDateComponents) -> Option<DateTime<Local>> {
    // Get a calendar to convert components to a date
    let calendar = NSCalendar::currentCalendar();

    // Convert components to NSDate using the calendar
    let date = calendar.dateFromComponents(components)?;

    Some(nsdate_to_datetime(&date))
}

// Helper to convert chrono DateTime to NSDateComponents
fn datetime_to_date_components(dt: DateTime<Local>) -> Retained<NSDateComponents> {
    let components = NSDateComponents::new();

    components.setYear(dt.year() as isize);
    components.setMonth(dt.month() as isize);
    components.setDay(dt.day() as isize);
    components.setHour(dt.hour() as isize);
    components.setMinute(dt.minute() as isize);
    components.setSecond(dt.second() as isize);

    components
}

// ============================================================================
// Shared EKCalendarItem operations
// ============================================================================
// EKCalendarItem is the base class for both EKReminder and EKEvent.
// These functions operate on the shared interface — both types auto-deref to it.

/// Read all alarms from a calendar item.
fn get_item_alarms(item: &EKCalendarItem) -> Vec<AlarmInfo> {
    let alarms = unsafe { item.alarms() };
    let Some(alarms) = alarms else {
        return Vec::new();
    };
    let mut result = Vec::new();
    for i in 0..alarms.len() {
        let alarm = alarms.objectAtIndex(i);
        result.push(alarm_to_info(&alarm));
    }
    result
}

/// Add an alarm to a calendar item.
fn add_item_alarm(item: &EKCalendarItem, alarm: &AlarmInfo) -> Result<()> {
    let ek_alarm = create_ek_alarm(alarm)?;
    unsafe { item.addAlarm(&ek_alarm) };
    Ok(())
}

/// Remove an alarm from a calendar item by index.
fn remove_item_alarm(item: &EKCalendarItem, index: usize) -> Result<()> {
    let alarms = unsafe { item.alarms() };
    let Some(alarms) = alarms else {
        return Err(EventKitError::ItemNotFound("No alarms on this item".into()));
    };
    if index >= alarms.len() {
        return Err(EventKitError::ItemNotFound(format!(
            "Alarm index {} out of range ({})",
            index,
            alarms.len()
        )));
    }
    let alarm = alarms.objectAtIndex(index);
    unsafe { item.removeAlarm(&alarm) };
    Ok(())
}

/// Clear all alarms from a calendar item.
fn clear_item_alarms(item: &EKCalendarItem) {
    unsafe { item.setAlarms(None) };
}

/// Read all recurrence rules from a calendar item.
fn get_item_recurrence_rules(item: &EKCalendarItem) -> Vec<RecurrenceRule> {
    let rules = unsafe { item.recurrenceRules() };
    let Some(rules) = rules else {
        return Vec::new();
    };
    let mut result = Vec::new();
    for i in 0..rules.len() {
        let rule = rules.objectAtIndex(i);
        result.push(recurrence_rule_to_info(&rule));
    }
    result
}

/// Set a single recurrence rule on a calendar item (replaces any existing).
fn set_item_recurrence_rule(item: &EKCalendarItem, rule: &RecurrenceRule) {
    let ek_rule = create_ek_recurrence_rule(rule);
    unsafe {
        let rules = NSArray::from_retained_slice(&[ek_rule]);
        item.setRecurrenceRules(Some(&rules));
    }
}

/// Clear all recurrence rules from a calendar item.
fn clear_item_recurrence_rules(item: &EKCalendarItem) {
    unsafe { item.setRecurrenceRules(None) };
}

/// Set URL on a calendar item.
///
/// Uses `+[NSURL URLWithString:encodingInvalidCharacters:NO]` for strict
/// RFC 3986 validation — returns `Err(InvalidURL)` if the string isn't a
/// well-formed URL instead of silently auto-encoding or panicking.
#[allow(non_snake_case)]
fn set_item_URL(item: &EKCalendarItem, url: Option<&str>) -> Result<()> {
    let ns_url = match url {
        None => None,
        Some(s) => {
            let ns_str = NSString::from_str(s);
            let parsed =
                objc2_foundation::NSURL::URLWithString_encodingInvalidCharacters(&ns_str, false);
            match parsed {
                Some(u) => Some(u),
                None => return Err(EventKitError::InvalidURL(s.to_string())),
            }
        }
    };
    unsafe { item.setURL(ns_url.as_deref()) };
    Ok(())
}

/// Read URL from a calendar item.
#[allow(non_snake_case)]
fn get_item_URL(item: &EKCalendarItem) -> Option<String> {
    unsafe { item.URL() }.map(|u| u.absoluteString().unwrap().to_string())
}

/// Set the free-text `location` on a calendar item. Pass `None` to clear.
///
/// iCloud caveat: on iCloud-synced reminder lists the string `location`
/// property may silently revert to null even though `setLocation:` returns
/// success and the save commits. iCloud Reminders treats the location as a
/// derived view of `structuredLocation` set via a location-based alarm.
/// To attach a location that survives iCloud sync, use
/// `RemindersManager::set_geofence` (or pass `geofence` to a `ReminderDraft`).
fn set_item_location(item: &EKCalendarItem, location: Option<&str>) {
    match location {
        Some(text) => {
            let ns_loc = NSString::from_str(text);
            unsafe { item.setLocation(Some(&ns_loc)) };
        }
        None => unsafe { item.setLocation(None) },
    }
}

/// Set the timezone applied to the reminder's due date. EventKit derives
/// `EKReminder.dueDateTimeZone` from `dueDateComponents.timeZone` (the
/// `dueDateTimeZone` property is readonly), so the setter mutates the
/// components and re-assigns them. Pass `None` to clear.
///
/// No-op if the reminder has no due date yet — without `dueDateComponents`
/// there's nothing to hang the timezone on. Callers that want a timezone-
/// scoped reminder should set the due date first.
fn set_reminder_due_date_timezone(reminder: &EKReminder, tz_name: Option<&str>) {
    use objc2_foundation::NSTimeZone;
    let Some(components) = (unsafe { reminder.dueDateComponents() }) else {
        return;
    };
    let tz = tz_name.and_then(|n| {
        let ns_n = NSString::from_str(n);
        NSTimeZone::timeZoneWithName(&ns_n)
    });
    components.setTimeZone(tz.as_deref());
    unsafe { reminder.setDueDateComponents(Some(&components)) };
}

/// Set or clear the reminder's own `structuredLocation` — the iCloud-native
/// location chip Reminders.app reads/writes. Pass `None` to clear.
///
/// Uses `msg_send!` because `objc2-event-kit` 0.3 didn't generate
/// `setStructuredLocation:` on `EKCalendarItem` / `EKReminder` (only on
/// `EKEvent` and `EKAlarm`). The method exists at runtime — confirmed via
/// `class_copyMethodList`.
fn set_reminder_structured_location(reminder: &EKReminder, loc: Option<&StructuredLocation>) {
    use objc2::msg_send;
    let ek = loc.map(build_ek_structured_location);
    // EKCalendarItem exposes both — try the no-prediction variant first
    // (skips iCloud's "smart suggest based on title" pass), then the plain
    // setter. On iCloud-synced reminder lists the underlying daemon
    // silently drops both mutations; the alarm-based path (`set_geofence`)
    // is the only persistence route iCloud honors. We still call these
    // setters because local/CalDAV reminder sources accept them.
    let _: () =
        unsafe { msg_send![reminder, setStructuredLocationWithoutPrediction: ek.as_deref()] };
    let _: () = unsafe { msg_send![reminder, setStructuredLocation: ek.as_deref()] };
}

/// Build an `EKStructuredLocation` from our plain `StructuredLocation`.
/// Geo coordinates only set when the `location` feature is on (CoreLocation).
fn build_ek_structured_location(loc: &StructuredLocation) -> Retained<EKStructuredLocation> {
    let title = NSString::from_str(&loc.title);
    let structured = unsafe { EKStructuredLocation::locationWithTitle(&title) };
    unsafe { structured.setRadius(loc.radius) };
    #[cfg(feature = "location")]
    {
        use objc2::AnyThread;
        use objc2_core_location::CLLocation;
        let cl = unsafe {
            CLLocation::initWithLatitude_longitude(CLLocation::alloc(), loc.latitude, loc.longitude)
        };
        unsafe { structured.setGeoLocation(Some(&cl)) };
    }
    structured
}

/// Attach (or replace) a location-based alarm on the reminder. EventKit has
/// no `structuredLocation` directly on `EKCalendarItem`/`EKReminder` — the
/// geofence lives on an `EKAlarm` with `proximity`. Passing `None` clears
/// every proximity-bearing alarm.
fn set_reminder_geofence(
    reminder: &EKReminder,
    geofence: Option<(&StructuredLocation, AlarmProximity)>,
) {
    // Strip existing location-based alarms — leave time-based alarms alone.
    if let Some(alarms) = unsafe { reminder.alarms() } {
        for i in (0..alarms.len()).rev() {
            let alarm = alarms.objectAtIndex(i);
            if unsafe { alarm.proximity() } != EKAlarmProximity::None {
                unsafe { reminder.removeAlarm(&alarm) };
            }
        }
    }

    let Some((loc, proximity)) = geofence else {
        return;
    };

    let info = AlarmInfo {
        relative_offset: Some(0.0),
        proximity,
        location: Some(loc.clone()),
        ..Default::default()
    };
    // safe to expect — info has no `url`, the only field that can fail to parse
    let alarm = create_ek_alarm(&info).expect("geofence alarm has no URL to parse");
    unsafe { reminder.addAlarm(&alarm) };
}

// ============================================================================
// Type conversion helpers
// ============================================================================

// Helper to convert an EKRecurrenceRule to a RecurrenceRule
fn recurrence_rule_to_info(rule: &EKRecurrenceRule) -> RecurrenceRule {
    let frequency = unsafe { rule.frequency() };
    let frequency = match frequency {
        EKRecurrenceFrequency::Daily => RecurrenceFrequency::Daily,
        EKRecurrenceFrequency::Weekly => RecurrenceFrequency::Weekly,
        EKRecurrenceFrequency::Monthly => RecurrenceFrequency::Monthly,
        EKRecurrenceFrequency::Yearly => RecurrenceFrequency::Yearly,
        _ => RecurrenceFrequency::Daily,
    };

    let interval = unsafe { rule.interval() } as usize;

    let end = unsafe { rule.recurrenceEnd() }
        .map(|end| {
            let count = unsafe { end.occurrenceCount() };
            if count > 0 {
                RecurrenceEndCondition::AfterCount(count)
            } else if let Some(date) = unsafe { end.endDate() } {
                RecurrenceEndCondition::OnDate(nsdate_to_datetime(&date))
            } else {
                RecurrenceEndCondition::Never
            }
        })
        .unwrap_or(RecurrenceEndCondition::Never);

    let days_of_week = unsafe { rule.daysOfTheWeek() }.map(|days| {
        let mut result = Vec::new();
        for i in 0..days.len() {
            let day = days.objectAtIndex(i);
            let weekday = unsafe { day.dayOfTheWeek() };
            result.push(weekday.0 as u8);
        }
        result
    });

    fn nsnumber_array_to_vec(arr: Option<Retained<NSArray<NSNumber>>>) -> Option<Vec<i32>> {
        arr.map(|days| {
            let mut result = Vec::with_capacity(days.len());
            for i in 0..days.len() {
                result.push(days.objectAtIndex(i).intValue());
            }
            result
        })
    }

    let days_of_month = nsnumber_array_to_vec(unsafe { rule.daysOfTheMonth() });
    let months_of_year = nsnumber_array_to_vec(unsafe { rule.monthsOfTheYear() });
    let weeks_of_year = nsnumber_array_to_vec(unsafe { rule.weeksOfTheYear() });
    let days_of_year = nsnumber_array_to_vec(unsafe { rule.daysOfTheYear() });
    let set_positions = nsnumber_array_to_vec(unsafe { rule.setPositions() });

    RecurrenceRule {
        frequency,
        interval,
        end,
        days_of_week,
        days_of_month,
        months_of_year,
        weeks_of_year,
        days_of_year,
        set_positions,
    }
}

// Helper to create an EKRecurrenceRule from a RecurrenceRule
fn create_ek_recurrence_rule(rule: &RecurrenceRule) -> Retained<EKRecurrenceRule> {
    let frequency = match rule.frequency {
        RecurrenceFrequency::Daily => EKRecurrenceFrequency::Daily,
        RecurrenceFrequency::Weekly => EKRecurrenceFrequency::Weekly,
        RecurrenceFrequency::Monthly => EKRecurrenceFrequency::Monthly,
        RecurrenceFrequency::Yearly => EKRecurrenceFrequency::Yearly,
    };

    let end = match &rule.end {
        RecurrenceEndCondition::Never => None,
        RecurrenceEndCondition::AfterCount(count) => {
            Some(unsafe { EKRecurrenceEnd::recurrenceEndWithOccurrenceCount(*count) })
        }
        RecurrenceEndCondition::OnDate(date) => {
            let nsdate = datetime_to_nsdate(*date);
            Some(unsafe { EKRecurrenceEnd::recurrenceEndWithEndDate(&nsdate) })
        }
    };

    let days_of_week: Option<Vec<Retained<EKRecurrenceDayOfWeek>>> =
        rule.days_of_week.as_ref().map(|days| {
            days.iter()
                .map(|&d| {
                    let weekday = EKWeekday(d as isize);
                    unsafe { EKRecurrenceDayOfWeek::dayOfWeek(weekday) }
                })
                .collect()
        });

    fn vec_to_nsnumber_array(v: Option<&Vec<i32>>) -> Option<Vec<Retained<NSNumber>>> {
        v.map(|nums| nums.iter().map(|&n| NSNumber::new_i32(n)).collect())
    }
    let days_of_month = vec_to_nsnumber_array(rule.days_of_month.as_ref());
    let months_of_year = vec_to_nsnumber_array(rule.months_of_year.as_ref());
    let weeks_of_year = vec_to_nsnumber_array(rule.weeks_of_year.as_ref());
    let days_of_year = vec_to_nsnumber_array(rule.days_of_year.as_ref());
    let set_positions = vec_to_nsnumber_array(rule.set_positions.as_ref());

    let days_of_week_arr = days_of_week
        .as_ref()
        .map(|v| NSArray::from_retained_slice(v));
    let days_of_month_arr = days_of_month
        .as_ref()
        .map(|v| NSArray::from_retained_slice(v));
    let months_of_year_arr = months_of_year
        .as_ref()
        .map(|v| NSArray::from_retained_slice(v));
    let weeks_of_year_arr = weeks_of_year
        .as_ref()
        .map(|v| NSArray::from_retained_slice(v));
    let days_of_year_arr = days_of_year
        .as_ref()
        .map(|v| NSArray::from_retained_slice(v));
    let set_positions_arr = set_positions
        .as_ref()
        .map(|v| NSArray::from_retained_slice(v));

    unsafe {
        use objc2::AnyThread;
        EKRecurrenceRule::initRecurrenceWithFrequency_interval_daysOfTheWeek_daysOfTheMonth_monthsOfTheYear_weeksOfTheYear_daysOfTheYear_setPositions_end(
            EKRecurrenceRule::alloc(),
            frequency,
            rule.interval as isize,
            days_of_week_arr.as_deref(),
            days_of_month_arr.as_deref(),
            months_of_year_arr.as_deref(),
            weeks_of_year_arr.as_deref(),
            days_of_year_arr.as_deref(),
            set_positions_arr.as_deref(),
            end.as_deref(),
        )
    }
}

// Helper to convert an EKAlarm to an AlarmInfo
fn alarm_to_info(alarm: &EKAlarm) -> AlarmInfo {
    let relative_offset = unsafe { alarm.relativeOffset() };
    let absolute_date = unsafe { alarm.absoluteDate() }.map(|d| nsdate_to_datetime(&d));

    let proximity = unsafe { alarm.proximity() };
    let proximity = match proximity {
        EKAlarmProximity::Enter => AlarmProximity::Enter,
        EKAlarmProximity::Leave => AlarmProximity::Leave,
        _ => AlarmProximity::None,
    };

    let location = unsafe { alarm.structuredLocation() }.map(|loc| {
        let title = unsafe { loc.title() }
            .map(|t| t.to_string())
            .unwrap_or_default();
        let radius = unsafe { loc.radius() };
        let (latitude, longitude) = unsafe { loc.geoLocation() }
            .map(|geo| {
                let coord = unsafe { geo.coordinate() };
                (coord.latitude, coord.longitude)
            })
            .unwrap_or((0.0, 0.0));

        StructuredLocation {
            title,
            latitude,
            longitude,
            radius,
        }
    });

    let email_address = unsafe { alarm.emailAddress() }.map(|s| s.to_string());
    let sound_name = unsafe { alarm.soundName() }.map(|s| s.to_string());
    #[allow(deprecated)]
    let url = unsafe { alarm.url() }
        .as_ref()
        .and_then(|u| u.absoluteString())
        .map(|s| s.to_string());

    let alarm_type = match unsafe { alarm.r#type() } {
        EKAlarmType::Display => AlarmType::Display,
        EKAlarmType::Audio => AlarmType::Audio,
        EKAlarmType::Procedure => AlarmType::Procedure,
        EKAlarmType::Email => AlarmType::Email,
        _ => AlarmType::Unknown,
    };

    AlarmInfo {
        // relativeOffset of 0 means "at time of event" — it's always set
        relative_offset: Some(relative_offset),
        absolute_date,
        proximity,
        location,
        email_address,
        sound_name,
        url,
        alarm_type,
    }
}

// Helper to create an EKAlarm from an AlarmInfo. Returns Err if the
// caller-supplied `url` isn't a valid RFC 3986 URL.
fn create_ek_alarm(info: &AlarmInfo) -> Result<Retained<EKAlarm>> {
    let alarm = if let Some(date) = &info.absolute_date {
        let nsdate = datetime_to_nsdate(*date);
        unsafe { EKAlarm::alarmWithAbsoluteDate(&nsdate) }
    } else {
        let offset = info.relative_offset.unwrap_or(0.0);
        unsafe { EKAlarm::alarmWithRelativeOffset(offset) }
    };

    let prox = match info.proximity {
        AlarmProximity::Enter => EKAlarmProximity::Enter,
        AlarmProximity::Leave => EKAlarmProximity::Leave,
        AlarmProximity::None => EKAlarmProximity::None,
    };
    unsafe { alarm.setProximity(prox) };

    if let Some(loc) = &info.location {
        let structured = build_ek_structured_location(loc);
        unsafe { alarm.setStructuredLocation(Some(&structured)) };
    }

    // Apple infers EKAlarmType from which of these are set:
    //   soundName → Audio, url → Procedure, emailAddress → Email, else Display.
    if let Some(email) = &info.email_address {
        let ns = NSString::from_str(email);
        unsafe { alarm.setEmailAddress(Some(&ns)) };
    }
    if let Some(sound) = &info.sound_name {
        let ns = NSString::from_str(sound);
        unsafe { alarm.setSoundName(Some(&ns)) };
    }
    if let Some(u) = &info.url {
        let ns_str = NSString::from_str(u);
        let parsed =
            objc2_foundation::NSURL::URLWithString_encodingInvalidCharacters(&ns_str, false)
                .ok_or_else(|| EventKitError::InvalidURL(u.clone()))?;
        #[allow(deprecated)]
        unsafe {
            alarm.setUrl(Some(&parsed))
        };
    }

    Ok(alarm)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn event_span_default_is_this_and_maps_to_ek() {
        assert_eq!(EventSpan::default(), EventSpan::This);
        assert_eq!(EventSpan::This.to_ek(), EKSpan::ThisEvent);
        assert_eq!(EventSpan::Future.to_ek(), EKSpan::FutureEvents);
    }

    #[test]
    fn event_availability_round_trips_every_variant() {
        for v in [
            EventAvailability::NotSupported,
            EventAvailability::Busy,
            EventAvailability::Free,
            EventAvailability::Tentative,
            EventAvailability::Unavailable,
        ] {
            assert_eq!(EventAvailability::from_ek(v.to_ek()), v);
        }
    }

    #[test]
    fn event_status_from_ek_covers_each_variant() {
        assert_eq!(EventStatus::from_ek(EKEventStatus::None), EventStatus::None);
        assert_eq!(
            EventStatus::from_ek(EKEventStatus::Confirmed),
            EventStatus::Confirmed
        );
        assert_eq!(
            EventStatus::from_ek(EKEventStatus::Tentative),
            EventStatus::Tentative
        );
        assert_eq!(
            EventStatus::from_ek(EKEventStatus::Canceled),
            EventStatus::Canceled
        );
    }

    #[test]
    fn event_draft_default_has_empty_title_and_zero_dates() {
        // Documents that defaults aren't valid for actually creating —
        // callers must populate title/start/end. Just confirms the struct
        // builds with `..Default::default()` so the call sites can use it.
        let d: EventDraft<'_> = EventDraft::default();
        assert_eq!(d.title, "");
        assert!(d.start.is_none());
        assert!(d.end.is_none());
        assert!(!d.all_day);
        assert!(d.URL.is_none());
        assert!(d.availability.is_none());
    }

    #[test]
    fn event_patch_default_touches_nothing() {
        let p: EventPatch<'_> = EventPatch::default();
        assert!(p.title.is_none());
        assert!(p.notes.is_none());
        assert!(p.URL.is_none());
        assert!(p.availability.is_none());
        assert!(p.all_day.is_none());
        assert_eq!(p.span, EventSpan::This);
    }

    #[test]
    fn test_authorization_status_display() {
        assert_eq!(
            format!("{}", AuthorizationStatus::NotDetermined),
            "Not Determined"
        );
        assert_eq!(
            format!("{}", AuthorizationStatus::FullAccess),
            "Full Access"
        );
    }

    #[test]
    fn test_event_item_debug() {
        let event = EventItem {
            identifier: "test".to_string(),
            title: "Test Event".to_string(),
            notes: None,
            location: None,
            start_date: Local::now(),
            end_date: Local::now(),
            all_day: false,
            calendar_title: None,
            calendar_id: None,
            URL: None,
            availability: EventAvailability::Busy,
            status: EventStatus::None,
            is_detached: false,
            occurrence_date: None,
            structured_location: None,
            creation_date: None,
            last_modified_date: None,
            external_identifier: None,
            timezone: None,
            attachments_count: 0,
            attendees: Vec::new(),
            organizer: None,
        };
        assert!(format!("{:?}", event).contains("Test Event"));
    }
}