zotron 0.2.3

Typed CLI for Zotero — search, manage, export, OCR, and RAG over your academic library
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
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
//! Minimal typed CLI surface for the Rust migration scaffold.

use std::{
    env, fs,
    io::{self, Read},
    path::{Path, PathBuf},
    process::Command as ProcessCommand,
    thread,
    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};

use clap::{error::ErrorKind, Parser, Subcommand};
use serde_json::Value;
use zotron_rpc::{StdProviderCommandRunner, UreqProviderHttpTransport, ZoteroRpc};
use zotron_types::{
    bm25_score_chunks, build_embedding_provider_request, build_ocr_provider_request,
    builtin_ocr_provider_specs, cosine_similarity, execute_embedding_provider_request,
    is_zotron_evidence_artifact, machine_artifact_exists_for_item,
    machine_artifact_exists_in_sidecar, machine_artifact_store_root,
    ocr_provider_spec as raw_ocr_provider_spec, parse_embedding_provider_response,
    parse_ocr_provider_response, read_machine_artifact_sidecar, rrf_merge,
    write_machine_artifact_sidecar, ArtifactStorePlatform, EmbeddingChunkInput,
    EmbeddingRequestInput, EmbeddingVector, MachineArtifactKind, OcrRequestInput,
    ProviderCommandRunner, ProviderHttpInvocation, ProviderHttpTransport, StructureChunk,
    DEFAULT_RPC_URL,
};

pub trait RpcCaller {
    fn call(&mut self, method: &str, params: Option<Value>) -> Result<Value, String>;
}

#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub struct CliOcrProviderSpec {
    pub id: &'static str,
    pub provider: &'static str,
    pub request_style: &'static str,
    pub auth: &'static str,
    pub auth_header: &'static str,
    pub supports_pdf_direct: bool,
    pub key_field: &'static str,
}

#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub struct CliEmbeddingProviderSpec {
    pub id: &'static str,
    pub provider: &'static str,
    pub request_style: &'static str,
    pub default_url: String,
    pub default_model: &'static str,
    pub auth: &'static str,
    pub key_field: &'static str,
}

pub fn ocr_provider_specs() -> Vec<CliOcrProviderSpec> {
    builtin_ocr_provider_specs()
        .into_iter()
        .map(cli_ocr_provider_spec)
        .collect()
}

pub fn ocr_provider_spec(provider: &str) -> Result<CliOcrProviderSpec, String> {
    zotron_types::ocr_provider_spec(provider).map(cli_ocr_provider_spec)
}

pub fn embedding_provider_spec(provider: &str) -> Result<CliEmbeddingProviderSpec, String> {
    let spec = zotron_types::embedding_provider_spec(provider)?;
    Ok(CliEmbeddingProviderSpec {
        id: spec.id,
        provider: spec.provider_key,
        request_style: if spec.provider_key == "alibaba" {
            "dashscope"
        } else {
            spec.request_style.as_str()
        },
        default_url: spec.default_url.unwrap_or("").to_string(),
        default_model: spec.default_model,
        auth: spec.auth,
        key_field: spec.key_field,
    })
}

pub fn chunks_from_blocks(blocks: &[Value], max_chars: usize) -> Result<Vec<Value>, String> {
    let typed = blocks
        .iter()
        .map(json_block_to_pdf_block)
        .collect::<Result<Vec<_>, _>>()?;
    let chunks = zotron_types::chunks_from_blocks(&typed, max_chars);
    chunks
        .into_iter()
        .map(|chunk| chunk_to_cli_value(&chunk, &typed))
        .collect()
}

fn cli_ocr_provider_spec(spec: zotron_types::OcrProviderSpec) -> CliOcrProviderSpec {
    CliOcrProviderSpec {
        id: spec.provider_key,
        provider: spec.provider_key,
        request_style: spec.request_style.as_str(),
        auth: spec.auth,
        auth_header: spec.auth_header,
        supports_pdf_direct: spec.supports_pdf_direct,
        key_field: spec.key_field,
    }
}

fn json_block_to_pdf_block(value: &Value) -> Result<zotron_types::PdfEvidenceBlock, String> {
    let block_key = value
        .get("block_key")
        .and_then(Value::as_str)
        .ok_or_else(|| "block missing block_key".to_string())?
        .to_string();
    let item_key = value
        .get("item_key")
        .and_then(Value::as_str)
        .ok_or_else(|| "block missing item_key".to_string())?
        .to_string();
    let attachment_key = value
        .get("attachment_key")
        .and_then(Value::as_str)
        .ok_or_else(|| "block missing attachment_key".to_string())?
        .to_string();
    let page_idx = value
        .get("page_idx")
        .or_else(|| value.get("page"))
        .and_then(Value::as_u64)
        .unwrap_or(1);
    let block_type = value
        .get("type")
        .or_else(|| value.get("block_type"))
        .and_then(Value::as_str)
        .unwrap_or("paragraph")
        .to_string();
    let section_path = value
        .get("section_path")
        .and_then(Value::as_array)
        .map(|items| {
            items
                .iter()
                .filter_map(Value::as_str)
                .map(ToString::to_string)
                .collect::<Vec<_>>()
        })
        .unwrap_or_default();
    let text = value
        .get("text")
        .and_then(Value::as_str)
        .unwrap_or("")
        .to_string();
    let bbox = value.get("bbox").and_then(value_bbox4);

    Ok(zotron_types::PdfEvidenceBlock {
        block_key,
        item_key,
        attachment_key,
        page_idx,
        block_type,
        bbox,
        section_path,
        text,
    })
}

fn chunk_to_cli_value(
    chunk: &zotron_types::StructureChunk,
    blocks: &[zotron_types::PdfEvidenceBlock],
) -> Result<Value, String> {
    let refs = chunk
        .block_keys
        .iter()
        .filter_map(|key| blocks.iter().find(|block| &block.block_key == key))
        .map(|block| {
            serde_json::json!({
                "block_key": block.block_key,
                "page_idx": block.page_idx,
                "bbox": block.bbox.map(|bbox| bbox.iter().map(|n| {
                    if n.fract() == 0.0 {
                        Value::from(*n as i64)
                    } else {
                        Value::from(*n)
                    }
                }).collect::<Vec<_>>()),
            })
        })
        .collect::<Vec<_>>();
    Ok(serde_json::json!({
        "chunk_key": chunk.chunk_key,
        "item_key": chunk.item_key,
        "attachment_key": chunk.attachment_key,
        "block_keys": chunk.block_keys,
        "section_path": chunk.section_path,
        "text": chunk.text,
        "page_start": chunk.page_start,
        "page_end": chunk.page_end,
        "evidence_refs": refs,
    }))
}

fn value_bbox4(value: &Value) -> Option<[f64; 4]> {
    let arr = value.as_array()?;
    if arr.len() != 4 {
        return None;
    }
    Some([
        arr[0].as_f64()?,
        arr[1].as_f64()?,
        arr[2].as_f64()?,
        arr[3].as_f64()?,
    ])
}

impl RpcCaller for ZoteroRpc {
    fn call(&mut self, method: &str, params: Option<Value>) -> Result<Value, String> {
        self.call(method, params).map_err(|err| err.to_string())
    }
}

#[derive(Debug, Parser)]
#[command(name = "zotron", about = "Rust client + CLI for the Zotron XPI")]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

#[derive(Debug, Subcommand)]
enum OcrCommand {
    /// Print supported OCR provider contracts.
    Providers,
    /// Execute an OCR provider request from JSON and emit normalized blocks.
    #[command(name = "run")]
    Run {
        #[arg(long)]
        provider: String,
        /// Path to an OcrRequestInput JSON file, or "-" to read stdin.
        #[arg(long)]
        input: Option<String>,
        /// Local PDF/image file to encode into an OcrRequestInput.
        #[arg(long)]
        file: Option<String>,
        /// Zotero item key used when --file builds the OCR request.
        #[arg(long = "item-key")]
        item_key: Option<String>,
        /// Zotero attachment key used when --file builds the OCR request.
        #[arg(long = "attachment-key")]
        attachment_key: Option<String>,
        /// MIME type used when --file builds the OCR request.
        #[arg(long = "mime-type")]
        mime_type: Option<String>,
        /// Override the provider endpoint, required for service-hosted PaddleOCR-VL.
        #[arg(long)]
        endpoint: Option<String>,
        /// Environment variable containing the provider bearer token.
        #[arg(long = "api-key-env")]
        api_key_env: Option<String>,
    },
    /// Show OCR statistics for a collection.
    Status {
        #[arg(long)]
        collection: String,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// Parse a Zotero PDF through MinerU and write hidden sidecar OCR/RAG artifacts.
    #[command(name = "process")]
    Process {
        #[arg(long, default_value = "mineru")]
        provider: String,
        /// Parent Zotero item key.
        #[arg(long)]
        parent: String,
        /// Zotero PDF attachment key (auto-resolved from --parent when omitted).
        #[arg(long)]
        attachment: Option<String>,
        /// Public URL for MinerU cloud parsing. Use --result-dir/--result-zip for offline ingestion.
        #[arg(long = "source-url")]
        source_url: Option<String>,
        /// Already-extracted MinerU result directory, used by tests/offline replay.
        #[arg(long = "result-dir")]
        result_dir: Option<String>,
        /// Already-downloaded MinerU result zip, used by tests/offline replay.
        #[arg(long = "result-zip")]
        result_zip: Option<String>,
        /// Override MinerU submit endpoint.
        #[arg(long = "provider-endpoint")]
        provider_endpoint: Option<String>,
        /// Environment variable containing the MinerU bearer token.
        #[arg(long = "api-key-env", default_value = "ZOTRON_MINERU_API_KEY")]
        api_key_env: String,
        #[arg(long = "poll-interval-seconds", default_value_t = 5)]
        poll_interval_seconds: u64,
        #[arg(long = "timeout-seconds", default_value_t = 900)]
        timeout_seconds: u64,
        #[arg(long = "chunk-chars", default_value_t = 1200)]
        chunk_chars: usize,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
}

#[derive(Debug, Subcommand)]
enum Command {
    /// Check that Zotero is running with the Zotron XPI enabled.
    Ping {
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// Generic RPC escape hatch.
    Rpc {
        method: String,
        #[arg(default_value = "{}")]
        params_json: String,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
        #[arg(long)]
        paginate: bool,
        #[arg(long, default_value_t = 100)]
        page_size: usize,
    },
    /// Push prepared Zotero JSON (from file or stdin) to Zotero.
    Push {
        /// Path to a JSON file, or "-" to read from stdin.
        json_file: String,
        /// Optional PDF attachment path.
        #[arg(long)]
        pdf: Option<String>,
        /// Collection name (fuzzy) or key.
        #[arg(long)]
        collection: Option<String>,
        /// Duplicate handling: skip | update | create.
        #[arg(long = "on-duplicate", default_value = "skip")]
        on_duplicate: String,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
        /// Parse input + resolve collection only; do not push to Zotero.
        #[arg(long = "dry-run")]
        dry_run: bool,
    },
    /// System and plugin introspection commands.
    System {
        #[command(subcommand)]
        command: SystemCommand,
    },
    /// Search items by text, tag, identifier, or structured conditions.
    Search(SearchArgs),
    /// Inspect and manage Zotero items.
    Items {
        #[command(subcommand)]
        command: ItemsCommand,
    },
    /// Inspect Zotero collections.
    Collections {
        #[command(subcommand)]
        command: CollectionsCommand,
    },
    /// Inspect Zotero notes.
    Notes {
        #[command(subcommand)]
        command: NotesCommand,
    },
    /// Inspect Zotero preferences.
    Settings {
        #[command(subcommand)]
        command: SettingsCommand,
    },
    /// Inspect and manage Zotero tags.
    Tags {
        #[command(subcommand)]
        command: TagsCommand,
    },
    /// Export items as BibTeX, RIS, CSL-JSON, or formatted bibliography.
    Export(ExportArgs),
    /// List, create, and delete PDF annotations.
    Annotations {
        #[command(subcommand)]
        command: AnnotationsCommand,
    },
    /// OCR PDFs and manage raw/block/chunk evidence artifacts.
    Ocr {
        #[command(subcommand)]
        command: OcrCommand,
    },
    /// Build and search retrieval artifacts.
    Rag {
        #[command(subcommand)]
        command: RagCommand,
    },
}

struct RagSearchOptions {
    query: String,
    collection: Option<String>,
    keys: Vec<String>,
    zotero: bool,
    top_spans_per_item: u64,
    include_fulltext_spans: bool,
    top_k: u64,
    output: String,
}

#[derive(Debug, Subcommand)]
enum RagCommand {
    /// Print supported embedding provider contracts.
    #[command(name = "providers")]
    Providers,
    /// Execute an embedding provider request from JSON and emit vectors.
    #[command(name = "embed")]
    Embed {
        #[arg(long)]
        provider: String,
        /// Path to an EmbeddingRequestInput JSON file, or "-" to read stdin.
        #[arg(long)]
        input: String,
        /// Override the embedding endpoint.
        #[arg(long)]
        endpoint: Option<String>,
        /// Override the embedding model.
        #[arg(long)]
        model: Option<String>,
        /// Override provider input type, for example document or query.
        #[arg(long = "input-type")]
        input_type: Option<String>,
        /// Environment variable containing the provider bearer token.
        #[arg(long = "api-key-env")]
        api_key_env: Option<String>,
    },
    /// Show index status for a collection.
    Status {
        #[arg(long)]
        collection: String,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// Emit academic-zh retrieval hits with item_key/title/text provenance.
    #[command(name = "search")]
    Search {
        query: String,
        #[arg(long)]
        collection: Option<String>,
        /// Limit retrieval to one or more Zotero item keys.
        #[arg(long = "key", alias = "keys")]
        keys: Vec<String>,
        #[arg(long)]
        zotero: bool,
        #[arg(long = "top-spans-per-item", default_value_t = 3)]
        top_spans_per_item: u64,
        #[arg(long = "include-fulltext-spans")]
        include_fulltext_spans: bool,
        #[arg(long = "limit", alias = "top-k", default_value_t = 50)]
        top_k: u64,
        #[arg(long, default_value = "json", value_parser = ["json", "jsonl"])]
        output: String,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
}

#[derive(Debug, Subcommand)]
enum SystemCommand {
    /// Show XPI version and exposed method metadata.
    Version {
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// List all libraries (user + groups).
    Libraries {
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// Get statistics for the current (or specified) library.
    #[command(name = "library-stats")]
    LibraryStats {
        #[arg(long)]
        library: Option<i64>,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// Show item type schema. Without --type, lists all types. With --type, shows fields and creator types.
    Schema {
        #[arg(long = "type")]
        item_type: Option<String>,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// Get the currently selected Zotero collection (or null).
    #[command(name = "current-collection")]
    CurrentCollection {
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// List RPC methods, or describe a specific method.
    Methods {
        /// Method name to describe. Omit to list all methods.
        method: Option<String>,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
}

#[derive(Debug, clap::Args)]
struct SearchArgs {
    /// Search query (title/creator/year by default; PDF content with --fulltext).
    query: Option<String>,
    /// Search inside PDF full-text content instead of metadata.
    #[arg(long)]
    fulltext: bool,
    /// Filter by author/creator name (contains match).
    #[arg(long)]
    author: Option<String>,
    /// Filter by date after (YYYY or YYYY-MM-DD).
    #[arg(long)]
    after: Option<String>,
    /// Filter by date before (YYYY or YYYY-MM-DD).
    #[arg(long)]
    before: Option<String>,
    /// Filter by journal/publication title (contains match).
    #[arg(long)]
    journal: Option<String>,
    /// Filter by tag (exact match).
    #[arg(long)]
    tag: Option<String>,
    /// Find by DOI.
    #[arg(long)]
    doi: Option<String>,
    /// Find by ISBN.
    #[arg(long)]
    isbn: Option<String>,
    /// Find by ISSN.
    #[arg(long)]
    issn: Option<String>,
    /// Limit results to a collection name or key.
    #[arg(long)]
    collection: Option<String>,
    #[arg(long, default_value_t = 50)]
    limit: u64,
    #[arg(long, default_value_t = 0)]
    offset: u64,
    #[arg(long, default_value = DEFAULT_RPC_URL)]
    url: String,
    #[command(subcommand)]
    management: Option<SearchManagementCommand>,
}

#[derive(Debug, Subcommand)]
enum SearchManagementCommand {
    /// List all saved searches in the library.
    #[command(name = "saved-searches")]
    SavedSearches {
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// Create a saved search with one or more conditions.
    #[command(name = "create-saved")]
    CreateSaved {
        name: String,
        #[arg(long = "condition", required = true)]
        condition: Vec<String>,
        #[arg(long)]
        dry_run: bool,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// Delete a saved search by key.
    #[command(name = "delete-saved")]
    DeleteSaved {
        search_key: String,
        #[arg(long)]
        dry_run: bool,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
}

#[derive(Debug, Subcommand)]
enum ItemsCommand {
    /// Add an item by DOI, ISBN, URL, local file, or manual entry (--type + --field).
    Add {
        #[arg(long)]
        doi: Option<String>,
        #[arg(long)]
        isbn: Option<String>,
        /// Web page URL to add from.
        #[arg(long = "from-url")]
        from_url: Option<String>,
        /// Local file path to add from.
        #[arg(long)]
        file: Option<String>,
        /// Item type for manual creation (e.g. journalArticle).
        #[arg(long = "type")]
        item_type: Option<String>,
        /// Field values for manual creation (e.g. title="My Paper").
        #[arg(long = "field")]
        fields: Vec<String>,
        #[arg(long)]
        collection: Option<String>,
        #[arg(long)]
        dry_run: bool,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// Update fields on an existing item.
    Update {
        key: String,
        #[arg(long = "field")]
        fields: Vec<String>,
        #[arg(long)]
        dry_run: bool,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// Permanently delete an item.
    Delete {
        key: String,
        #[arg(long)]
        dry_run: bool,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// Move one or more items to trash.
    Trash {
        items: Vec<String>,
        #[arg(long)]
        dry_run: bool,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// Restore a trashed item.
    Restore {
        item: String,
        #[arg(long)]
        dry_run: bool,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// Merge a group of duplicate items.
    #[command(name = "merge-duplicates")]
    MergeDuplicates {
        keys: Vec<String>,
        #[arg(long)]
        dry_run: bool,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// Add a related-item link between two items.
    #[command(name = "add-related")]
    AddRelated {
        key: String,
        #[arg(long)]
        target: String,
        #[arg(long)]
        dry_run: bool,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// Remove a related-item link between two items.
    #[command(name = "remove-related")]
    RemoveRelated {
        key: String,
        #[arg(long)]
        target: String,
        #[arg(long)]
        dry_run: bool,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// Print the full serialization of an item by key.
    Get {
        item: String,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// List items in the library with optional sorting and pagination.
    List {
        #[arg(long, default_value_t = 50)]
        limit: u64,
        #[arg(long, default_value_t = 0)]
        offset: u64,
        #[arg(long)]
        sort: Option<String>,
        #[arg(long, default_value = "asc")]
        direction: String,
        /// List trashed items instead of regular items.
        #[arg(long)]
        trash: bool,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// Run Zotero's duplicate scan and print groups.
    #[command(name = "find-duplicates")]
    FindDuplicates {
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// List recently added or modified items.
    Recent {
        #[arg(long, default_value_t = 20)]
        limit: u64,
        #[arg(long, default_value_t = 0)]
        offset: u64,
        #[arg(long = "type", default_value = "added")]
        recent_type: String,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// Retrieve the full-text content of an item's attachment.
    Fulltext {
        key: String,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// List items related to the given item.
    Related {
        key: String,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// Get the citation key for an item.
    #[command(name = "citation-key")]
    CitationKey {
        key: String,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// Get the local filesystem path of an item's PDF attachment.
    Path {
        key: String,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// List attachments belonging to an item.
    Attachments {
        key: String,
        #[arg(long, default_value_t = 0)]
        offset: u64,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// Batch find missing PDFs in a collection via Zotero's resolver chain.
    #[command(name = "find-pdfs")]
    FindPdfs {
        #[arg(long)]
        collection: String,
        #[arg(long, default_value_t = 0)]
        limit: usize,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
}

#[derive(Debug, Subcommand)]
enum SettingsCommand {
    /// Get a single Zotero preference value.
    Get {
        key: String,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// List all Zotero preferences as a key->value dict.
    #[command(visible_alias = "get-all")]
    List {
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// Set one or more Zotero preferences (key value pairs), or bulk-set from a JSON file.
    Set {
        /// key value key value ... (pairs of positional args)
        pairs: Vec<String>,
        /// Bulk-set from a JSON file.
        #[arg(long)]
        file: Option<String>,
        #[arg(long)]
        dry_run: bool,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
}

#[derive(Debug, Subcommand)]
enum TagsCommand {
    /// List all tags in the library (flat).
    List {
        #[arg(long, default_value_t = 200)]
        limit: u64,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// Rename a tag across all items.
    Rename {
        old: String,
        new: String,
        #[arg(long)]
        dry_run: bool,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// Delete a tag library-wide.
    Delete {
        tag: String,
        #[arg(long)]
        dry_run: bool,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// Add tags to one or more items.
    Add {
        keys: Vec<String>,
        #[arg(long = "tag", required = true)]
        tags: Vec<String>,
        #[arg(long)]
        dry_run: bool,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// Remove tags from one or more items.
    Remove {
        keys: Vec<String>,
        #[arg(long = "tag", required = true)]
        tags: Vec<String>,
        #[arg(long)]
        dry_run: bool,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
}

#[derive(Debug, clap::Args)]
struct ExportArgs {
    /// Item keys to export.
    keys: Vec<String>,
    /// Output format: bibtex, ris, csl-json, bibliography.
    #[arg(long, default_value = "bibtex")]
    format: String,
    /// Export all items from this collection (name or key).
    #[arg(long)]
    collection: Option<String>,
    /// Citation style URL (only for bibliography format).
    #[arg(long, default_value = "http://www.zotero.org/styles/apa")]
    style: String,
    /// Output HTML instead of plain text (only for bibliography format).
    #[arg(long)]
    html: bool,
    #[arg(long, default_value = DEFAULT_RPC_URL)]
    url: String,
}

#[derive(Debug, Subcommand)]
enum AnnotationsCommand {
    /// List annotations on a PDF. Accepts an item key (auto-resolves to PDF) or attachment key.
    List {
        /// Item key or attachment key
        parent: String,
        /// Use a specific attachment when the item has multiple PDFs
        #[arg(long)]
        attachment: Option<String>,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// Create a new annotation on a PDF. Accepts an item key (auto-resolves to PDF) or attachment key.
    Create {
        /// Item key or attachment key
        parent: String,
        /// Use a specific attachment when the item has multiple PDFs
        #[arg(long)]
        attachment: Option<String>,
        #[arg(long = "type")]
        annotation_type: Option<String>,
        /// JSON annotation position, for example '{"pageIndex":0,"rects":[[10,20,30,40]]}'.
        /// Not required when --quote is given.
        #[arg(long)]
        position: Option<String>,
        /// Text to locate in the PDF and highlight. Resolves to rects automatically.
        /// Locates text headlessly (no PDF viewer required).
        /// Use with --dry-run for locate-only mode.
        #[arg(long)]
        quote: Option<String>,
        /// Restrict quote search to a specific page (0-indexed).
        #[arg(long)]
        page: Option<u32>,
        /// Zotero annotation sort index.
        #[arg(long = "sort-index")]
        sort_index: Option<String>,
        #[arg(long)]
        text: Option<String>,
        #[arg(long)]
        comment: Option<String>,
        #[arg(long, default_value = "#ffd400")]
        color: String,
        #[arg(long)]
        dry_run: bool,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// Delete an annotation by key.
    Delete {
        annotation_key: String,
        #[arg(long)]
        dry_run: bool,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
}

#[derive(Debug, Subcommand)]
enum NotesCommand {
    /// List notes attached to a parent item.
    List {
        #[arg(long)]
        parent: String,
        #[arg(long, default_value_t = 50)]
        limit: u64,
        #[arg(long, default_value_t = 0)]
        offset: u64,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// Get a single note by key.
    Get {
        note_key: String,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// Create a note attached to a parent item.
    Create {
        #[arg(long)]
        parent: String,
        #[arg(long)]
        content: String,
        #[arg(long = "tag")]
        tags: Vec<String>,
        #[arg(long)]
        dry_run: bool,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// Update the content of an existing note.
    Update {
        note_key: String,
        #[arg(long)]
        content: String,
        #[arg(long)]
        dry_run: bool,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// Delete a note by key.
    Delete {
        note_key: String,
        #[arg(long)]
        dry_run: bool,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// Search notes by text content.
    Search {
        query: String,
        #[arg(long, default_value_t = 50)]
        limit: u64,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
}

#[derive(Debug, Subcommand)]
enum CollectionsCommand {
    /// List all collections in the user library (flat).
    List {
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// Print the collection hierarchy as a tree.
    Tree {
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// Get a single collection's metadata.
    Get {
        name_or_id: String,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// List all items in a collection.
    #[command(name = "get-items", visible_alias = "items")]
    GetItems {
        name_or_id: String,
        #[arg(long)]
        limit: Option<u64>,
        #[arg(long, default_value_t = 0)]
        offset: u64,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// Show item/attachment/note/subcollection counts for a collection.
    Stats {
        name_or_id: String,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
    },
    /// Rename a collection.
    Rename {
        old_name: String,
        new_name: String,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
        #[arg(long)]
        dry_run: bool,
    },
    /// Create a collection, optionally nested under a parent.
    Create {
        name: String,
        #[arg(long)]
        parent: Option<String>,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
        #[arg(long)]
        dry_run: bool,
    },
    /// Delete a collection.
    Delete {
        name_or_id: String,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
        #[arg(long)]
        dry_run: bool,
    },
    /// Add existing items to a collection.
    #[command(name = "add-items")]
    AddItems {
        collection: String,
        item_keys: Vec<String>,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
        #[arg(long)]
        dry_run: bool,
    },
    /// Remove items from a collection.
    #[command(name = "remove-items")]
    RemoveItems {
        collection: String,
        item_keys: Vec<String>,
        #[arg(long, default_value = DEFAULT_RPC_URL)]
        url: String,
        #[arg(long)]
        dry_run: bool,
    },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum JsonStyle {
    /// Matches Python's top-level `ping` command (`json.dumps` defaults).
    PythonCompact,
    /// Matches namespace commands that route through Python `emit(..., indent=2)`.
    Pretty,
}

enum ParseOutcome<T> {
    Command(T),
    Display(String),
}

fn parse_cli<T>(
    args: impl IntoIterator<Item = impl Into<std::ffi::OsString> + Clone>,
) -> Result<ParseOutcome<T>, String>
where
    T: Parser,
{
    match T::try_parse_from(args) {
        Ok(cli) => Ok(ParseOutcome::Command(cli)),
        Err(err)
            if matches!(
                err.kind(),
                ErrorKind::DisplayHelp | ErrorKind::DisplayVersion
            ) =>
        {
            Ok(ParseOutcome::Display(err.to_string()))
        }
        Err(err) => Err(err.to_string()),
    }
}

pub fn format_error_json(message: &str) -> String {
    let message = message.trim_end();
    let (code, message) = split_error_code(message).unwrap_or(("RUNTIME_ERROR", message));
    serde_json::json!({"error": {"code": code, "message": message}}).to_string()
}

fn split_error_code(message: &str) -> Option<(&str, &str)> {
    let (code, rest) = message.split_once(':')?;
    if !code.is_empty()
        && code
            .chars()
            .all(|ch| ch.is_ascii_uppercase() || ch.is_ascii_digit() || ch == '_')
    {
        Some((code, rest.trim_start()))
    } else {
        None
    }
}

pub fn run(
    args: impl IntoIterator<Item = impl Into<std::ffi::OsString> + Clone>,
) -> Result<String, String> {
    // Emit plugin hint for Claude Code discovery
    if std::env::var("CLAUDECODE").as_deref() == Ok("1") {
        eprintln!(r#"<claude-code-hint v="1" type="plugin" value="zotron@dianzuan/zotron" />"#);
    }

    let cli = match parse_cli::<Cli>(args)? {
        ParseOutcome::Command(cli) => cli,
        ParseOutcome::Display(output) => return Ok(output),
    };
    let url = command_url(&cli.command);
    let mut client = ZoteroRpc::new(url);
    run_command(cli.command, &mut client)
}

pub fn run_with_client(
    args: impl IntoIterator<Item = impl Into<std::ffi::OsString> + Clone>,
    client: &mut impl RpcCaller,
) -> Result<String, String> {
    let cli = match parse_cli::<Cli>(args)? {
        ParseOutcome::Command(cli) => cli,
        ParseOutcome::Display(output) => return Ok(output),
    };
    run_command(cli.command, client)
}

fn rag_command_url(command: &RagCommand) -> String {
    match command {
        RagCommand::Providers => DEFAULT_RPC_URL.to_string(),
        RagCommand::Embed { .. } => DEFAULT_RPC_URL.to_string(),
        RagCommand::Status { url, .. } => url.clone(),
        RagCommand::Search { url, .. } => url.clone(),
    }
}

fn command_url(command: &Command) -> String {
    match command {
        Command::Ping { url }
        | Command::Rpc { url, .. }
        | Command::Push { url, .. }
        => url.clone(),
        Command::Ocr { command } => match command {
            OcrCommand::Providers => DEFAULT_RPC_URL.to_string(),
            OcrCommand::Run { .. } => DEFAULT_RPC_URL.to_string(),
            OcrCommand::Status { url, .. } => url.clone(),
            OcrCommand::Process { url, .. } => url.clone(),
        },
        Command::Rag { command } => rag_command_url(command),
        Command::System { command } => match command {
            SystemCommand::Version { url }
            | SystemCommand::Libraries { url }
            | SystemCommand::LibraryStats { url, .. }
            | SystemCommand::Schema { url, .. }
            | SystemCommand::CurrentCollection { url }
            | SystemCommand::Methods { url, .. } => url.clone(),
        },
        Command::Search(ref args) => match &args.management {
            Some(SearchManagementCommand::SavedSearches { url })
            | Some(SearchManagementCommand::CreateSaved { url, .. })
            | Some(SearchManagementCommand::DeleteSaved { url, .. }) => url.clone(),
            None => args.url.clone(),
        },
        Command::Items { command } => match command {
            ItemsCommand::Add { url, .. }
            | ItemsCommand::Update { url, .. }
            | ItemsCommand::Delete { url, .. }
            | ItemsCommand::Trash { url, .. }
            | ItemsCommand::Restore { url, .. }
            | ItemsCommand::MergeDuplicates { url, .. }
            | ItemsCommand::AddRelated { url, .. }
            | ItemsCommand::RemoveRelated { url, .. }
            | ItemsCommand::Get { url, .. }
            | ItemsCommand::List { url, .. }
            | ItemsCommand::FindDuplicates { url }
            | ItemsCommand::Recent { url, .. }
            | ItemsCommand::Fulltext { url, .. }
            | ItemsCommand::Related { url, .. }
            | ItemsCommand::CitationKey { url, .. }
            | ItemsCommand::Path { url, .. }
            | ItemsCommand::Attachments { url, .. }
            | ItemsCommand::FindPdfs { url, .. } => url.clone(),
        },
        Command::Collections { command } => match command {
            CollectionsCommand::List { url }
            | CollectionsCommand::Tree { url }
            | CollectionsCommand::Get { url, .. }
            | CollectionsCommand::GetItems { url, .. }
            | CollectionsCommand::Stats { url, .. }
            | CollectionsCommand::Rename { url, .. }
            | CollectionsCommand::Create { url, .. }
            | CollectionsCommand::Delete { url, .. }
            | CollectionsCommand::AddItems { url, .. }
            | CollectionsCommand::RemoveItems { url, .. } => url.clone(),
        },
        Command::Notes { command } => match command {
            NotesCommand::List { url, .. }
            | NotesCommand::Get { url, .. }
            | NotesCommand::Create { url, .. }
            | NotesCommand::Update { url, .. }
            | NotesCommand::Delete { url, .. }
            | NotesCommand::Search { url, .. } => url.clone(),
        },
        Command::Settings { command } => match command {
            SettingsCommand::Get { url, .. }
            | SettingsCommand::List { url }
            | SettingsCommand::Set { url, .. } => url.clone(),
        },
        Command::Tags { command } => match command {
            TagsCommand::List { url, .. }
            | TagsCommand::Rename { url, .. }
            | TagsCommand::Delete { url, .. }
            | TagsCommand::Add { url, .. }
            | TagsCommand::Remove { url, .. } => url.clone(),
        },
        Command::Export(ref args) => args.url.clone(),
        Command::Annotations { command } => match command {
            AnnotationsCommand::List { url, .. }
            | AnnotationsCommand::Create { url, .. }
            | AnnotationsCommand::Delete { url, .. } => url.clone(),
        },
    }
}

fn run_ocr_command(command: OcrCommand, client: &mut impl RpcCaller) -> Result<String, String> {
    if let OcrCommand::Providers = &command {
        return format_json(
            &serde_json::json!({ "providers": ocr_provider_specs() }),
            JsonStyle::Pretty,
        );
    }
    let value = match command {
        OcrCommand::Providers => unreachable!(),
        OcrCommand::Run {
            provider,
            input,
            file,
            item_key,
            attachment_key,
            mime_type,
            endpoint,
            api_key_env,
        } => run_ocr_run_command(OcrRunOptions {
            provider,
            input,
            file,
            item_key,
            attachment_key,
            mime_type,
            endpoint,
            api_key_env,
        })?,
        OcrCommand::Status { collection, .. } => run_ocr_status_command(client, collection)?,
        OcrCommand::Process {
            provider,
            parent,
            attachment,
            source_url,
            result_dir,
            result_zip,
            provider_endpoint,
            api_key_env,
            poll_interval_seconds,
            timeout_seconds,
            chunk_chars,
            ..
        } => run_ocr_process_command(
            client,
            OcrProcessOptions {
                provider,
                parent,
                attachment,
                source_url,
                result_dir,
                result_zip,
                provider_endpoint,
                api_key_env,
                poll_interval_seconds,
                timeout_seconds,
                chunk_chars,
            },
        )?,
    };
    format_json(&value, JsonStyle::PythonCompact)
}

struct OcrProcessOptions {
    provider: String,
    parent: String,
    attachment: Option<String>,
    source_url: Option<String>,
    result_dir: Option<String>,
    result_zip: Option<String>,
    provider_endpoint: Option<String>,
    api_key_env: String,
    poll_interval_seconds: u64,
    timeout_seconds: u64,
    chunk_chars: usize,
}

struct OcrRunOptions {
    provider: String,
    input: Option<String>,
    file: Option<String>,
    item_key: Option<String>,
    attachment_key: Option<String>,
    mime_type: Option<String>,
    endpoint: Option<String>,
    api_key_env: Option<String>,
}

fn run_ocr_run_command(options: OcrRunOptions) -> Result<Value, String> {
    let input: OcrRequestInput = match (options.input, options.file) {
        (Some(input), None) => read_json_input(&input)?,
        (None, Some(file)) => ocr_input_from_file(
            file,
            options.item_key,
            options.attachment_key,
            options.mime_type,
        )?,
        (Some(_), Some(_)) => {
            return Err("INVALID_ARGS: use either --input or --file, not both".to_string())
        }
        (None, None) => return Err("INVALID_ARGS: provide --input JSON or --file".to_string()),
    };
    let request = build_ocr_provider_request(&options.provider, &input)?;
    let payload = if request.command.is_empty() {
        let method = request
            .method
            .ok_or_else(|| format!("OCR provider {} missing HTTP method", request.provider))?;
        let auth_scheme = raw_ocr_provider_spec(&options.provider)?.auth;
        let mut transport =
            provider_http_transport_with_auth(options.api_key_env.as_deref(), auth_scheme)?;
        transport.post_json(&ProviderHttpInvocation {
            provider: request.provider.to_string(),
            style: request.style.to_string(),
            method: method.to_string(),
            url: options
                .endpoint
                .or_else(|| request.url.map(ToString::to_string)),
            auth_header_name: request.auth_header.map(ToString::to_string),
            auth_header_value: None,
            body: request.body,
        })?
    } else {
        let mut command_runner = StdProviderCommandRunner;
        command_runner.run_json(&request.command)?
    };
    let blocks = match parse_ocr_provider_response(
        request.provider,
        &payload,
        &input.item_key,
        &input.attachment_key,
    ) {
        Ok(blocks) => blocks,
        Err(err) => {
            if let Some(task) = ocr_async_task_result(request.provider, &payload) {
                return Ok(task);
            }
            return Err(err);
        }
    };

    Ok(serde_json::json!({
        "provider": request.provider,
        "blocks": blocks,
    }))
}

fn run_ocr_process_command(
    client: &mut impl RpcCaller,
    mut options: OcrProcessOptions,
) -> Result<Value, String> {
    let spec = raw_ocr_provider_spec(&options.provider)?;

    let attachment = match options.attachment.take() {
        Some(key) => key,
        None => resolve_first_pdf_attachment_key(client, &options.parent)?,
    };
    options.attachment = Some(attachment.clone());

    let attachment_path = resolve_attachment_path(client, &attachment)?;
    let storage_dir = attachment_path
        .parent()
        .ok_or_else(|| {
            format!(
                "ATTACHMENT_PATH_INVALID: attachment path has no parent directory: {}",
                attachment_path.display()
            )
        })?
        .to_path_buf();

    match spec.provider_key {
        "mineru" | "mineru-cli" => {
            if options.result_dir.is_some() && options.result_zip.is_some() {
                return Err("INVALID_ARGS: use either --result-dir or --result-zip, not both".to_string());
            }
            if options.source_url.is_some()
                && (options.result_dir.is_some() || options.result_zip.is_some())
            {
                return Err(
                    "INVALID_ARGS: --source-url cannot be combined with --result-dir/--result-zip"
                        .to_string(),
                );
            }
            let file_name = attachment_path
                .file_name()
                .and_then(|name| name.to_str())
                .unwrap_or("document.pdf")
                .to_string();
            let source = load_mineru_result_source(&options, &attachment_path, &file_name)?;
            let artifacts = persist_mineru_result_sidecars(
                &storage_dir, &options.parent, &attachment,
                &options.provider, &source, options.chunk_chars,
            )?;
            Ok(serde_json::json!({
                "provider": spec.provider_key,
                "status": "indexed",
                "item_key": options.parent,
                "attachment_key": attachment,
                "attachment_path": attachment_path,
                "storage_dir": storage_dir,
                "task_id": source.task_id,
                "state": source.state,
                "blocks": artifacts.block_count,
                "chunks": artifacts.chunk_count,
                "artifacts": artifacts.artifacts,
            }))
        }
        _ => {
            run_ocr_process_sync(
                client, &options, spec.provider_key,
                &attachment, &attachment_path, &storage_dir,
            )
        }
    }
}

fn run_ocr_process_sync(
    client: &mut impl RpcCaller,
    options: &OcrProcessOptions,
    provider: &str,
    attachment_key: &str,
    attachment_path: &Path,
    storage_dir: &Path,
) -> Result<Value, String> {
    let api_url = if let Some(endpoint) = &options.provider_endpoint {
        endpoint.clone()
    } else {
        let settings = client.call("settings.getAll", None)?;
        settings.get("ocr.apiUrl")
            .and_then(Value::as_str)
            .unwrap_or("")
            .to_string()
    };
    if api_url.is_empty() {
        return Err(format!("MISSING_CONFIG: ocr.apiUrl not configured for provider {provider}"));
    }

    let api_key = {
        let from_env = if !options.api_key_env.is_empty() {
            env::var(&options.api_key_env).ok().filter(|v| !v.is_empty())
        } else {
            None
        };
        from_env.unwrap_or_else(|| {
            client.call("settings.getRaw", Some(serde_json::json!({"key": "ocr.apiKey"})))
                .ok()
                .and_then(|raw| raw.get("ocr.apiKey").and_then(Value::as_str).map(String::from))
                .unwrap_or_default()
        })
    };

    let pdf_bytes = fs::read(attachment_path)
        .map_err(|e| format!("READ_PDF_FAILED: {}: {e}", attachment_path.display()))?;

    const MAX_PDF_SIZE: usize = 100 * 1024 * 1024; // 100 MB
    if pdf_bytes.len() > MAX_PDF_SIZE {
        return Err(format!(
            "PDF_TOO_LARGE: {} is {} MB, max {} MB",
            attachment_path.display(),
            pdf_bytes.len() / (1024 * 1024),
            MAX_PDF_SIZE / (1024 * 1024),
        ));
    }

    let base64_pdf = format!("data:application/pdf;base64,{}", base64_encode(&pdf_bytes));

    let input = OcrRequestInput {
        content_base64: base64_pdf,
        file_name: attachment_path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("document.pdf")
            .to_string(),
        mime_type: "application/pdf".to_string(),
        item_key: options.parent.clone(),
        attachment_key: attachment_key.to_string(),
        source_url: None,
        local_path: Some(attachment_path.to_string_lossy().to_string()),
        output_dir: None,
    };
    let request = build_ocr_provider_request(provider, &input)?;

    let payload = if request.command.is_empty() {
        let method = request
            .method
            .ok_or_else(|| format!("OCR provider {provider} missing HTTP method"))?;
        let spec = raw_ocr_provider_spec(provider)?;

        let mut transport = if !api_key.is_empty() {
            match spec.auth {
                "bearer" => UreqProviderHttpTransport::with_bearer_token(&api_key),
                "token" => UreqProviderHttpTransport::with_api_key(format!("token {api_key}")),
                _ => UreqProviderHttpTransport::new(),
            }
        } else {
            UreqProviderHttpTransport::new()
        };

        transport.post_json(&ProviderHttpInvocation {
            provider: request.provider.to_string(),
            style: request.style.to_string(),
            method: method.to_string(),
            url: Some(api_url),
            auth_header_name: request.auth_header.map(ToString::to_string),
            auth_header_value: None,
            body: request.body,
        })?
    } else {
        let mut runner = StdProviderCommandRunner;
        runner.run_json(&request.command)?
    };

    let blocks = parse_ocr_provider_response(provider, &payload, &options.parent, attachment_key)?;
    let chunks = zotron_types::chunks_from_blocks(&blocks, options.chunk_chars);

    let artifacts = vec![
        write_sidecar_json(
            storage_dir, &options.parent, attachment_key,
            MachineArtifactKind::OcrRaw, &payload,
        )?,
        write_sidecar_jsonl(
            storage_dir, &options.parent, attachment_key,
            MachineArtifactKind::Blocks, &blocks,
        )?,
        write_sidecar_jsonl(
            storage_dir, &options.parent, attachment_key,
            MachineArtifactKind::Chunks, &chunks,
        )?,
    ];

    let embedding_count = embed_sidecar_chunks(client, storage_dir, &options.parent, attachment_key, &chunks);

    Ok(serde_json::json!({
        "provider": provider,
        "status": "indexed",
        "item_key": options.parent,
        "attachment_key": attachment_key,
        "embeddings": embedding_count,
        "attachment_path": attachment_path,
        "storage_dir": storage_dir,
        "blocks": blocks.len(),
        "chunks": chunks.len(),
        "artifacts": artifacts,
    }))
}

fn embed_sidecar_chunks(
    client: &mut impl RpcCaller,
    storage_dir: &Path,
    item_key: &str,
    _attachment_key: &str,
    chunks: &[zotron_types::StructureChunk],
) -> usize {
    let Ok((provider, model, api_url, api_key)) = fetch_embedding_settings(client) else {
        return 0;
    };
    if provider.is_empty() || (api_key.is_empty() && provider != "ollama") {
        return 0;
    }
    let emb_chunks: Vec<EmbeddingChunkInput> = chunks
        .iter()
        .map(|c| EmbeddingChunkInput {
            chunk_key: c.chunk_key.clone(),
            text: c.text.clone(),
        })
        .collect();
    if emb_chunks.is_empty() {
        return 0;
    }
    // Batch in groups of 20 to avoid API limits
    let batch_size = 20;
    let mut all_vectors: Vec<EmbeddingVector> = Vec::new();
    for batch in emb_chunks.chunks(batch_size) {
        let input = EmbeddingRequestInput {
            item_key: item_key.to_string(),
            chunks: batch.to_vec(),
            model: if model.is_empty() { None } else { Some(model.clone()) },
            url: if api_url.is_empty() { None } else { Some(api_url.clone()) },
            input_type: Some("document".to_string()),
        };
        let Ok(request) = build_embedding_provider_request(&provider, &input) else {
            break;
        };
        let Some(url) = request.url.as_deref() else { break };
        let mut http = ureq::post(url).set("Content-Type", "application/json");
        if let Some(auth) = request.auth_header {
            if !api_key.is_empty() {
                http = http.set(auth, &format!("Bearer {api_key}"));
            }
        }
        let Ok(resp) = http.send_json(&request.body) else { break };
        let Ok(payload): Result<Value, _> = resp.into_json() else { break };
        let Ok(vectors) = parse_embedding_provider_response(&provider, &payload, item_key, batch)
        else {
            break;
        };
        all_vectors.extend(vectors);
    }
    let count = all_vectors.len();
    if count > 0 {
        let filename = embedding_vector_filename(&provider, &model);
        let vectors_dir = storage_dir.join(".zotron").join("embeddings");
        fs::create_dir_all(&vectors_dir).map_err(|e| {
            eprintln!("warning: cannot create embeddings dir {}: {e}", vectors_dir.display());
            e
        }).ok();
        let vectors_path = vectors_dir.join(&filename);
        let mut out = String::new();
        for v in &all_vectors {
            if let Ok(line) = serde_json::to_string(v) {
                out.push_str(&line);
                out.push('\n');
            }
        }
        if let Err(e) = fs::write(&vectors_path, &out) {
            eprintln!("warning: failed to persist embeddings to {}: {e}", vectors_path.display());
        }
    }
    count
}

struct MineruResultSource {
    task_id: Option<String>,
    state: String,
    result_dir: PathBuf,
    raw_zip_bytes: Option<Vec<u8>>,
    task_status: Option<Value>,
    payload: Value,
    content_list_file: Option<PathBuf>,
    markdown: Option<String>,
}

struct PersistedOcrArtifacts {
    block_count: usize,
    chunk_count: usize,
    artifacts: Vec<Value>,
}

fn resolve_attachment_path(
    client: &mut impl RpcCaller,
    attachment_key: &str,
) -> Result<PathBuf, String> {
    let payload = client.call(
        "attachments.getPath",
        Some(serde_json::json!({"key": attachment_key})),
    )?;
    let raw_path = payload
        .get("path")
        .and_then(Value::as_str)
        .filter(|path| !path.trim().is_empty())
        .ok_or_else(|| {
            format!("ATTACHMENT_PATH_NOT_FOUND: attachment {attachment_key} has no local PDF path")
        })?;
    Ok(PathBuf::from(local_path_from_zotero_path(raw_path)))
}

/// Resolve the first PDF attachment key for a parent item via `attachments.list`.
fn resolve_first_pdf_attachment_key(
    client: &mut impl RpcCaller,
    parent_key: &str,
) -> Result<String, String> {
    let response = client.call(
        "attachments.list",
        Some(serde_json::json!({"parentKey": parent_key})),
    )?;
    // The XPI returns {items: [...], total: N}.
    let attachments = response
        .get("items")
        .and_then(Value::as_array)
        .or_else(|| response.as_array())
        .ok_or_else(|| {
            format!("NO_PDF_ATTACHMENT: no attachments found for item {parent_key}")
        })?;
    for attachment in attachments {
        if is_pdf_attachment(attachment) {
            if let Some(key) = attachment.get("key").and_then(Value::as_str) {
                return Ok(key.to_string());
            }
        }
    }
    Err(format!(
        "NO_PDF_ATTACHMENT: no PDF attachment found for item {parent_key}"
    ))
}

fn load_mineru_result_source(
    options: &OcrProcessOptions,
    attachment_path: &Path,
    file_name: &str,
) -> Result<MineruResultSource, String> {
    if let Some(result_dir) = options.result_dir.as_deref() {
        return mineru_result_source_from_dir(PathBuf::from(result_dir), None, None, None);
    }
    if let Some(result_zip) = options.result_zip.as_deref() {
        let zip_path = PathBuf::from(result_zip);
        let zip_bytes = fs::read(&zip_path)
            .map_err(|err| format!("read MinerU result zip {}: {err}", zip_path.display()))?;
        let result_dir = extract_zip_bytes_to_temp("zotron-mineru-result", &zip_bytes)?;
        return mineru_result_source_from_dir(result_dir, Some(zip_bytes), None, None);
    }

    let Some(source_url) = options
        .source_url
        .as_deref()
        .filter(|value| !value.trim().is_empty())
    else {
        return submit_mineru_local_file(options, attachment_path, file_name);
    };
    let input = OcrRequestInput {
        item_key: options.parent.clone(),
        attachment_key: options.attachment.clone().expect("attachment resolved"),
        file_name: file_name.to_string(),
        mime_type: "application/pdf".to_string(),
        content_base64: format!("url:{source_url}"),
        source_url: Some(source_url.to_string()),
        local_path: None,
        output_dir: None,
    };
    let task = submit_mineru_task(
        &options.provider,
        &input,
        options.provider_endpoint.clone(),
        &options.api_key_env,
    )?;
    let task_id = task
        .get("data")
        .and_then(|data| data.get("task_id"))
        .and_then(Value::as_str)
        .ok_or_else(|| "MinerU submit response missing data.task_id".to_string())?
        .to_string();
    let auth_header = provider_auth_header_value(&options.api_key_env, "bearer")?;
    let status = poll_mineru_task(
        options.provider_endpoint.as_deref(),
        &task_id,
        &auth_header,
        options.poll_interval_seconds,
        options.timeout_seconds,
    )?;
    let zip_url = status
        .pointer("/data/full_zip_url")
        .or_else(|| status.pointer("/data/result/full_zip_url"))
        .and_then(Value::as_str)
        .ok_or_else(|| "MinerU completed task missing data.full_zip_url".to_string())?;
    let zip_bytes = download_bytes(zip_url)?;
    let result_dir = extract_zip_bytes_to_temp("zotron-mineru-result", &zip_bytes)?;
    mineru_result_source_from_dir(result_dir, Some(zip_bytes), Some(status), Some(task_id))
}

fn submit_mineru_local_file(
    options: &OcrProcessOptions,
    attachment_path: &Path,
    file_name: &str,
) -> Result<MineruResultSource, String> {
    let auth_header = provider_auth_header_value(&options.api_key_env, "bearer")?;
    let upload_request = create_mineru_file_upload(
        options.provider_endpoint.as_deref(),
        file_name,
        options.attachment.as_deref().expect("attachment resolved"),
        &auth_header,
    )?;
    let upload_url = upload_request
        .pointer("/data/file_urls/0")
        .or_else(|| upload_request.pointer("/data/fileUrls/0"))
        .and_then(Value::as_str)
        .ok_or_else(|| "MinerU upload URL response missing data.file_urls[0]".to_string())?;
    let batch_id = upload_request
        .pointer("/data/batch_id")
        .or_else(|| upload_request.pointer("/data/batchId"))
        .and_then(Value::as_str)
        .ok_or_else(|| "MinerU upload URL response missing data.batch_id".to_string())?
        .to_string();
    let bytes = fs::read(attachment_path)
        .map_err(|err| format!("read attachment PDF {}: {err}", attachment_path.display()))?;
    put_bytes(upload_url, &bytes)?;
    let status = poll_mineru_batch(
        options.provider_endpoint.as_deref(),
        &batch_id,
        &auth_header,
        options.poll_interval_seconds,
        options.timeout_seconds,
    )?;
    let zip_url = mineru_batch_zip_url(&status)
        .ok_or_else(|| "MinerU completed batch missing full_zip_url".to_string())?;
    let zip_bytes = download_bytes(&zip_url)?;
    let result_dir = extract_zip_bytes_to_temp("zotron-mineru-result", &zip_bytes)?;
    mineru_result_source_from_dir(result_dir, Some(zip_bytes), Some(status), Some(batch_id))
}

fn create_mineru_file_upload(
    endpoint: Option<&str>,
    file_name: &str,
    data_id: &str,
    auth_header: &str,
) -> Result<Value, String> {
    let url = mineru_file_urls_url(endpoint);
    let body = serde_json::json!({
        "files": [{"name": file_name, "data_id": data_id}],
        "model_version": "vlm",
        "is_ocr": false,
        "enable_formula": true,
        "enable_table": true,
        "language": "ch",
        "page_ranges": "1-200",
    });
    ureq::post(&url)
        .set("Authorization", auth_header)
        .send_json(body)
        .map_err(|err| format!("POST {url} failed: {err}"))?
        .into_json::<Value>()
        .map_err(|err| format!("POST {url} returned invalid JSON: {err}"))
}

fn put_bytes(url: &str, bytes: &[u8]) -> Result<(), String> {
    ureq::put(url)
        .send_bytes(bytes)
        .map_err(|err| format!("PUT {url} failed: {err}"))?;
    Ok(())
}

fn submit_mineru_task(
    provider: &str,
    input: &OcrRequestInput,
    endpoint: Option<String>,
    api_key_env: &str,
) -> Result<Value, String> {
    let request = build_ocr_provider_request(provider, input)?;
    let method = request
        .method
        .ok_or_else(|| "MinerU provider missing HTTP method".to_string())?;
    let mut transport = provider_http_transport_with_auth(Some(api_key_env), "bearer")?;
    transport.post_json(&ProviderHttpInvocation {
        provider: request.provider.to_string(),
        style: request.style.to_string(),
        method: method.to_string(),
        url: endpoint.or_else(|| request.url.map(ToString::to_string)),
        auth_header_name: request.auth_header.map(ToString::to_string),
        auth_header_value: None,
        body: request.body,
    })
}

fn poll_mineru_task(
    endpoint: Option<&str>,
    task_id: &str,
    auth_header: &str,
    poll_interval_seconds: u64,
    timeout_seconds: u64,
) -> Result<Value, String> {
    let url = mineru_task_status_url(endpoint, task_id);
    let started = Instant::now();
    loop {
        let status = get_json_with_auth(&url, auth_header)?;
        let state = status
            .pointer("/data/state")
            .or_else(|| status.pointer("/data/status"))
            .and_then(Value::as_str)
            .unwrap_or("unknown");
        match state {
            "done" | "finished" | "success" => return Ok(status),
            "failed" | "error" => return Err(format!("MinerU task {task_id} failed: {status}")),
            _ => {
                if started.elapsed() >= Duration::from_secs(timeout_seconds) {
                    return Err(format!(
                        "MinerU task {task_id} timed out after {timeout_seconds}s with state {state}"
                    ));
                }
                thread::sleep(Duration::from_secs(poll_interval_seconds.max(1)));
            }
        }
    }
}

fn mineru_task_status_url(endpoint: Option<&str>, task_id: &str) -> String {
    let base = endpoint
        .unwrap_or("https://mineru.net/api/v4/extract/task")
        .trim_end_matches('/');
    if base.ends_with("/extract/task") {
        format!("{base}/{task_id}")
    } else {
        format!("{base}/extract/task/{task_id}")
    }
}

fn mineru_file_urls_url(endpoint: Option<&str>) -> String {
    let base = mineru_api_base(endpoint);
    format!("{base}/file-urls/batch")
}

fn mineru_batch_status_url(endpoint: Option<&str>, batch_id: &str) -> String {
    let base = mineru_api_base(endpoint);
    format!("{base}/extract-results/batch/{batch_id}")
}

fn mineru_api_base(endpoint: Option<&str>) -> String {
    let base = endpoint
        .unwrap_or("https://mineru.net/api/v4/extract/task")
        .trim_end_matches('/');
    if let Some(stripped) = base.strip_suffix("/extract/task") {
        return stripped.to_string();
    }
    if let Some(stripped) = base.strip_suffix("/extract") {
        return stripped.to_string();
    }
    base.to_string()
}

fn poll_mineru_batch(
    endpoint: Option<&str>,
    batch_id: &str,
    auth_header: &str,
    poll_interval_seconds: u64,
    timeout_seconds: u64,
) -> Result<Value, String> {
    let url = mineru_batch_status_url(endpoint, batch_id);
    let started = Instant::now();
    loop {
        let status = get_json_with_auth(&url, auth_header)?;
        let state = mineru_batch_state(&status).unwrap_or("unknown");
        match state {
            "done" | "finished" | "success" => return Ok(status),
            "failed" | "error" => return Err(format!("MinerU batch {batch_id} failed: {status}")),
            _ => {
                if started.elapsed() >= Duration::from_secs(timeout_seconds) {
                    return Err(format!(
                        "MinerU batch {batch_id} timed out after {timeout_seconds}s with state {state}"
                    ));
                }
                thread::sleep(Duration::from_secs(poll_interval_seconds.max(1)));
            }
        }
    }
}

fn mineru_batch_state(status: &Value) -> Option<&str> {
    status
        .pointer("/data/extract_result/0/state")
        .or_else(|| status.pointer("/data/extractResult/0/state"))
        .or_else(|| status.pointer("/data/state"))
        .and_then(Value::as_str)
}

fn mineru_batch_zip_url(status: &Value) -> Option<String> {
    status
        .pointer("/data/extract_result/0/full_zip_url")
        .or_else(|| status.pointer("/data/extractResult/0/full_zip_url"))
        .or_else(|| status.pointer("/data/full_zip_url"))
        .and_then(Value::as_str)
        .map(ToString::to_string)
}

fn provider_auth_header_value(api_key_env: &str, auth_scheme: &str) -> Result<String, String> {
    let token = env::var(api_key_env)
        .map_err(|_| format!("missing provider credential env var {api_key_env}"))?;
    let token = token.trim();
    if token.is_empty() {
        return Err(format!(
            "provider credential env var {api_key_env} is empty"
        ));
    }
    Ok(match auth_scheme {
        "bearer" if token.starts_with("Bearer ") => token.to_string(),
        "bearer" => format!("Bearer {token}"),
        "token" if token.starts_with("token ") => token.to_string(),
        "token" => format!("token {token}"),
        _ => token.to_string(),
    })
}

fn get_json_with_auth(url: &str, auth_header: &str) -> Result<Value, String> {
    ureq::get(url)
        .set("Authorization", auth_header)
        .call()
        .map_err(|err| format!("GET {url} failed: {err}"))?
        .into_json::<Value>()
        .map_err(|err| format!("GET {url} returned invalid JSON: {err}"))
}

fn download_bytes(url: &str) -> Result<Vec<u8>, String> {
    let response = ureq::get(url)
        .call()
        .map_err(|err| format!("download {url} failed: {err}"))?;
    let mut bytes = Vec::new();
    response
        .into_reader()
        .read_to_end(&mut bytes)
        .map_err(|err| format!("read download {url}: {err}"))?;
    Ok(bytes)
}

fn extract_zip_bytes_to_temp(prefix: &str, zip_bytes: &[u8]) -> Result<PathBuf, String> {
    let dir = unique_temp_path(prefix);
    fs::create_dir_all(&dir).map_err(|err| format!("create temp dir {}: {err}", dir.display()))?;
    let zip_path = dir.with_extension("zip");
    fs::write(&zip_path, zip_bytes)
        .map_err(|err| format!("write temp zip {}: {err}", zip_path.display()))?;
    let output = ProcessCommand::new("unzip")
        .arg("-q")
        .arg("-o")
        .arg(&zip_path)
        .arg("-d")
        .arg(&dir)
        .output()
        .map_err(|err| format!("run unzip: {err}"))?;
    if !output.status.success() {
        return Err(format!(
            "unzip {} failed: {}",
            zip_path.display(),
            String::from_utf8_lossy(&output.stderr).trim()
        ));
    }
    Ok(dir)
}

fn unique_temp_path(prefix: &str) -> PathBuf {
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|duration| duration.as_nanos())
        .unwrap_or(0);
    env::temp_dir().join(format!("{prefix}-{}-{nanos}", std::process::id()))
}

fn mineru_result_source_from_dir(
    result_dir: PathBuf,
    raw_zip_bytes: Option<Vec<u8>>,
    task_status: Option<Value>,
    task_id: Option<String>,
) -> Result<MineruResultSource, String> {
    let (payload, content_list_file) = mineru_payload_from_result_dir(&result_dir)?;
    let markdown = find_first_file_by_name(&result_dir, "full.md")
        .map(|path| {
            fs::read_to_string(&path)
                .map_err(|err| format!("read native markdown {}: {err}", path.display()))
        })
        .transpose()?;
    Ok(MineruResultSource {
        task_id,
        state: "done".to_string(),
        result_dir,
        raw_zip_bytes,
        task_status,
        payload,
        content_list_file,
        markdown,
    })
}

fn mineru_payload_from_result_dir(result_dir: &Path) -> Result<(Value, Option<PathBuf>), String> {
    let v2 = find_first_file_with_suffix(result_dir, "_content_list_v2.json");
    if let Some(path) = v2 {
        let value = read_json_file(&path)?;
        return Ok((serde_json::json!({"content_list_v2": value}), Some(path)));
    }
    let content_list = find_first_file_with_suffix(result_dir, "_content_list.json");
    if let Some(path) = content_list {
        let value = read_json_file(&path)?;
        return Ok((serde_json::json!({"content_list": value}), Some(path)));
    }
    let layout = find_first_file_by_name(result_dir, "layout.json");
    if let Some(path) = layout {
        return Ok((read_json_file(&path)?, Some(path)));
    }
    let markdown = find_first_file_by_name(result_dir, "full.md");
    if let Some(path) = markdown {
        let text = fs::read_to_string(&path)
            .map_err(|err| format!("read native markdown {}: {err}", path.display()))?;
        return Ok((serde_json::json!({"result": text}), Some(path)));
    }
    Err(format!(
        "MinerU result directory {} missing content_list_v2/content_list/layout/full.md",
        result_dir.display()
    ))
}

fn read_json_file(path: &Path) -> Result<Value, String> {
    let raw = fs::read_to_string(path).map_err(|err| format!("read {}: {err}", path.display()))?;
    serde_json::from_str(&raw).map_err(|err| format!("parse JSON {}: {err}", path.display()))
}

fn persist_mineru_result_sidecars(
    storage_dir: &Path,
    item_key: &str,
    attachment_key: &str,
    provider: &str,
    source: &MineruResultSource,
    chunk_chars: usize,
) -> Result<PersistedOcrArtifacts, String> {
    let blocks = parse_ocr_provider_response(provider, &source.payload, item_key, attachment_key)?;
    let chunks = zotron_types::chunks_from_blocks(&blocks, chunk_chars);
    let assets = copy_mineru_assets(&source.result_dir, storage_dir)?;
    let raw_bundle = serde_json::json!({
        "provider": provider,
        "item_key": item_key,
        "attachment_key": attachment_key,
        "task_id": source.task_id,
        "state": source.state,
        "task_status": source.task_status,
        "content_list_file": source.content_list_file,
        "payload": source.payload,
    });

    let mut artifacts = Vec::new();
    artifacts.push(write_sidecar_json(
        storage_dir,
        item_key,
        attachment_key,
        MachineArtifactKind::OcrRaw,
        &raw_bundle,
    )?);
    artifacts.push(write_sidecar_jsonl(
        storage_dir,
        item_key,
        attachment_key,
        MachineArtifactKind::Blocks,
        &blocks,
    )?);
    artifacts.push(write_sidecar_jsonl(
        storage_dir,
        item_key,
        attachment_key,
        MachineArtifactKind::Chunks,
        &chunks,
    )?);
    if let Some(markdown) = source.markdown.as_deref() {
        artifacts.push(write_sidecar_bytes(
            storage_dir,
            item_key,
            attachment_key,
            MachineArtifactKind::OcrNativeMarkdown,
            markdown.as_bytes(),
        )?);
    }
    artifacts.push(write_sidecar_json(
        storage_dir,
        item_key,
        attachment_key,
        MachineArtifactKind::OcrNativeAssets,
        &assets,
    )?);
    if let Some(bytes) = source.raw_zip_bytes.as_deref() {
        artifacts.push(write_extra_sidecar_bytes(
            storage_dir,
            ".zotron/ocr/latest.raw.zip",
            bytes,
        )?);
    }

    Ok(PersistedOcrArtifacts {
        block_count: blocks.len(),
        chunk_count: chunks.len(),
        artifacts,
    })
}

fn write_sidecar_json(
    storage_dir: &Path,
    item_key: &str,
    attachment_key: &str,
    kind: MachineArtifactKind,
    value: &Value,
) -> Result<Value, String> {
    let bytes = serde_json::to_vec_pretty(value).map_err(|err| err.to_string())?;
    write_sidecar_bytes(storage_dir, item_key, attachment_key, kind, &bytes)
}

fn write_sidecar_jsonl<T: serde::Serialize>(
    storage_dir: &Path,
    item_key: &str,
    attachment_key: &str,
    kind: MachineArtifactKind,
    values: &[T],
) -> Result<Value, String> {
    let mut out = String::new();
    for value in values {
        out.push_str(&serde_json::to_string(value).map_err(|err| err.to_string())?);
        out.push('\n');
    }
    write_sidecar_bytes(storage_dir, item_key, attachment_key, kind, out.as_bytes())
}

fn write_sidecar_bytes(
    storage_dir: &Path,
    item_key: &str,
    attachment_key: &str,
    kind: MachineArtifactKind,
    bytes: &[u8],
) -> Result<Value, String> {
    let record = write_machine_artifact_sidecar(storage_dir, item_key, attachment_key, kind, bytes)
        .map_err(|err| format!("write sidecar {:?}: {err}", kind))?;
    Ok(serde_json::json!({
        "kind": kind,
        "relative_path": record.relative_path,
        "absolute_path": record.absolute_path,
    }))
}

fn write_extra_sidecar_bytes(
    storage_dir: &Path,
    relative_path: &str,
    bytes: &[u8],
) -> Result<Value, String> {
    let absolute_path = storage_dir.join(relative_path);
    if let Some(parent) = absolute_path.parent() {
        fs::create_dir_all(parent).map_err(|err| format!("create {}: {err}", parent.display()))?;
    }
    fs::write(&absolute_path, bytes)
        .map_err(|err| format!("write sidecar {}: {err}", absolute_path.display()))?;
    Ok(serde_json::json!({
        "kind": "ocr_raw_zip",
        "relative_path": relative_path,
        "absolute_path": absolute_path,
    }))
}

fn copy_mineru_assets(result_dir: &Path, storage_dir: &Path) -> Result<Value, String> {
    let mut images = Vec::new();
    for file in collect_files(result_dir)? {
        if !is_image_file(&file) {
            continue;
        }
        let relative = file.strip_prefix(result_dir).unwrap_or(&file).to_path_buf();
        let destination = storage_dir.join(".zotron").join("ocr").join(&relative);
        if let Some(parent) = destination.parent() {
            fs::create_dir_all(parent)
                .map_err(|err| format!("create {}: {err}", parent.display()))?;
        }
        fs::copy(&file, &destination).map_err(|err| {
            format!(
                "copy MinerU asset {} to {}: {err}",
                file.display(),
                destination.display()
            )
        })?;
        images.push(serde_json::json!({
            "source_relative": relative,
            "sidecar_relative": PathBuf::from(".zotron").join("ocr").join(&relative),
            "absolute_path": destination,
        }));
    }
    Ok(serde_json::json!({
        "provider": "mineru",
        "images": images,
    }))
}

fn is_image_file(path: &Path) -> bool {
    matches!(
        path.extension()
            .and_then(|ext| ext.to_str())
            .unwrap_or_default()
            .to_ascii_lowercase()
            .as_str(),
        "png" | "jpg" | "jpeg" | "webp" | "gif"
    )
}

fn find_first_file_with_suffix(root: &Path, suffix: &str) -> Option<PathBuf> {
    collect_files(root).ok()?.into_iter().find(|path| {
        path.file_name()
            .and_then(|name| name.to_str())
            .is_some_and(|name| name.ends_with(suffix))
    })
}

fn find_first_file_by_name(root: &Path, name: &str) -> Option<PathBuf> {
    collect_files(root).ok()?.into_iter().find(|path| {
        path.file_name()
            .and_then(|file_name| file_name.to_str())
            .is_some_and(|file_name| file_name == name)
    })
}

fn collect_files(root: &Path) -> Result<Vec<PathBuf>, String> {
    let mut files = Vec::new();
    collect_files_into(root, &mut files)?;
    files.sort();
    Ok(files)
}

fn collect_files_into(root: &Path, files: &mut Vec<PathBuf>) -> Result<(), String> {
    for entry in fs::read_dir(root).map_err(|err| format!("read dir {}: {err}", root.display()))? {
        let entry = entry.map_err(|err| format!("read dir entry {}: {err}", root.display()))?;
        let path = entry.path();
        let file_type = entry
            .file_type()
            .map_err(|err| format!("stat {}: {err}", path.display()))?;
        if file_type.is_dir() {
            collect_files_into(&path, files)?;
        } else if file_type.is_file() {
            files.push(path);
        }
    }
    Ok(())
}

fn ocr_async_task_result(provider: &str, payload: &Value) -> Option<Value> {
    let data = payload.get("data")?;
    let task_id = data.get("task_id").and_then(Value::as_str)?;
    Some(serde_json::json!({
        "provider": provider,
        "status": "submitted",
        "task_id": task_id,
        "state": data.get("state").and_then(Value::as_str).unwrap_or("submitted"),
        "result_url": data.get("full_zip_url").or_else(|| data.get("markdown_url")).cloned(),
        "raw": payload,
    }))
}

fn ocr_input_from_file(
    file: String,
    item_key: Option<String>,
    attachment_key: Option<String>,
    mime_type: Option<String>,
) -> Result<OcrRequestInput, String> {
    let item_key = item_key
        .ok_or_else(|| "INVALID_ARGS: --item-key is required when using --file".to_string())?;
    let attachment_key = attachment_key.ok_or_else(|| {
        "INVALID_ARGS: --attachment-key is required when using --file".to_string()
    })?;
    let path = PathBuf::from(&file);
    let bytes = fs::read(&path).map_err(|err| format!("read {file}: {err}"))?;
    let file_name = path
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or("document.pdf")
        .to_string();
    let mime_type = mime_type.unwrap_or_else(|| guess_mime_type(&path).to_string());
    Ok(OcrRequestInput {
        item_key,
        attachment_key,
        file_name,
        mime_type,
        content_base64: base64_encode(&bytes),
        source_url: None,
        local_path: Some(file),
        output_dir: None,
    })
}

fn guess_mime_type(path: &Path) -> &'static str {
    match path
        .extension()
        .and_then(|ext| ext.to_str())
        .unwrap_or_default()
        .to_ascii_lowercase()
        .as_str()
    {
        "png" => "image/png",
        "jpg" | "jpeg" => "image/jpeg",
        "webp" => "image/webp",
        _ => "application/pdf",
    }
}

fn base64_encode(bytes: &[u8]) -> String {
    const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
    for chunk in bytes.chunks(3) {
        let b0 = chunk[0];
        let b1 = *chunk.get(1).unwrap_or(&0);
        let b2 = *chunk.get(2).unwrap_or(&0);
        out.push(TABLE[(b0 >> 2) as usize] as char);
        out.push(TABLE[(((b0 & 0b0000_0011) << 4) | (b1 >> 4)) as usize] as char);
        if chunk.len() > 1 {
            out.push(TABLE[(((b1 & 0b0000_1111) << 2) | (b2 >> 6)) as usize] as char);
        } else {
            out.push('=');
        }
        if chunk.len() > 2 {
            out.push(TABLE[(b2 & 0b0011_1111) as usize] as char);
        } else {
            out.push('=');
        }
    }
    out
}

fn run_ocr_status_command(
    client: &mut impl RpcCaller,
    collection: String,
) -> Result<Value, String> {
    let collection_key = find_collection_in_tree(client, &collection)?
        .and_then(|node| node.get("key").cloned())
        .ok_or_else(|| format!("COLLECTION_NOT_FOUND: Collection not found: {collection:?}"))?;
    let raw = paginate_rpc(
        client,
        "collections.getItems",
        serde_json::json!({"key": collection_key}),
        500,
    )?;
    let items = raw
        .get("items")
        .and_then(Value::as_array)
        .or_else(|| raw.as_array())
        .ok_or_else(|| "collections.getItems returned non-array/non-items result".to_string())?
        .clone();

    let mut has_ocr = 0usize;
    for item in &items {
        let item_key = item.get("key").cloned().unwrap_or(Value::Null);
        if has_ocr_artifact(client, &item_key)? || has_ocr_note(client, &item_key)? {
            has_ocr += 1;
        }
    }

    Ok(serde_json::json!({
        "collection": collection,
        "total": items.len(),
        "has_ocr": has_ocr,
        "missing_ocr": items.len() - has_ocr,
    }))
}

fn has_ocr_artifact(client: &mut impl RpcCaller, item_key: &Value) -> Result<bool, String> {
    if let Some(item_key) = item_key.as_str() {
        // Legacy external store lookup for artifacts produced before the
        // per-attachment hidden sidecar became the default.
        if machine_artifact_exists_for_item(
            machine_artifact_store_root(),
            item_key,
            MachineArtifactKind::Chunks,
        ) {
            return Ok(true);
        }
    }

    let attachments = client.call(
        "attachments.list",
        Some(serde_json::json!({"parentKey": item_key.clone()})),
    )?;
    Ok(attachments.as_array().is_some_and(|attachments| {
        attachments.iter().any(|attachment| {
            let has_sidecar_chunks = attachment
                .get("path")
                .and_then(Value::as_str)
                .map(local_path_from_zotero_path)
                .as_deref()
                .map(Path::new)
                .and_then(Path::parent)
                .is_some_and(|dir| {
                    machine_artifact_exists_in_sidecar(dir, MachineArtifactKind::Chunks)
                });
            if has_sidecar_chunks {
                return true;
            }

            // Read-only fallback for old Zotero-visible artifact attachments.
            attachment
                .get("title")
                .and_then(Value::as_str)
                .is_some_and(|title| title.ends_with("zotron-chunks.jsonl"))
        })
    }))
}

fn local_path_from_zotero_path(path: &str) -> String {
    if is_wsl() && path.as_bytes().get(1) == Some(&b':') {
        return ProcessCommand::new("wslpath")
            .arg("-u")
            .arg(path)
            .output()
            .ok()
            .filter(|output| output.status.success())
            .and_then(|output| String::from_utf8(output.stdout).ok())
            .map(|converted| converted.trim().to_string())
            .filter(|converted| !converted.is_empty())
            .unwrap_or_else(|| path.to_string());
    }
    path.to_string()
}

fn has_ocr_note(client: &mut impl RpcCaller, item_key: &Value) -> Result<bool, String> {
    let notes = client.call(
        "notes.list",
        Some(serde_json::json!({"parentKey": item_key.clone()})),
    )?;
    Ok(notes.as_array().is_some_and(|notes| {
        notes.iter().any(|note| {
            note.get("tags")
                .and_then(Value::as_array)
                .is_some_and(|tags| tags.iter().any(tag_is_ocr))
        })
    }))
}

fn tag_is_ocr(tag: &Value) -> bool {
    tag.as_str() == Some("ocr")
        || tag
            .get("tag")
            .and_then(Value::as_str)
            .is_some_and(|tag| tag == "ocr")
}

fn find_collection_in_tree(
    client: &mut impl RpcCaller,
    collection: &str,
) -> Result<Option<Value>, String> {
    let tree = client.call("collections.tree", None)?;
    let nodes = tree
        .as_array()
        .ok_or_else(|| "collections.tree returned non-array result".to_string())?;
    Ok(search_collection_tree(nodes, collection).cloned())
}

fn search_collection_tree<'a>(nodes: &'a [Value], collection: &str) -> Option<&'a Value> {
    for node in nodes {
        if node.get("key").and_then(Value::as_str) == Some(collection)
            || node.get("name").and_then(Value::as_str) == Some(collection)
        {
            return Some(node);
        }
        if let Some(children) = node.get("children").and_then(Value::as_array) {
            if let Some(found) = search_collection_tree(children, collection) {
                return Some(found);
            }
        }
    }
    None
}

fn run_command(command: Command, client: &mut impl RpcCaller) -> Result<String, String> {
    if let Command::Export(args) = command {
        return run_export(args, client);
    }

    let (value, style) = match command {
        Command::Ping { .. } => (
            call_json(client, "system.ping", None)?,
            JsonStyle::PythonCompact,
        ),
        Command::Rpc {
            method,
            params_json,
            paginate,
            page_size,
            ..
        } => {
            let params = serde_json::from_str::<Value>(&params_json)
                .map_err(|err| format!("INVALID_JSON: params must be a JSON object: {err}"))?;
            if !params.is_object() {
                return Err("INVALID_JSON: params must be a JSON object".to_string());
            }
            if paginate {
                (
                    paginate_rpc(client, &method, params, page_size)?,
                    JsonStyle::Pretty,
                )
            } else {
                (call_json(client, &method, Some(params))?, JsonStyle::Pretty)
            }
        }
        Command::Push {
            json_file,
            pdf,
            collection,
            on_duplicate,
            dry_run,
            ..
        } => return run_push_command(json_file, pdf, collection, on_duplicate, dry_run, client),
        Command::System { command } => run_system_command(command, client)?,
        Command::Search(args) => {
            if let Some(mgmt) = args.management {
                run_search_management_command(mgmt, client)?
            } else {
                run_search(args, client)?
            }
        }
        Command::Items { command } => run_items_command(command, client)?,
        Command::Collections { command } => run_collections_command(command, client)?,
        Command::Notes { command } => run_notes_command(command, client)?,
        Command::Settings { command } => run_settings_command(command, client)?,
        Command::Tags { command } => run_tags_command(command, client)?,
        Command::Annotations { command } => run_annotations_command(command, client)?,
        Command::Ocr { command } => {
            return run_ocr_command(command, client);
        }
        Command::Rag { command } => {
            return run_rag_command(command, client);
        }
        Command::Export(_) => unreachable!("export commands return raw output above"),
    };

    format_json(&value, style)
}

fn run_rag_command(command: RagCommand, client: &mut impl RpcCaller) -> Result<String, String> {
    match command {
        RagCommand::Providers => format_json(
            &serde_json::json!({
                "providers": [
                    embedding_provider_spec("volcengine")?,
                    embedding_provider_spec("alibaba")?,
                    embedding_provider_spec("custom")?,
                ],
            }),
            JsonStyle::Pretty,
        ),
        RagCommand::Embed {
            provider,
            input,
            endpoint,
            model,
            input_type,
            api_key_env,
        } => {
            let value = run_embedding_provider_json_command(
                provider,
                input,
                endpoint,
                model,
                input_type,
                api_key_env,
            )?;
            format_json(&value, JsonStyle::PythonCompact)
        }
        RagCommand::Status { collection, .. } => {
            let value = rag_status_value(client, &collection)?;
            format_json(&value, JsonStyle::PythonCompact)
        }
        RagCommand::Search {
            query,
            collection,
            keys,
            zotero,
            top_spans_per_item,
            include_fulltext_spans,
            top_k,
            output,
            ..
        } => run_rag_search_command(
            client,
            RagSearchOptions {
                query,
                collection,
                keys,
                zotero,
                top_spans_per_item,
                include_fulltext_spans,
                top_k,
                output,
            },
        ),
    }
}

fn run_embedding_provider_json_command(
    provider: String,
    input: String,
    endpoint: Option<String>,
    model: Option<String>,
    input_type: Option<String>,
    api_key_env: Option<String>,
) -> Result<Value, String> {
    let mut input: EmbeddingRequestInput = read_json_input(&input)?;
    if endpoint.is_some() {
        input.url = endpoint;
    }
    if model.is_some() {
        input.model = model;
    }
    if input_type.is_some() {
        input.input_type = input_type;
    }
    let mut transport = provider_http_transport(api_key_env.as_deref())?;
    let vectors = execute_embedding_provider_request(&provider, &input, &mut transport)?;

    Ok(serde_json::json!({
        "provider": provider,
        "vectors": vectors,
    }))
}

fn provider_http_transport(api_key_env: Option<&str>) -> Result<UreqProviderHttpTransport, String> {
    provider_http_transport_with_auth(api_key_env, "bearer")
}

fn provider_http_transport_with_auth(
    api_key_env: Option<&str>,
    auth_scheme: &str,
) -> Result<UreqProviderHttpTransport, String> {
    let Some(env_name) = api_key_env else {
        return Ok(UreqProviderHttpTransport::new());
    };
    let token = env::var(env_name)
        .map_err(|_| format!("missing provider credential env var {env_name}"))?;
    if token.trim().is_empty() {
        return Err(format!("provider credential env var {env_name} is empty"));
    }
    let token = token.trim();
    match auth_scheme {
        "token" if token.starts_with("token ") => {
            Ok(UreqProviderHttpTransport::with_api_key(token.to_string()))
        }
        "token" => Ok(UreqProviderHttpTransport::with_api_key(format!(
            "token {token}"
        ))),
        "bearer" if token.starts_with("Bearer ") => {
            Ok(UreqProviderHttpTransport::with_api_key(token.to_string()))
        }
        "bearer" => Ok(UreqProviderHttpTransport::with_bearer_token(token)),
        "none" => Ok(UreqProviderHttpTransport::new()),
        other => Err(format!("unsupported provider auth scheme {other}")),
    }
}

fn read_json_input<T: serde::de::DeserializeOwned>(path: &str) -> Result<T, String> {
    let payload = if path == "-" {
        let mut input = String::new();
        io::stdin()
            .read_to_string(&mut input)
            .map_err(|err| format!("read stdin: {err}"))?;
        input
    } else {
        fs::read_to_string(path).map_err(|err| format!("read {path}: {err}"))?
    };
    serde_json::from_str::<T>(&payload)
        .map_err(|err| format!("INVALID_JSON: Could not parse JSON: {err}"))
}

fn fetch_embedding_settings(
    client: &mut impl RpcCaller,
) -> Result<(String, String, String, String), String> {
    let settings = client.call("settings.getAll", None)?;
    let provider = settings
        .get("embedding.provider")
        .and_then(Value::as_str)
        .unwrap_or("ollama")
        .to_string();
    let model = settings
        .get("embedding.model")
        .and_then(Value::as_str)
        .unwrap_or("")
        .to_string();
    let api_url = settings
        .get("embedding.apiUrl")
        .and_then(Value::as_str)
        .unwrap_or("")
        .to_string();
    let raw = client.call("settings.getRaw", Some(serde_json::json!({"key": "embedding.apiKey"})))?;
    let api_key = raw
        .get("embedding.apiKey")
        .and_then(Value::as_str)
        .unwrap_or("")
        .to_string();
    Ok((provider, model, api_url, api_key))
}

fn fetch_retrieval_mode(client: &mut impl RpcCaller) -> String {
    client
        .call(
            "settings.get",
            Some(serde_json::json!({"key": "rag.retrievalMode"})),
        )
        .ok()
        .and_then(|v| {
            v.get("rag.retrievalMode")
                .and_then(Value::as_str)
                .map(String::from)
        })
        .unwrap_or_else(|| "hybrid".to_string())
}

fn resolve_sidecar_paths(
    client: &mut impl RpcCaller,
    collection: Option<&str>,
    keys: &[String],
) -> Result<Vec<(String, String, PathBuf)>, String> {
    let items = if !keys.is_empty() {
        let mut items = Vec::new();
        for key in keys {
            let item = client.call("items.get", Some(serde_json::json!({"key": key})))?;
            items.push(item);
        }
        items
    } else if let Some(col) = collection {
        let col_key = resolve_collection(client, col)?;
        let response = client.call(
            "collections.getItems",
            Some(serde_json::json!({"key": col_key})),
        )?;
        collection_items(&response)
    } else {
        return Err("INVALID_ARGS: --collection or --key required".into());
    };

    let mut results = Vec::new();
    for item in &items {
        let item_key = item.get("key").and_then(Value::as_str).unwrap_or_default();
        let attachments = client.call(
            "attachments.list",
            Some(serde_json::json!({"parentKey": item_key})),
        )?;
        let att_list = attachments
            .get("items")
            .and_then(Value::as_array)
            .or_else(|| attachments.as_array())
            .cloned()
            .unwrap_or_default();
        for att in &att_list {
            let content_type = att
                .get("contentType")
                .and_then(Value::as_str)
                .unwrap_or("");
            if content_type != "application/pdf" {
                continue;
            }
            let att_key = att.get("key").and_then(Value::as_str).unwrap_or_default();
            let path = att.get("path").and_then(Value::as_str).unwrap_or_default();
            if path.is_empty() {
                continue;
            }
            let local_path = local_path_from_zotero_path(path);
            let pdf_path = PathBuf::from(&local_path);
            if let Some(parent) = pdf_path.parent() {
                let sidecar_root = parent.join(".zotron");
                if sidecar_root.exists() {
                    results.push((item_key.to_string(), att_key.to_string(), sidecar_root));
                }
            }
        }
    }
    Ok(results)
}

fn load_sidecar_chunks(sidecar_root: &Path) -> Vec<StructureChunk> {
    let chunks_path = sidecar_root.join("chunks").join("chunks.v1.jsonl");
    let Ok(content) = fs::read_to_string(&chunks_path) else {
        return Vec::new();
    };
    content
        .lines()
        .filter(|line| !line.trim().is_empty())
        .filter_map(|line| serde_json::from_str::<StructureChunk>(line).ok())
        .collect()
}

fn embedding_vector_filename(provider: &str, model: &str) -> String {
    let p = provider.trim().to_lowercase().replace('/', "-");
    let m = model.trim().to_lowercase().replace('/', "-");
    if p.is_empty() && m.is_empty() {
        return "vectors.jsonl".to_string();
    }
    format!("{p}--{m}.jsonl")
}

fn load_sidecar_vectors(sidecar_root: &Path, provider: &str, model: &str) -> Vec<EmbeddingVector> {
    let embeddings_dir = sidecar_root.join("embeddings");
    let target = embedding_vector_filename(provider, model);
    let target_path = embeddings_dir.join(&target);
    if let Ok(content) = fs::read_to_string(&target_path) {
        let vecs: Vec<EmbeddingVector> = content
            .lines()
            .filter(|line| !line.trim().is_empty())
            .filter_map(|line| serde_json::from_str(line).ok())
            .collect();
        if !vecs.is_empty() {
            return vecs;
        }
    }
    // Fallback: try legacy vectors.v1.jsonl / vectors.jsonl with provider match
    for legacy in &["vectors.v1.jsonl", "vectors.jsonl"] {
        let path = embeddings_dir.join(legacy);
        if let Ok(content) = fs::read_to_string(&path) {
            let vecs: Vec<EmbeddingVector> = content
                .lines()
                .filter(|line| !line.trim().is_empty())
                .filter_map(|line| serde_json::from_str::<EmbeddingVector>(line).ok())
                .filter(|v| v.source_provider == provider || provider.is_empty())
                .collect();
            if !vecs.is_empty() {
                return vecs;
            }
        }
    }
    Vec::new()
}

fn embed_query_text(
    query: &str,
    provider: &str,
    model: &str,
    api_url: &str,
    api_key: &str,
) -> Result<Vec<f64>, String> {
    let input = EmbeddingRequestInput {
        item_key: "query".to_string(),
        chunks: vec![EmbeddingChunkInput {
            chunk_key: "q0".to_string(),
            text: query.to_string(),
        }],
        model: if model.is_empty() {
            None
        } else {
            Some(model.to_string())
        },
        url: if api_url.is_empty() {
            None
        } else {
            Some(api_url.to_string())
        },
        input_type: Some("query".to_string()),
    };
    let request = build_embedding_provider_request(provider, &input)?;
    let url = request
        .url
        .as_deref()
        .ok_or("no embedding URL configured")?;
    let mut http = ureq::post(url).set("Content-Type", "application/json");
    if let Some(auth) = request.auth_header {
        if !api_key.is_empty() {
            http = http.set(auth, &format!("Bearer {api_key}"));
        }
    }
    let resp = http
        .send_json(&request.body)
        .map_err(|e| format!("embedding request failed: {e}"))?;
    let payload: Value = resp
        .into_json()
        .map_err(|e| format!("embedding response parse: {e}"))?;
    let vectors =
        parse_embedding_provider_response(provider, &payload, "query", &input.chunks)?;
    vectors
        .into_iter()
        .next()
        .map(|v| v.vector)
        .ok_or_else(|| "no embedding vector returned".to_string())
}

fn run_rag_search_xpi_fallback(
    client: &mut impl RpcCaller,
    options: &RagSearchOptions,
) -> Result<String, String> {
    let mut params = serde_json::json!({
        "query": options.query,
        "limit": options.top_k,
        "top_spans_per_item": options.top_spans_per_item,
        "include_fulltext_spans": options.include_fulltext_spans,
    });
    if let Some(map) = params.as_object_mut() {
        if let Some(col) = &options.collection {
            map.insert("collection".into(), Value::String(col.clone()));
        }
        if !options.keys.is_empty() {
            map.insert(
                "keys".into(),
                Value::Array(options.keys.iter().map(|k| Value::String(k.clone())).collect()),
            );
        }
    }
    let payload = client.call("rag.searchHits", Some(params))?;
    let hits = payload
        .get("hits")
        .and_then(Value::as_array)
        .cloned()
        .unwrap_or_default();
    if options.output == "jsonl" {
        let mut out = String::new();
        for hit in &hits {
            out.push_str(&serde_json::to_string(hit).map_err(|e| e.to_string())?);
            out.push('\n');
        }
        Ok(out)
    } else {
        let total = hits.len() as u64;
        format_json(
            &normalize_list_envelope(
                serde_json::json!({"items": hits, "total": total}),
                "items",
                Some(options.top_k),
                0,
            ),
            JsonStyle::Pretty,
        )
    }
}

fn run_rag_search_command(
    client: &mut impl RpcCaller,
    options: RagSearchOptions,
) -> Result<String, String> {
    // When --zotero is explicitly passed, use XPI fallback directly (backward compat).
    if options.zotero {
        if options.collection.is_none() && options.keys.is_empty() {
            return Err(
                "INVALID_ARGS: --collection or --key is required".to_string(),
            );
        }
        return run_rag_search_xpi_fallback(client, &options);
    }

    // Hybrid path: require scope.
    if options.collection.is_none() && options.keys.is_empty() {
        return Err("INVALID_ARGS: --collection or --key required".to_string());
    }

    // Step 1: resolve sidecar paths from collection/keys.
    let sidecars = resolve_sidecar_paths(
        client,
        options.collection.as_deref(),
        &options.keys,
    );

    // If sidecar resolution fails or returns empty, fall back to XPI.
    // But propagate COLLECTION_NOT_FOUND errors directly instead of masking them.
    let sidecars = match sidecars {
        Ok(ref s) if !s.is_empty() => s,
        Err(ref e) if e.contains("COLLECTION_NOT_FOUND") => return Err(e.clone()),
        _ => return run_rag_search_xpi_fallback(client, &options),
    };

    // Step 2: load all chunks and vectors from sidecars.
    let (emb_provider, emb_model, emb_url, emb_key) = fetch_embedding_settings(client)?;
    let mut all_chunks: Vec<StructureChunk> = Vec::new();
    let mut all_vectors: Vec<EmbeddingVector> = Vec::new();
    for (_item_key, _att_key, sidecar_root) in sidecars {
        all_chunks.extend(load_sidecar_chunks(sidecar_root));
        all_vectors.extend(load_sidecar_vectors(sidecar_root, &emb_provider, &emb_model));
    }

    if all_chunks.is_empty() {
        return run_rag_search_xpi_fallback(client, &options);
    }

    // Step 3: determine retrieval mode.
    let mode = fetch_retrieval_mode(client);

    // Step 4: BM25 scoring (unless mode is "dense").
    let bm25_ranked = if mode != "dense" {
        bm25_score_chunks(&all_chunks, &options.query, 1.2, 0.75)
    } else {
        Vec::new()
    };

    // Step 5: dense vector scoring (unless mode is "lexical" or no vectors).
    let dense_ranked = if mode != "lexical" && !all_vectors.is_empty() {
        match embed_query_text(&options.query, &emb_provider, &emb_model, &emb_url, &emb_key) {
            Ok(query_vec) => {
                let vec_map: std::collections::HashMap<&str, &[f64]> = all_vectors
                    .iter()
                    .map(|v| (v.chunk_key.as_str(), v.vector.as_slice()))
                    .collect();
                let mut scores: Vec<(usize, f64)> = all_chunks
                    .iter()
                    .enumerate()
                    .filter_map(|(i, chunk)| {
                        vec_map.get(chunk.chunk_key.as_str()).map(|stored| {
                            (i, cosine_similarity(&query_vec, stored))
                        })
                    })
                    .filter(|(_, s)| *s > 0.0)
                    .collect();
                scores.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
                scores
            }
            Err(_) => Vec::new(),
        }
    } else {
        Vec::new()
    };

    // Step 6: merge results.
    let limit = options.top_k as usize;
    let ranked = if !bm25_ranked.is_empty() && !dense_ranked.is_empty() {
        rrf_merge(&bm25_ranked, &dense_ranked, 60.0, limit)
    } else if !bm25_ranked.is_empty() {
        bm25_ranked.into_iter().take(limit).collect()
    } else {
        dense_ranked.into_iter().take(limit).collect()
    };

    // Step 7: apply per-item span limit.
    let mut per_item_count: std::collections::HashMap<&str, u64> =
        std::collections::HashMap::new();
    let mut selected: Vec<(usize, f64)> = Vec::new();
    for (idx, score) in &ranked {
        let item_key = all_chunks[*idx].item_key.as_str();
        let count = per_item_count.entry(item_key).or_insert(0);
        if *count < options.top_spans_per_item {
            *count += 1;
            selected.push((*idx, *score));
        }
    }

    // Step 8: enrich hits with item metadata.
    let mut meta_cache: std::collections::HashMap<String, Value> =
        std::collections::HashMap::new();
    let mut hits: Vec<Value> = Vec::new();
    for (idx, score) in &selected {
        let chunk = &all_chunks[*idx];
        let meta = if let Some(cached) = meta_cache.get(&chunk.item_key) {
            cached.clone()
        } else {
            let fetched = client
                .call(
                    "items.get",
                    Some(serde_json::json!({"key": chunk.item_key})),
                )
                .unwrap_or(Value::Null);
            meta_cache.insert(chunk.item_key.clone(), fetched.clone());
            fetched
        };
        let title = meta
            .get("title")
            .and_then(Value::as_str)
            .unwrap_or("")
            .to_string();
        let authors = meta
            .get("creators")
            .and_then(Value::as_array)
            .map(|creators| {
                creators
                    .iter()
                    .filter_map(|c| {
                        let last = c.get("lastName").and_then(Value::as_str).unwrap_or("");
                        let first = c.get("firstName").and_then(Value::as_str).unwrap_or("");
                        if last.is_empty() && first.is_empty() {
                            None
                        } else {
                            Some(format!("{last}{first}"))
                        }
                    })
                    .collect::<Vec<_>>()
                    .join(", ")
            })
            .unwrap_or_default();
        let year = meta.get("date").and_then(Value::as_str).unwrap_or("");
        let mut hit = serde_json::json!({
            "item_key": chunk.item_key,
            "chunk_key": chunk.chunk_key,
            "title": title,
            "authors": authors,
            "year": year,
            "text": chunk.text,
            "page_range": chunk.page_range,
            "section_path": chunk.section_path,
            "score": score,
        });
        if options.include_fulltext_spans {
            hit.as_object_mut().unwrap().insert(
                "attachment_key".to_string(),
                Value::String(chunk.attachment_key.clone()),
            );
        }
        hits.push(hit);
    }

    // Step 9: format output.
    if options.output == "jsonl" {
        let mut out = String::new();
        for hit in &hits {
            out.push_str(&serde_json::to_string(hit).map_err(|e| e.to_string())?);
            out.push('\n');
        }
        Ok(out)
    } else {
        let total = hits.len() as u64;
        format_json(
            &normalize_list_envelope(
                serde_json::json!({"items": hits, "total": total}),
                "items",
                Some(options.top_k),
                0,
            ),
            JsonStyle::Pretty,
        )
    }
}

fn rag_status_value(client: &mut impl RpcCaller, collection: &str) -> Result<Value, String> {
    let raw_store_path = rag_store_path(collection);
    if raw_store_path.exists() {
        return rag_status_from_store(collection, &raw_store_path);
    }

    let mut store_candidates = Vec::new();
    let collection_match = find_collection_in_tree(client, collection)?;
    if let Some(collection_node) = collection_match.as_ref() {
        if let Some(name) = collection_node.get("name").and_then(Value::as_str) {
            store_candidates.push(rag_store_path(name));
        }
        if let Some(key) = collection_node.get("key").and_then(Value::as_str) {
            store_candidates.push(rag_store_path(key));
        }
    }
    for store_path in unique_paths(store_candidates) {
        if store_path.exists() {
            return rag_status_from_store(collection, &store_path);
        }
    }

    rag_status_from_zotero_sidecars(client, collection, collection_match)
}

fn unique_paths(paths: Vec<PathBuf>) -> Vec<PathBuf> {
    let mut unique = Vec::new();
    for path in paths {
        if !unique.iter().any(|seen| seen == &path) {
            unique.push(path);
        }
    }
    unique
}

fn rag_status_from_store(collection: &str, store_path: &Path) -> Result<Value, String> {
    let raw = fs::read_to_string(store_path)
        .map_err(|err| format!("read RAG store {}: {err}", store_path.display()))?;
    let store: Value = serde_json::from_str(&raw)
        .map_err(|err| format!("parse RAG store {}: {err}", store_path.display()))?;
    let chunks = store
        .get("chunks")
        .and_then(Value::as_array)
        .cloned()
        .unwrap_or_default();
    let mut item_keys = Vec::<Value>::new();
    for chunk in &chunks {
        let Some(item_key) = chunk.get("item_key") else {
            continue;
        };
        if !item_keys.iter().any(|seen| seen == item_key) {
            item_keys.push(item_key.clone());
        }
    }
    Ok(serde_json::json!({
        "status": "indexed",
        "collection": store.get("collection").and_then(Value::as_str).unwrap_or(collection),
        "collection_key": store.get("collection_key").cloned().unwrap_or(Value::Null),
        "model": store.get("model").cloned().unwrap_or(Value::String("unknown".to_string())),
        "total_chunks": chunks.len(),
        "total_items": item_keys.len(),
        "store_path": store_path.to_string_lossy(),
    }))
}

fn rag_status_from_zotero_sidecars(
    client: &mut impl RpcCaller,
    collection: &str,
    collection_match: Option<Value>,
) -> Result<Value, String> {
    let collection_key = collection_match
        .as_ref()
        .and_then(|node| node.get("key").cloned())
        .ok_or_else(|| format!("COLLECTION_NOT_FOUND: Collection not found: {collection:?}"))?;
    let raw = paginate_rpc(
        client,
        "collections.getItems",
        serde_json::json!({"key": collection_key}),
        500,
    )?;
    let items = raw
        .get("items")
        .and_then(Value::as_array)
        .or_else(|| raw.as_array())
        .ok_or_else(|| "collections.getItems returned non-array/non-items result".to_string())?
        .clone();

    let mut indexed_items = 0usize;
    let mut total_chunks = 0usize;
    for item in &items {
        let item_key = item.get("key").cloned().unwrap_or(Value::Null);
        let chunk_count = sidecar_chunk_count_for_item(client, &item_key)?;
        if chunk_count > 0 {
            indexed_items += 1;
            total_chunks += chunk_count;
        }
    }

    if indexed_items == 0 {
        return Ok(serde_json::json!({
            "status": "not indexed",
            "collection": collection,
            "total_items": items.len(),
            "indexed_items": 0,
        }));
    }

    Ok(serde_json::json!({
        "status": "indexed",
        "collection": collection,
        "total_chunks": total_chunks,
        "total_items": indexed_items,
        "collection_items": items.len(),
        "source": "zotero-sidecar",
    }))
}

fn sidecar_chunk_count_for_item(
    client: &mut impl RpcCaller,
    item_key: &Value,
) -> Result<usize, String> {
    let attachments = client.call(
        "attachments.list",
        Some(serde_json::json!({"parentKey": item_key.clone()})),
    )?;
    let Some(attachments) = attachments.as_array() else {
        return Ok(0);
    };

    let mut count = 0usize;
    for attachment in attachments {
        let Some(path) = attachment.get("path").and_then(Value::as_str) else {
            continue;
        };
        let local = local_path_from_zotero_path(path);
        let Some(dir) = Path::new(&local).parent() else {
            continue;
        };
        let Ok(bytes) = read_machine_artifact_sidecar(dir, MachineArtifactKind::Chunks) else {
            continue;
        };
        let text = String::from_utf8_lossy(&bytes);
        count += text.lines().filter(|line| !line.trim().is_empty()).count();
    }
    Ok(count)
}

fn rag_store_path(collection: &str) -> PathBuf {
    rag_store_root().join(format!("{collection}.json"))
}

fn rag_store_root() -> PathBuf {
    let xdg_data_home = env::var_os("XDG_DATA_HOME")
        .filter(|path| !path.is_empty())
        .map(PathBuf::from);
    let appdata = env::var_os("APPDATA")
        .filter(|path| !path.is_empty())
        .map(PathBuf::from);
    let userprofile = env::var_os("USERPROFILE")
        .filter(|path| !path.is_empty())
        .map(PathBuf::from);
    let home = env::var_os("HOME")
        .filter(|path| !path.is_empty())
        .map(PathBuf::from);

    rag_store_root_for_platform(
        ArtifactStorePlatform::current(),
        xdg_data_home.as_deref(),
        appdata.as_deref(),
        userprofile.as_deref(),
        home.as_deref(),
    )
}

fn rag_store_root_for_platform(
    platform: ArtifactStorePlatform,
    xdg_data_home: Option<&Path>,
    appdata: Option<&Path>,
    userprofile: Option<&Path>,
    home: Option<&Path>,
) -> PathBuf {
    match platform {
        ArtifactStorePlatform::Windows => {
            if let Some(path) = appdata {
                return path.join("Zotron").join("rag");
            }
            if let Some(path) = userprofile {
                return path
                    .join("AppData")
                    .join("Roaming")
                    .join("Zotron")
                    .join("rag");
            }
            if let Some(path) = home {
                return path
                    .join("AppData")
                    .join("Roaming")
                    .join("Zotron")
                    .join("rag");
            }
            PathBuf::from(".zotron").join("rag")
        }
        ArtifactStorePlatform::Macos => {
            if let Some(path) = home {
                return path
                    .join("Library")
                    .join("Application Support")
                    .join("Zotron")
                    .join("rag");
            }
            if let Some(path) = xdg_data_home {
                return path.join("zotron").join("rag");
            }
            PathBuf::from(".zotron").join("rag")
        }
        ArtifactStorePlatform::Linux | ArtifactStorePlatform::Other => xdg_data_home
            .map(|path| path.join("zotron").join("rag"))
            .or_else(|| {
                home.map(|path| path.join(".local").join("share").join("zotron").join("rag"))
            })
            .unwrap_or_else(|| PathBuf::from(".zotron").join("rag")),
    }
}

fn run_push_command(
    json_file: String,
    pdf: Option<String>,
    collection: Option<String>,
    on_duplicate: String,
    dry_run: bool,
    client: &mut impl RpcCaller,
) -> Result<String, String> {
    if !matches!(on_duplicate.as_str(), "skip" | "update" | "create") {
        return Err(format!(
            "INVALID_ARGS: --on-duplicate must be skip|update|create, got {on_duplicate:?}"
        ));
    }

    let payload = if json_file == "-" {
        let mut input = String::new();
        io::stdin()
            .read_to_string(&mut input)
            .map_err(|err| format!("read stdin: {err}"))?;
        input
    } else {
        fs::read_to_string(&json_file).map_err(|err| format!("read {json_file}: {err}"))?
    };
    let item_json = serde_json::from_str::<Value>(&payload)
        .map_err(|err| format!("INVALID_JSON: Could not parse JSON: {err}"))?;

    // Validate required fields
    match item_json.get("itemType").and_then(Value::as_str) {
        Some(s) if !s.is_empty() => {}
        _ => return Err("INVALID_ARGS: input JSON must include a non-empty \"itemType\" field".to_string()),
    }

    if dry_run {
        let collection_key = collection
            .as_deref()
            .map(|name| resolve_collection(client, name))
            .transpose()?;
        return format_json(
            &serde_json::json!({
                "ok": true,
                "dryRun": true,
                "wouldPush": {
                    "title": item_json.get("title").cloned().unwrap_or(Value::Null),
                    "itemType": item_json.get("itemType").cloned().unwrap_or(Value::Null),
                    "collectionKey": collection_key,
                    "pdfPath": pdf,
                    "onDuplicate": on_duplicate,
                }
            }),
            JsonStyle::PythonCompact,
        );
    }

    let result = push_item(
        client,
        &item_json,
        pdf.as_deref(),
        collection.as_deref(),
        &on_duplicate,
    )?;
    format_json(&result, JsonStyle::PythonCompact)
}

fn push_item(
    client: &mut impl RpcCaller,
    item_json: &Value,
    pdf_path: Option<&str>,
    collection: Option<&str>,
    on_duplicate: &str,
) -> Result<Value, String> {
    let pdf_size = if let Some(path) = pdf_path {
        validate_pdf_magic(path)?
    } else {
        0
    };

    let collection_key = match collection {
        Some(name) => resolve_collection(client, name)?,
        None => resolve_current_collection(client)?,
    };

    let dup_id = find_duplicate(client, item_json)?;
    if let Some(dup_id) = dup_id.as_deref().filter(|_| on_duplicate == "skip") {
        if !is_library_root(&collection_key) {
            client.call(
                "collections.addItems",
                Some(serde_json::json!({"key": collection_key, "keys": [dup_id]})),
            )?;
        }
        let mut pdf_attached = false;
        if let Some(path) = pdf_path {
            if !item_has_pdf_attachment(client, dup_id)? {
                attach_pdf(client, dup_id, path)?;
                pdf_attached = true;
            }
        }
        return Ok(push_result(
            "skipped_duplicate",
            Some(dup_id.to_string()),
            pdf_attached,
            if pdf_attached { pdf_size } else { 0 },
            Value::Null,
        ));
    }

    let xpi_payload = to_xpi_payload(item_json, Some(&collection_key));
    let (item_key, status) =
        if let Some(dup_id) = dup_id.as_deref().filter(|_| on_duplicate == "update") {
            let mut params = serde_json::Map::new();
            params.insert("key".to_string(), Value::String(dup_id.to_string()));
            params.insert(
                "fields".to_string(),
                xpi_payload
                    .get("fields")
                    .cloned()
                    .unwrap_or_else(|| serde_json::json!({})),
            );
            if let Some(creators) = xpi_payload.get("creators") {
                params.insert("creators".to_string(), creators.clone());
            }
            if let Some(tags) = xpi_payload.get("tags") {
                params.insert("tags".to_string(), tags.clone());
            }
            client.call("items.update", Some(Value::Object(params)))?;
            (dup_id.to_string(), "updated")
        } else {
            let created = client.call("items.create", Some(xpi_payload))?;
            let key = created
                .get("key")
                .and_then(Value::as_str)
                .ok_or_else(|| format!("items.create returned unexpected shape: {created:?}"))?;
            (key.to_string(), "created")
        };

    let mut pdf_attached = false;
    if let Some(path) = pdf_path {
        if status != "updated" || !item_has_pdf_attachment(client, &item_key)? {
            attach_pdf(client, &item_key, path)?;
            pdf_attached = true;
        }
    }

    if status == "updated" && !is_library_root(&collection_key) {
        client.call(
            "collections.addItems",
            Some(serde_json::json!({"key": collection_key, "keys": [item_key]})),
        )?;
    }

    Ok(push_result(
        status,
        Some(item_key),
        pdf_attached,
        if pdf_attached { pdf_size } else { 0 },
        Value::Null,
    ))
}

fn validate_pdf_magic(path: &str) -> Result<u64, String> {
    let bytes = fs::read(path)
        .map_err(|e| format!("INVALID_PDF: cannot read {path}: {e}"))?;
    if !bytes.starts_with(b"%PDF-") {
        return Err(format!(
            "INVALID_PDF: {path} does not start with %PDF- magic bytes"
        ));
    }
    Ok(bytes.len() as u64)
}

fn resolve_current_collection(client: &mut impl RpcCaller) -> Result<Value, String> {
    let selected = client.call("system.currentCollection", None)?;
    Ok(selected
        .get("key")
        .cloned()
        .unwrap_or_else(|| Value::Number(0.into())))
}

fn find_duplicate(
    client: &mut impl RpcCaller,
    item_json: &Value,
) -> Result<Option<String>, String> {
    if let Some(doi) = item_json
        .get("DOI")
        .and_then(Value::as_str)
        .filter(|doi| !doi.is_empty())
    {
        let hits = client.call("search.byIdentifier", Some(serde_json::json!({"doi": doi})))?;
        if let Some(key) = first_hit_key(&hits) {
            return Ok(Some(key));
        }
    }

    if let Some(title) = item_json
        .get("title")
        .and_then(Value::as_str)
        .filter(|title| title.len() >= 10)
    {
        let hits = client.call(
            "search.quick",
            Some(serde_json::json!({"query": title, "limit": 20})),
        )?;
        if let Some(items) = response_items(&hits) {
            for item in items {
                if item.get("title").and_then(Value::as_str) == Some(title) {
                    if let Some(key) = item.get("key").and_then(Value::as_str) {
                        return Ok(Some(key.to_string()));
                    }
                }
            }
        }
    }

    Ok(None)
}

fn first_hit_key(response: &Value) -> Option<String> {
    response_items(response)?
        .first()?
        .get("key")?
        .as_str()
        .map(ToString::to_string)
}

fn response_items(response: &Value) -> Option<&Vec<Value>> {
    response
        .get("items")
        .and_then(Value::as_array)
        .or_else(|| response.as_array())
}

fn to_xpi_payload(item_json: &Value, collection_key: Option<&Value>) -> Value {
    const NON_FIELD_KEYS: &[&str] = &[
        "itemType",
        "creators",
        "tags",
        "collections",
        "attachments",
        "relations",
        "notes",
        "id",
        "key",
        "version",
    ];

    let mut fields = serde_json::Map::new();
    if let Some(item) = item_json.as_object() {
        for (key, value) in item {
            if !NON_FIELD_KEYS.contains(&key.as_str()) && !value.is_null() && value != "" {
                fields.insert(key.clone(), value.clone());
            }
        }
    }

    let mut payload = serde_json::Map::new();
    payload.insert(
        "itemType".to_string(),
        item_json
            .get("itemType")
            .cloned()
            .unwrap_or_else(|| Value::String("journalArticle".to_string())),
    );
    payload.insert("fields".to_string(), Value::Object(fields));

    if let Some(creators) = item_json.get("creators").and_then(Value::as_array) {
        if !creators.is_empty() {
            payload.insert(
                "creators".to_string(),
                Value::Array(
                    creators
                        .iter()
                        .map(|creator| {
                            let mut c = serde_json::json!({
                                "firstName": creator.get("firstName").and_then(Value::as_str).unwrap_or(""),
                                "lastName": creator.get("lastName").and_then(Value::as_str).unwrap_or(""),
                                "creatorType": creator.get("creatorType").and_then(Value::as_str).unwrap_or("author"),
                            });
                            if let Some(fm) = creator.get("fieldMode").and_then(Value::as_u64) {
                                c["fieldMode"] = Value::from(fm);
                            }
                            c
                        })
                        .collect(),
                ),
            );
        }
    }

    if let Some(tags) = item_json.get("tags").and_then(Value::as_array) {
        if !tags.is_empty() {
            payload.insert(
                "tags".to_string(),
                Value::Array(
                    tags.iter()
                        .map(|tag| tag.get("tag").cloned().unwrap_or_else(|| tag.clone()))
                        .collect(),
                ),
            );
        }
    }

    if let Some(collection_key) = collection_key.filter(|key| !is_library_root(key)) {
        payload.insert(
            "collections".to_string(),
            Value::Array(vec![collection_key.clone()]),
        );
    }

    Value::Object(payload)
}

fn item_has_pdf_attachment(client: &mut impl RpcCaller, item_key: &str) -> Result<bool, String> {
    let attachments = client.call(
        "attachments.list",
        Some(serde_json::json!({"parentKey": item_key})),
    )?;
    Ok(has_pdf_attachment(&attachments))
}

fn attach_pdf(client: &mut impl RpcCaller, item_key: &str, path: &str) -> Result<(), String> {
    client.call(
        "attachments.add",
        Some(serde_json::json!({
            "parentKey": item_key,
            "path": zotero_path(path),
            "title": "Full Text PDF",
        })),
    )?;
    Ok(())
}

fn zotero_path(path: &str) -> String {
    let path = Path::new(path)
        .canonicalize()
        .unwrap_or_else(|_| Path::new(path).to_path_buf())
        .to_string_lossy()
        .into_owned();
    if is_wsl() {
        return ProcessCommand::new("wslpath")
            .arg("-w")
            .arg(&path)
            .output()
            .ok()
            .filter(|output| output.status.success())
            .and_then(|output| String::from_utf8(output.stdout).ok())
            .map(|converted| converted.trim().to_string())
            .filter(|converted| !converted.is_empty())
            .unwrap_or(path);
    }
    path
}

fn is_wsl() -> bool {
    if env::var_os("WSL_DISTRO_NAME").is_some() {
        return true;
    }
    fs::read_to_string("/proc/sys/kernel/osrelease")
        .map(|release| release.to_ascii_lowercase().contains("microsoft"))
        .unwrap_or(false)
}

fn is_library_root(value: &Value) -> bool {
    value.as_i64() == Some(0) || value.as_u64() == Some(0)
}

fn push_result(
    status: &str,
    zotero_item_key: Option<String>,
    pdf_attached: bool,
    pdf_size_bytes: u64,
    error: Value,
) -> Value {
    serde_json::json!({
        "status": status,
        "zotero_item_key": zotero_item_key,
        "pdf_attached": pdf_attached,
        "pdf_size_bytes": pdf_size_bytes,
        "error": error,
    })
}

fn run_search(
    args: SearchArgs,
    client: &mut impl RpcCaller,
) -> Result<(Value, JsonStyle), String> {
    let SearchArgs {
        query, fulltext, author, after, before, journal, tag,
        doi, isbn, issn, collection, limit, offset, ..
    } = args;

    let has_identifier = doi.is_some() || isbn.is_some() || issn.is_some();
    if has_identifier {
        let mut params = serde_json::Map::new();
        if let Some(doi) = doi { params.insert("doi".into(), Value::String(doi)); }
        if let Some(isbn) = isbn { params.insert("isbn".into(), Value::String(isbn)); }
        if let Some(issn) = issn { params.insert("issn".into(), Value::String(issn)); }
        let value = client.call("search.byIdentifier", Some(Value::Object(params)))?;
        return Ok((normalize_list_envelope(value, "items", None, 0), JsonStyle::Pretty));
    }

    if fulltext {
        let query = query.ok_or("INVALID_ARGS: --fulltext requires a search query")?;
        let mut params = serde_json::json!({"query": query, "limit": limit});
        if let (Some(col), Some(map)) = (collection, params.as_object_mut()) {
            map.insert("collection".into(), resolve_collection(client, &col)?);
        }
        let value = client.call("search.fulltext", Some(params))?;
        return Ok((normalize_list_envelope(value, "items", Some(limit), 0), JsonStyle::Pretty));
    }

    let has_filters = author.is_some() || after.is_some() || before.is_some()
        || journal.is_some() || tag.is_some();
    if has_filters {
        let mut conditions: Vec<Value> = Vec::new();
        if let Some(query) = &query {
            conditions.push(serde_json::json!({
                "field": "quicksearch-titleCreatorYear",
                "operator": "contains",
                "value": query,
            }));
        }
        if let Some(author) = author {
            conditions.push(serde_json::json!({
                "field": "creator", "operator": "contains", "value": author,
            }));
        }
        if let Some(after) = after {
            conditions.push(serde_json::json!({
                "field": "date", "operator": "isAfter", "value": after,
            }));
        }
        if let Some(before) = before {
            conditions.push(serde_json::json!({
                "field": "date", "operator": "isBefore", "value": before,
            }));
        }
        if let Some(journal) = journal {
            conditions.push(serde_json::json!({
                "field": "publicationTitle", "operator": "contains", "value": journal,
            }));
        }
        if let Some(tag) = tag {
            conditions.push(serde_json::json!({
                "field": "tag", "operator": "is", "value": tag,
            }));
        }
        let value = client.call(
            "search.advanced",
            Some(serde_json::json!({
                "conditions": conditions,
                "operator": "and",
                "limit": limit,
                "offset": offset,
            })),
        )?;
        return Ok((normalize_list_envelope(value, "items", Some(limit), offset), JsonStyle::Pretty));
    }

    let query = query.ok_or(
        "INVALID_ARGS: provide a search query, or use --doi/--isbn/--issn for identifier lookup"
    )?;
    let value = if let Some(col) = collection {
        let key = resolve_collection(client, &col)?;
        let response = client.call(
            "collections.getItems",
            Some(serde_json::json!({"key": key})),
        )?;
        collection_quick_search_response(&response, &query, limit)
    } else {
        filter_search_artifacts(client.call(
            "search.quick",
            Some(serde_json::json!({"query": query, "limit": limit})),
        )?)
    };
    Ok((normalize_list_envelope(value, "items", Some(limit), 0), JsonStyle::Pretty))
}

fn run_search_management_command(
    command: SearchManagementCommand,
    client: &mut impl RpcCaller,
) -> Result<(Value, JsonStyle), String> {
    match command {
        SearchManagementCommand::SavedSearches { .. } => Ok((
            normalize_list_envelope(client.call("search.savedSearches", None)?, "items", None, 0),
            JsonStyle::Pretty,
        )),
        SearchManagementCommand::CreateSaved {
            name, condition, dry_run, ..
        } => {
            let conditions = condition
                .iter()
                .map(|raw| parse_search_condition(raw))
                .collect::<Result<Vec<_>, _>>()?;
            let params = serde_json::json!({"name": name, "conditions": conditions});
            if dry_run {
                Ok((dry_run_value("search.createSavedSearch", params), JsonStyle::PythonCompact))
            } else {
                Ok((client.call("search.createSavedSearch", Some(params))?, JsonStyle::PythonCompact))
            }
        }
        SearchManagementCommand::DeleteSaved {
            search_key, dry_run, ..
        } => {
            let params = serde_json::json!({"key": search_key});
            if dry_run {
                Ok((dry_run_value("search.deleteSavedSearch", params), JsonStyle::PythonCompact))
            } else {
                Ok((client.call("search.deleteSavedSearch", Some(params))?, JsonStyle::PythonCompact))
            }
        }
    }
}

fn filter_search_artifacts(mut value: Value) -> Value {
    let Some(items) = value.get_mut("items").and_then(Value::as_array_mut) else {
        return value;
    };
    items.retain(|item| match item.get("title").and_then(Value::as_str) {
        Some(title) => !is_zotron_evidence_artifact(title),
        None => true,
    });
    let total_items = items.len() as u64;
    if let Some(total) = value.get_mut("total") {
        *total = Value::from(total_items);
    }
    value
}

fn collection_quick_search_response(response: &Value, query: &str, limit: u64) -> Value {
    let mut matched = collection_items(response)
        .into_iter()
        .filter(|item| !item_is_evidence_artifact(item))
        .filter(|item| quick_item_matches(item, query))
        .collect::<Vec<_>>();
    let total = matched.len() as u64;
    let limit = usize::try_from(limit).unwrap_or(usize::MAX);
    if matched.len() > limit {
        matched.truncate(limit);
    }
    serde_json::json!({"items": matched, "total": total})
}

fn item_is_evidence_artifact(item: &Value) -> bool {
    item.get("title")
        .and_then(Value::as_str)
        .is_some_and(is_zotron_evidence_artifact)
}

fn quick_item_matches(item: &Value, query: &str) -> bool {
    let terms = query
        .split_whitespace()
        .map(|term| term.to_lowercase())
        .filter(|term| !term.is_empty())
        .collect::<Vec<_>>();
    if terms.is_empty() {
        return true;
    }
    let mut haystack = String::new();
    append_search_text(item, &mut haystack);
    let haystack = haystack.to_lowercase();
    terms.iter().all(|term| haystack.contains(term))
}

fn append_search_text(value: &Value, out: &mut String) {
    match value {
        Value::String(text) => {
            out.push(' ');
            out.push_str(text);
        }
        Value::Number(number) => {
            out.push(' ');
            out.push_str(&number.to_string());
        }
        Value::Bool(value) => {
            out.push(' ');
            out.push_str(if *value { "true" } else { "false" });
        }
        Value::Array(items) => {
            for item in items {
                append_search_text(item, out);
            }
        }
        Value::Object(map) => {
            for item in map.values() {
                append_search_text(item, out);
            }
        }
        Value::Null => {}
    }
}

fn parse_search_condition(raw: &str) -> Result<Value, String> {
    let mut parts = raw.split_whitespace();
    let field = parts.next();
    let operator = parts.next();
    let value = parts.collect::<Vec<_>>().join(" ");
    match (field, operator, value.is_empty()) {
        (Some(field), Some(operator), false) => Ok(serde_json::json!({
            "field": field,
            "operator": operator,
            "value": value,
        })),
        _ => Err(format!(
            "INVALID_ARGS: --condition must be 'field operator value', got: {raw:?}"
        )),
    }
}

fn normalize_list_envelope(value: Value, list_key: &str, limit: Option<u64>, offset: u64) -> Value {
    if let Value::Array(arr) = value {
        let total = arr.len() as u64;
        let mut obj = serde_json::Map::new();
        obj.insert(list_key.to_string(), Value::Array(arr));
        obj.insert("total".to_string(), Value::from(total));
        if let Some(limit) = limit {
            obj.insert("limit".to_string(), Value::from(limit));
        }
        obj.insert("offset".to_string(), Value::from(offset));
        obj.insert("hasMore".to_string(), Value::Bool(false));
        return Value::Object(obj);
    }

    let mut obj = match value {
        Value::Object(obj) if obj.contains_key(list_key) => obj,
        other => return other,
    };

    let items_len = obj
        .get(list_key)
        .and_then(Value::as_array)
        .map_or(0, |a| a.len()) as u64;
    let total = obj
        .get("total")
        .and_then(Value::as_u64)
        .unwrap_or(items_len);

    obj.insert("total".to_string(), Value::from(total));
    if let Some(limit) = limit {
        obj.insert("limit".to_string(), Value::from(limit));
    }
    obj.insert("offset".to_string(), Value::from(offset));
    obj.insert(
        "hasMore".to_string(),
        Value::Bool(offset + items_len < total),
    );

    Value::Object(obj)
}

const RPC_PAGINATION_SAFETY_CAP: usize = 10_000;
const RPC_PAGE_LIST_KEYS: [&str; 4] = ["items", "tags", "results", "data"];

fn paginate_rpc(
    client: &mut impl RpcCaller,
    method: &str,
    params: Value,
    page_size: usize,
) -> Result<Value, String> {
    let base = params
        .as_object()
        .ok_or_else(|| "params must be a JSON object".to_string())?;
    let mut out = Vec::new();
    let mut prev_page: Option<Vec<Value>> = None;
    let mut offset = 0usize;

    loop {
        let mut page_params = base.clone();
        page_params.insert("offset".to_string(), Value::Number(offset.into()));
        page_params.insert("limit".to_string(), Value::Number(page_size.into()));
        let response = client.call(method, Some(Value::Object(page_params)))?;

        let page = match extract_page(&response) {
            Some(page) => page,
            None if out.is_empty() => return Ok(response),
            None if response.is_object() => {
                return Err(format!(
                    "paginate: {method:?} returned a non-paginated dict after {} accumulated rows; aborting",
                    out.len()
                ));
            }
            None => {
                return Err(format!(
                    "paginate: {method:?} returned non-list/non-dict shape after {} accumulated rows; aborting",
                    out.len()
                ));
            }
        };

        if prev_page.as_ref() == Some(&page) {
            return Err(format!(
                "paginate: {method:?} returned identical pages — method likely ignores offset; aborting after {} rows",
                out.len()
            ));
        }

        let page_len = page.len();
        out.extend(page.clone());
        if page_len < page_size {
            return Ok(Value::Array(out));
        }
        if out.len() >= RPC_PAGINATION_SAFETY_CAP {
            out.truncate(RPC_PAGINATION_SAFETY_CAP);
            return Ok(Value::Array(out));
        }
        prev_page = Some(page);
        offset += page_size;
    }
}

fn extract_page(response: &Value) -> Option<Vec<Value>> {
    if let Some(page) = response.as_array() {
        return Some(page.clone());
    }
    let object = response.as_object()?;
    for key in RPC_PAGE_LIST_KEYS {
        if let Some(page) = object.get(key).and_then(Value::as_array) {
            return Some(page.clone());
        }
    }
    None
}

fn run_find_pdfs_command(
    client: &mut impl RpcCaller,
    collection: String,
    limit: usize,
) -> Result<(Value, JsonStyle), String> {
    let collection_key = resolve_collection(client, &collection)?;
    let response = client.call(
        "collections.getItems",
        Some(serde_json::json!({"key": collection_key})),
    )?;
    let items = collection_items(&response);

    let mut missing = Vec::new();
    for item in &items {
        let Some(item_key) = item.get("key").and_then(Value::as_str) else {
            continue;
        };
        let attachments = client.call(
            "attachments.list",
            Some(serde_json::json!({"parentKey": item_key})),
        )?;
        if !has_pdf_attachment(&attachments) {
            missing.push(item.clone());
        }
        if limit > 0 && missing.len() >= limit {
            break;
        }
    }

    let mut results = Vec::new();
    for item in &missing {
        let item_key = item
            .get("key")
            .and_then(Value::as_str)
            .ok_or_else(|| "missing item lacks key".to_string())?;
        let response = client.call(
            "attachments.findPDF",
            Some(serde_json::json!({"parentKey": item_key})),
        )?;
        let attachment = response.get("attachment").filter(|value| !value.is_null());
        results.push(serde_json::json!({
            "item_key": item_key,
            "title": item.get("title").cloned().unwrap_or(Value::Null),
            "found": attachment.is_some(),
            "attachment_key": attachment
                .and_then(|attachment| attachment.get("key"))
                .cloned()
                .unwrap_or(Value::Null),
        }));
    }

    Ok((
        serde_json::json!({
            "scanned": items.len(),
            "attempted": missing.len(),
            "results": results,
        }),
        JsonStyle::Pretty,
    ))
}

fn collection_items(response: &Value) -> Vec<Value> {
    if let Some(items) = response.get("items").and_then(Value::as_array) {
        return items.clone();
    }
    response.as_array().cloned().unwrap_or_default()
}

fn has_pdf_attachment(attachments: &Value) -> bool {
    attachments
        .as_array()
        .is_some_and(|attachments| attachments.iter().any(is_pdf_attachment))
}

fn is_pdf_attachment(attachment: &Value) -> bool {
    let content_type = attachment
        .get("contentType")
        .and_then(Value::as_str)
        .unwrap_or_default()
        .to_lowercase();
    let path = attachment
        .get("path")
        .and_then(Value::as_str)
        .unwrap_or_default()
        .to_lowercase();
    matches!(
        content_type.as_str(),
        "application/pdf" | "application/x-pdf"
    ) || path.ends_with(".pdf")
}

fn call_json(
    client: &mut impl RpcCaller,
    method: &str,
    params: Option<Value>,
) -> Result<Value, String> {
    client.call(method, params)
}

fn run_system_command(
    command: SystemCommand,
    client: &mut impl RpcCaller,
) -> Result<(Value, JsonStyle), String> {
    let value = match command {
        SystemCommand::Version { .. } => client.call("system.version", None)?,
        SystemCommand::Libraries { .. } => client.call("system.libraries", None)?,
        SystemCommand::LibraryStats { library, .. } => {
            let params = library.map(|id| serde_json::json!({"id": id}));
            client.call("system.libraryStats", params)?
        }
        SystemCommand::Schema { item_type, .. } => {
            if let Some(item_type) = item_type {
                let fields = client.call("system.itemFields", Some(serde_json::json!({"itemType": item_type})))?;
                let creators = client.call("system.creatorTypes", Some(serde_json::json!({"itemType": item_type})))?;
                let field_names: Vec<Value> = fields.as_array().unwrap_or(&vec![])
                    .iter()
                    .filter_map(|f| f.get("field").cloned())
                    .collect();
                let creator_names: Vec<Value> = creators.as_array().unwrap_or(&vec![])
                    .iter()
                    .filter_map(|c| c.get("creatorType").cloned())
                    .collect();
                serde_json::json!({
                    "itemType": item_type,
                    "fields": field_names,
                    "creatorTypes": creator_names,
                })
            } else {
                let types = client.call("system.itemTypes", None)?;
                let type_names: Vec<Value> = types.as_array().unwrap_or(&vec![])
                    .iter()
                    .filter_map(|t| t.get("itemType").cloned())
                    .collect();
                Value::Array(type_names)
            }
        }
        SystemCommand::CurrentCollection { .. } => client.call("system.currentCollection", None)?,
        SystemCommand::Methods { method, .. } => {
            if let Some(method) = method {
                client.call("system.describe", Some(serde_json::json!({"method": method})))?
            } else {
                client.call("system.listMethods", None)?
            }
        }
    };
    Ok((value, JsonStyle::Pretty))
}

fn run_items_command(
    command: ItemsCommand,
    client: &mut impl RpcCaller,
) -> Result<(Value, JsonStyle), String> {
    let (value, style) = match command {
        ItemsCommand::Add {
            doi,
            isbn,
            from_url,
            file,
            item_type,
            fields,
            collection,
            dry_run,
            ..
        } => {
            if let Some(doi) = doi {
                run_add_identifier_command(client, "items.addByDOI", "doi", doi, collection, dry_run)?
            } else if let Some(isbn) = isbn {
                run_add_identifier_command(client, "items.addByISBN", "isbn", isbn, collection, dry_run)?
            } else if let Some(from_url) = from_url {
                run_add_identifier_command(client, "items.addByURL", "url", from_url, collection, dry_run)?
            } else if let Some(file) = file {
                let mut params = serde_json::json!({"path": zotero_path(&file)});
                maybe_insert_collection(client, &mut params, collection)?;
                run_mutation_command(client, "items.addFromFile", params, dry_run)?
            } else if let Some(item_type) = item_type {
                let parsed_fields = parse_field_options(&fields)?;
                let mut params = serde_json::json!({"itemType": item_type});
                if !parsed_fields.is_empty() {
                    if let Some(map) = params.as_object_mut() {
                        map.insert("fields".to_string(), Value::Object(parsed_fields));
                    }
                }
                run_mutation_command(client, "items.create", params, dry_run)?
            } else {
                return Err("INVALID_ARGS: provide one of --doi, --isbn, --from-url, --file, or --type".into());
            }
        }
        ItemsCommand::Update {
            key,
            fields,
            dry_run,
            ..
        } => {
            let parsed_fields = parse_field_options(&fields)?;
            let mut params = serde_json::json!({"key": key});
            if !parsed_fields.is_empty() {
                if let Some(map) = params.as_object_mut() {
                    map.insert("fields".to_string(), Value::Object(parsed_fields));
                }
            }
            run_mutation_command(client, "items.update", params, dry_run)?
        }
        ItemsCommand::Delete { key, dry_run, .. } => run_mutation_command(
            client,
            "items.delete",
            serde_json::json!({"key": key}),
            dry_run,
        )?,
        ItemsCommand::Trash {
            items, dry_run, ..
        } => {
            if items.len() == 1 {
                run_mutation_command(
                    client,
                    "items.trash",
                    serde_json::json!({"key": items[0]}),
                    dry_run,
                )?
            } else {
                run_mutation_command(
                    client,
                    "items.batchTrash",
                    serde_json::json!({"keys": items}),
                    dry_run,
                )?
            }
        }
        ItemsCommand::Restore { item, dry_run, .. } => run_mutation_command(
            client,
            "items.restore",
            serde_json::json!({"key": item}),
            dry_run,
        )?,
        ItemsCommand::MergeDuplicates { keys, dry_run, .. } => {
            if keys.len() < 2 {
                return Err("INVALID_ARGS: need at least 2 keys to merge".to_string());
            }
            run_mutation_command(
                client,
                "items.mergeDuplicates",
                serde_json::json!({"keys": keys}),
                dry_run,
            )?
        }
        ItemsCommand::AddRelated {
            key,
            target,
            dry_run,
            ..
        } => run_mutation_command(
            client,
            "items.addRelated",
            serde_json::json!({"key": key, "targetKey": target}),
            dry_run,
        )?,
        ItemsCommand::RemoveRelated {
            key,
            target,
            dry_run,
            ..
        } => run_mutation_command(
            client,
            "items.removeRelated",
            serde_json::json!({"key": key, "targetKey": target}),
            dry_run,
        )?,
        ItemsCommand::Get { item, .. } => (
            client.call("items.get", Some(serde_json::json!({"key": item})))?,
            JsonStyle::Pretty,
        ),
        ItemsCommand::List {
            limit,
            offset,
            sort,
            direction,
            trash,
            ..
        } => {
            if trash {
                let value = client.call(
                    "items.getTrash",
                    Some(serde_json::json!({"limit": limit, "offset": offset})),
                )?;
                (normalize_list_envelope(value, "items", Some(limit), offset), JsonStyle::Pretty)
            } else {
                let mut params = serde_json::json!({
                    "limit": limit,
                    "offset": offset,
                    "direction": direction,
                });
                if let (Some(sort), Some(map)) = (sort, params.as_object_mut()) {
                    map.insert("sort".to_string(), Value::String(sort));
                }
                let value = client.call("items.list", Some(params))?;
                (normalize_list_envelope(value, "items", Some(limit), offset), JsonStyle::Pretty)
            }
        }
        ItemsCommand::FindDuplicates { .. } => (
            client.call("items.findDuplicates", None)?,
            JsonStyle::Pretty,
        ),
        ItemsCommand::Recent {
            limit,
            offset,
            recent_type,
            ..
        } => {
            if recent_type != "added" && recent_type != "modified" {
                return Err(format!(
                    "--type must be added or modified, got {recent_type:?}"
                ));
            }
            let value = client.call(
                "items.getRecent",
                Some(
                    serde_json::json!({"limit": limit, "offset": offset, "type": recent_type}),
                ),
            )?;
            (normalize_list_envelope(value, "items", Some(limit), offset), JsonStyle::Pretty)
        }
        ItemsCommand::Fulltext { key, .. } => (
            client.call("items.getFullText", Some(serde_json::json!({"key": key})))?,
            JsonStyle::Pretty,
        ),
        ItemsCommand::Related { key, .. } => (
            normalize_list_envelope(
                client.call("items.getRelated", Some(serde_json::json!({"key": key})))?,
                "items",
                None,
                0,
            ),
            JsonStyle::Pretty,
        ),
        ItemsCommand::CitationKey { key, .. } => (
            client.call("items.citationKey", Some(serde_json::json!({"key": key})))?,
            JsonStyle::Pretty,
        ),
        ItemsCommand::Path { key, .. } => (
            localize_attachment_path_response(
                client.call("attachments.getPath", Some(serde_json::json!({"key": key})))?,
            ),
            JsonStyle::Pretty,
        ),
        ItemsCommand::Attachments { key, offset, .. } => {
            let value = client.call(
                "attachments.list",
                Some(serde_json::json!({"parentKey": key})),
            )?;
            let total = value
                .get("items")
                .and_then(Value::as_array)
                .map_or(0, |a| a.len()) as u64;
            (normalize_list_envelope(value, "items", Some(total), offset), JsonStyle::Pretty)
        }
        ItemsCommand::FindPdfs { collection, limit, .. } => {
            run_find_pdfs_command(client, collection, limit)?
        }
    };
    Ok((value, style))
}

fn run_add_identifier_command(
    client: &mut impl RpcCaller,
    method: &str,
    param_name: &str,
    param_value: String,
    collection: Option<String>,
    dry_run: bool,
) -> Result<(Value, JsonStyle), String> {
    let mut params = Value::Object(serde_json::Map::from_iter([(
        param_name.to_string(),
        Value::String(param_value),
    )]));
    maybe_insert_collection(client, &mut params, collection)?;
    run_mutation_command(client, method, params, dry_run)
}

fn run_mutation_command(
    client: &mut impl RpcCaller,
    method: &str,
    params: Value,
    dry_run: bool,
) -> Result<(Value, JsonStyle), String> {
    let value = if dry_run {
        serde_json::json!({
            "ok": true,
            "dryRun": true,
            "wouldCall": method,
            "wouldCallParams": params,
        })
    } else {
        client.call(method, Some(params))?
    };
    Ok((value, JsonStyle::PythonCompact))
}

fn parse_field_options(fields: &[String]) -> Result<serde_json::Map<String, Value>, String> {
    let mut parsed = serde_json::Map::new();
    for field in fields {
        let (key, value) = field
            .split_once('=')
            .ok_or_else(|| format!("INVALID_ARGS: --field must be key=value, got: {field:?}"))?;
        parsed.insert(key.to_string(), Value::String(value.to_string()));
    }
    Ok(parsed)
}

fn maybe_insert_collection(
    client: &mut impl RpcCaller,
    params: &mut Value,
    collection: Option<String>,
) -> Result<(), String> {
    let Some(collection) = collection else {
        return Ok(());
    };
    let collection = resolve_collection(client, &collection)?;
    let include = match &collection {
        Value::Null => false,
        Value::Number(number) => number.as_i64() != Some(0),
        _ => true,
    };
    if include {
        params
            .as_object_mut()
            .expect("mutation params are always objects")
            .insert("collection".to_string(), collection);
    }
    Ok(())
}

fn run_settings_command(
    command: SettingsCommand,
    client: &mut impl RpcCaller,
) -> Result<(Value, JsonStyle), String> {
    let (value, style) = match command {
        SettingsCommand::Get { key, .. } => (
            client.call("settings.get", Some(serde_json::json!({"key": key})))?,
            JsonStyle::Pretty,
        ),
        SettingsCommand::List { .. } => (client.call("settings.getAll", None)?, JsonStyle::Pretty),
        SettingsCommand::Set {
            pairs,
            file,
            dry_run,
            ..
        } => {
            if let Some(file) = file {
                // --file mode: read JSON and call settings.setAll
                let raw = fs::read_to_string(&file)
                    .map_err(|err| format!("INVALID_JSON: Could not read JSON: {err}"))?;
                let settings: Value = serde_json::from_str(&raw)
                    .map_err(|err| format!("INVALID_JSON: Could not parse JSON: {err}"))?;
                if dry_run {
                    (
                        dry_run_value("settings.setAll", settings),
                        JsonStyle::PythonCompact,
                    )
                } else {
                    (
                        client.call("settings.setAll", Some(settings))?,
                        JsonStyle::PythonCompact,
                    )
                }
            } else if pairs.len() == 2 {
                // Single key=value: settings.set
                let key = &pairs[0];
                let value = &pairs[1];
                let parsed_value = serde_json::from_str::<Value>(value)
                    .unwrap_or(Value::String(value.clone()));
                let params = serde_json::json!({"key": key, "value": parsed_value});
                if dry_run {
                    (
                        dry_run_value("settings.set", params),
                        JsonStyle::PythonCompact,
                    )
                } else {
                    (
                        client.call("settings.set", Some(params))?,
                        JsonStyle::PythonCompact,
                    )
                }
            } else if pairs.len() > 2 && pairs.len() % 2 == 0 {
                // Multiple pairs: build a map and call settings.setAll
                let mut map = serde_json::Map::new();
                for chunk in pairs.chunks(2) {
                    let parsed = serde_json::from_str::<Value>(&chunk[1])
                        .unwrap_or(Value::String(chunk[1].clone()));
                    map.insert(chunk[0].clone(), parsed);
                }
                let settings = Value::Object(map);
                if dry_run {
                    (
                        dry_run_value("settings.setAll", settings),
                        JsonStyle::PythonCompact,
                    )
                } else {
                    (
                        client.call("settings.setAll", Some(settings))?,
                        JsonStyle::PythonCompact,
                    )
                }
            } else {
                return Err(
                    "INVALID_ARGS: provide key value pairs (even number of args) or --file".into(),
                );
            }
        }
    };
    Ok((value, style))
}

fn run_tags_command(
    command: TagsCommand,
    client: &mut impl RpcCaller,
) -> Result<(Value, JsonStyle), String> {
    let (value, style) = match command {
        TagsCommand::List { limit, .. } => {
            let value = client.call("tags.list", Some(serde_json::json!({"limit": limit})))?;
            (normalize_list_envelope(value, "items", Some(limit), 0), JsonStyle::Pretty)
        }
        TagsCommand::Rename {
            old, new, dry_run, ..
        } => run_tag_mutation(
            client,
            "tags.rename",
            serde_json::json!({"oldName": old, "newName": new}),
            dry_run,
        )?,
        TagsCommand::Delete { tag, dry_run, .. } => run_tag_mutation(
            client,
            "tags.delete",
            serde_json::json!({"tag": tag}),
            dry_run,
        )?,
        TagsCommand::Add {
            keys, tags, dry_run, ..
        } => {
            if keys.len() == 1 {
                run_tag_mutation(
                    client,
                    "tags.add",
                    serde_json::json!({"key": keys[0], "tags": tags}),
                    dry_run,
                )?
            } else {
                run_tag_mutation(
                    client,
                    "tags.batchUpdate",
                    serde_json::json!({"keys": keys, "add": tags}),
                    dry_run,
                )?
            }
        }
        TagsCommand::Remove {
            keys, tags, dry_run, ..
        } => {
            if keys.len() == 1 {
                run_tag_mutation(
                    client,
                    "tags.remove",
                    serde_json::json!({"key": keys[0], "tags": tags}),
                    dry_run,
                )?
            } else {
                run_tag_mutation(
                    client,
                    "tags.batchUpdate",
                    serde_json::json!({"keys": keys, "remove": tags}),
                    dry_run,
                )?
            }
        }
    };
    Ok((value, style))
}

fn run_tag_mutation(
    client: &mut impl RpcCaller,
    method: &str,
    params: Value,
    dry_run: bool,
) -> Result<(Value, JsonStyle), String> {
    if dry_run {
        Ok((dry_run_value(method, params), JsonStyle::PythonCompact))
    } else {
        Ok((client.call(method, Some(params))?, JsonStyle::PythonCompact))
    }
}

fn dry_run_value(method: &str, params: Value) -> Value {
    serde_json::json!({
        "ok": true,
        "dryRun": true,
        "wouldCall": method,
        "wouldCallParams": params,
    })
}

fn run_annotations_command(
    command: AnnotationsCommand,
    client: &mut impl RpcCaller,
) -> Result<(Value, JsonStyle), String> {
    let (value, style) = match command {
        AnnotationsCommand::List { parent, attachment, .. } => {
            let mut params = serde_json::json!({"parentKey": parent});
            if let Some(att) = attachment {
                params["attachmentKey"] = Value::String(att);
            }
            let value = client.call("annotations.list", Some(params))?;
            let total = value
                .get("items")
                .and_then(Value::as_array)
                .map_or(0, |a| a.len()) as u64;
            (normalize_list_envelope(value, "items", Some(total), 0), JsonStyle::Pretty)
        }
        AnnotationsCommand::Create {
            parent,
            attachment,
            annotation_type,
            position,
            quote,
            page,
            sort_index,
            text,
            comment,
            color,
            dry_run,
            ..
        } => {
            let annotation_type = annotation_type.unwrap_or_else(|| "highlight".to_string());
            if !matches!(
                annotation_type.as_str(),
                "highlight" | "note" | "underline" | "image" | "ink"
            ) {
                return Err(format!(
                    "INVALID_ARGS: --type must be highlight|note|underline|image|ink, got {annotation_type:?}"
                ));
            }
            let mut params = serde_json::Map::new();
            params.insert("parentKey".to_string(), Value::String(parent));
            if let Some(att) = attachment {
                params.insert("attachmentKey".to_string(), Value::String(att));
            }
            params.insert("type".to_string(), Value::String(annotation_type.clone()));
            params.insert("color".to_string(), Value::String(color));

            if let Some(ref quote_text) = quote {
                if !matches!(annotation_type.as_str(), "highlight" | "underline") {
                    return Err(format!(
                        "INVALID_ARGS: --quote is only valid for highlight|underline, got {annotation_type:?}"
                    ));
                }
                params.insert("quote".to_string(), Value::String(quote_text.clone()));
                if let Some(page_idx) = page {
                    params.insert(
                        "pageIndex".to_string(),
                        Value::Number(page_idx.into()),
                    );
                }
                // When --quote is given, --position is optional
                if let Some(raw) = position {
                    let pos = serde_json::from_str::<Value>(&raw)
                        .map_err(|err| format!("INVALID_JSON: Could not parse --position: {err}"))?;
                    validate_annotation_position(annotation_type.as_str(), &pos)?;
                    params.insert("position".to_string(), pos);
                }
            } else {
                let position = position
                    .ok_or_else(|| "INVALID_ARGS: --position JSON is required (or use --quote)".to_string())
                    .and_then(|raw| {
                        serde_json::from_str::<Value>(&raw)
                            .map_err(|err| format!("INVALID_JSON: Could not parse --position: {err}"))
                    })?;
                validate_annotation_position(annotation_type.as_str(), &position)?;
                params.insert("position".to_string(), position);
            }

            if let Some(sort_index) = sort_index {
                params.insert(
                    "sortIndex".to_string(),
                    parse_annotation_sort_index(sort_index)?,
                );
            }
            if let Some(text) = text {
                params.insert("text".to_string(), Value::String(text));
            }
            if let Some(comment) = comment {
                params.insert("comment".to_string(), Value::String(comment));
            }
            run_mutating_command(client, "annotations.create", Value::Object(params), dry_run)?
        }
        AnnotationsCommand::Delete {
            annotation_key,
            dry_run,
            ..
        } => run_mutating_command(
            client,
            "annotations.delete",
            serde_json::json!({"key": annotation_key}),
            dry_run,
        )?,
    };
    Ok((value, style))
}

fn validate_annotation_position(annotation_type: &str, position: &Value) -> Result<(), String> {
    position
        .get("pageIndex")
        .and_then(Value::as_i64)
        .filter(|value| *value >= 0)
        .ok_or_else(|| {
            "INVALID_ARGS: --position must include a non-negative integer pageIndex".to_string()
        })?;

    if annotation_type == "ink" {
        let has_paths = position
            .get("paths")
            .and_then(Value::as_array)
            .is_some_and(|paths| !paths.is_empty());
        if !has_paths {
            return Err("INVALID_ARGS: ink --position must include non-empty paths".to_string());
        }
        return Ok(());
    }

    let valid_rects = position
        .get("rects")
        .and_then(Value::as_array)
        .is_some_and(|rects| !rects.is_empty() && rects.iter().all(is_annotation_rect));
    if !valid_rects {
        return Err(
            "INVALID_ARGS: --position must include non-empty rects of [x1, y1, x2, y2]".to_string(),
        );
    }
    Ok(())
}

fn is_annotation_rect(value: &Value) -> bool {
    value.as_array().is_some_and(|coords| {
        coords.len() == 4
            && coords
                .iter()
                .all(|coord| coord.as_f64().is_some_and(f64::is_finite))
    })
}

fn parse_annotation_sort_index(raw: String) -> Result<Value, String> {
    let parsed = serde_json::from_str::<Value>(&raw).unwrap_or_else(|_| Value::String(raw));
    let valid = match &parsed {
        Value::Number(number) => number.as_f64().is_some_and(f64::is_finite),
        Value::String(value) => {
            is_zotero_pdf_sort_index(value.trim())
                || (!value.trim().is_empty()
                    && value.trim().parse::<f64>().is_ok_and(f64::is_finite))
        }
        _ => false,
    };
    if valid {
        Ok(parsed)
    } else {
        Err(format!(
            "INVALID_ARGS: --sort-index must be a finite number or numeric string, got {parsed}"
        ))
    }
}

fn is_zotero_pdf_sort_index(value: &str) -> bool {
    let mut parts = value.split('|');
    matches!(
        (parts.next(), parts.next(), parts.next(), parts.next()),
        (Some(page), Some(offset), Some(y), None)
            if page.len() == 5
                && offset.len() == 6
                && y.len() == 5
                && page.chars().all(|ch| ch.is_ascii_digit())
                && offset.chars().all(|ch| ch.is_ascii_digit())
                && y.chars().all(|ch| ch.is_ascii_digit())
    )
}


fn localize_attachment_path_response(mut value: Value) -> Value {
    if let Some(path) = value.get("path").and_then(Value::as_str) {
        let local = local_path_from_zotero_path(path);
        if let Some(map) = value.as_object_mut() {
            map.insert("path".to_string(), Value::String(local));
        }
    }
    value
}

fn run_notes_command(
    command: NotesCommand,
    client: &mut impl RpcCaller,
) -> Result<(Value, JsonStyle), String> {
    let (value, style) = match command {
        NotesCommand::List {
            parent,
            limit,
            offset,
            ..
        } => {
            let value = client.call(
                "notes.list",
                Some(serde_json::json!({"parentKey": parent})),
            )?;
            (normalize_list_envelope(value, "items", Some(limit), offset), JsonStyle::Pretty)
        }
        NotesCommand::Get { note_key, .. } => {
            let value = client.call("notes.get", Some(serde_json::json!({"key": note_key})))?;
            (value, JsonStyle::Pretty)
        }
        NotesCommand::Create {
            parent,
            content,
            tags,
            dry_run,
            ..
        } => {
            let mut params = serde_json::Map::new();
            params.insert("parentKey".to_string(), Value::String(parent));
            params.insert("content".to_string(), Value::String(content));
            if !tags.is_empty() {
                params.insert(
                    "tags".to_string(),
                    Value::Array(tags.into_iter().map(Value::String).collect()),
                );
            }
            run_mutating_command(client, "notes.create", Value::Object(params), dry_run)?
        }
        NotesCommand::Update {
            note_key,
            content,
            dry_run,
            ..
        } => run_mutating_command(
            client,
            "notes.update",
            serde_json::json!({"key": note_key, "content": content}),
            dry_run,
        )?,
        NotesCommand::Delete {
            note_key, dry_run, ..
        } => {
            // Python CLI intentionally routes note deletion through items.delete.
            run_mutating_command(
                client,
                "items.delete",
                serde_json::json!({"key": note_key}),
                dry_run,
            )?
        }
        NotesCommand::Search { query, limit, .. } => {
            let value = client.call(
                "notes.search",
                Some(serde_json::json!({"query": query, "limit": limit})),
            )?;
            (normalize_list_envelope(value, "items", Some(limit), 0), JsonStyle::Pretty)
        }
    };
    Ok((value, style))
}

fn run_mutating_command(
    client: &mut impl RpcCaller,
    method: &str,
    params: Value,
    dry_run: bool,
) -> Result<(Value, JsonStyle), String> {
    if dry_run {
        Ok((
            serde_json::json!({
                "ok": true,
                "dryRun": true,
                "wouldCall": method,
                "wouldCallParams": params,
            }),
            JsonStyle::PythonCompact,
        ))
    } else {
        client
            .call(method, Some(params))
            .map(|value| (value, JsonStyle::PythonCompact))
    }
}

fn run_collections_command(
    command: CollectionsCommand,
    client: &mut impl RpcCaller,
) -> Result<(Value, JsonStyle), String> {
    let value = match command {
        CollectionsCommand::List { .. } => normalize_list_envelope(
            client.call("collections.list", None)?,
            "items",
            None,
            0,
        ),
        CollectionsCommand::Tree { .. } => client.call("collections.tree", None)?,
        CollectionsCommand::Get { name_or_id, .. } => {
            let key = resolve_collection(client, &name_or_id)?;
            client.call("collections.get", Some(serde_json::json!({"key": key})))?
        }
        CollectionsCommand::GetItems {
            name_or_id,
            limit,
            offset,
            ..
        } => {
            let key = resolve_collection(client, &name_or_id)?;
            let mut params = serde_json::json!({"key": key});
            if let Some(map) = params.as_object_mut() {
                if let Some(limit) = limit {
                    map.insert("limit".to_string(), Value::Number(limit.into()));
                }
                if offset > 0 {
                    map.insert("offset".to_string(), Value::Number(offset.into()));
                }
            }
            normalize_list_envelope(
                client.call("collections.getItems", Some(params))?,
                "items",
                limit,
                offset,
            )
        }
        CollectionsCommand::Stats { name_or_id, .. } => {
            let key = resolve_collection(client, &name_or_id)?;
            client.call("collections.stats", Some(serde_json::json!({"key": key})))?
        }
        CollectionsCommand::Rename {
            old_name,
            new_name,
            dry_run,
            ..
        } => {
            let key = resolve_mutable_collection(client, &old_name, "rename")?;
            let params = serde_json::json!({"key": key, "name": new_name});
            if dry_run {
                return Ok((
                    dry_run_value("collections.rename", params),
                    JsonStyle::PythonCompact,
                ));
            }
            return Ok((
                client.call("collections.rename", Some(params))?,
                JsonStyle::PythonCompact,
            ));
        }
        CollectionsCommand::Create {
            name,
            parent,
            dry_run,
            ..
        } => {
            let mut params = serde_json::json!({"name": name});
            if let Some(parent) = parent {
                let parent_key = resolve_mutable_collection(client, &parent, "use as parent")?;
                if let Some(map) = params.as_object_mut() {
                    map.insert("parentKey".to_string(), parent_key);
                }
            }
            if dry_run {
                return Ok((
                    dry_run_value("collections.create", params),
                    JsonStyle::PythonCompact,
                ));
            }
            return Ok((
                client.call("collections.create", Some(params))?,
                JsonStyle::PythonCompact,
            ));
        }
        CollectionsCommand::Delete {
            name_or_id,
            dry_run,
            ..
        } => {
            let key = resolve_mutable_collection(client, &name_or_id, "delete")?;
            let params = serde_json::json!({"key": key});
            if dry_run {
                return Ok((
                    dry_run_value("collections.delete", params),
                    JsonStyle::PythonCompact,
                ));
            }
            return Ok((
                client.call("collections.delete", Some(params))?,
                JsonStyle::PythonCompact,
            ));
        }
        CollectionsCommand::AddItems {
            collection,
            item_keys,
            dry_run,
            ..
        } => {
            let key = resolve_mutable_collection(client, &collection, "add to")?;
            let params = serde_json::json!({"key": key, "keys": item_keys});
            if dry_run {
                return Ok((
                    dry_run_value("collections.addItems", params),
                    JsonStyle::PythonCompact,
                ));
            }
            return Ok((
                client.call("collections.addItems", Some(params))?,
                JsonStyle::PythonCompact,
            ));
        }
        CollectionsCommand::RemoveItems {
            collection,
            item_keys,
            dry_run,
            ..
        } => {
            let key = resolve_mutable_collection(client, &collection, "operate on")?;
            let params = serde_json::json!({"key": key, "keys": item_keys});
            if dry_run {
                return Ok((
                    dry_run_value("collections.removeItems", params),
                    JsonStyle::PythonCompact,
                ));
            }
            return Ok((
                client.call("collections.removeItems", Some(params))?,
                JsonStyle::PythonCompact,
            ));
        }
    };
    Ok((value, JsonStyle::Pretty))
}

fn resolve_export_keys(
    client: &mut impl RpcCaller,
    mut keys: Vec<String>,
    collection: Option<String>,
) -> Result<Vec<String>, String> {
    if let Some(name) = collection {
        let col_key = resolve_collection(client, &name)?;
        let response = client.call(
            "collections.getItems",
            Some(serde_json::json!({"key": col_key})),
        )?;
        let items = collection_items(&response);
        for item in items {
            if let Some(key) = item.get("key").and_then(Value::as_str) {
                if !keys.contains(&key.to_string()) {
                    keys.push(key.to_string());
                }
            }
        }
    }
    if keys.is_empty() {
        return Err("No item keys provided. Pass positional keys and/or --collection.".to_string());
    }
    Ok(keys)
}

fn run_export(args: ExportArgs, client: &mut impl RpcCaller) -> Result<String, String> {
    let keys = resolve_export_keys(client, args.keys, args.collection)?;
    match args.format.as_str() {
        "bibtex" => run_export_content_command(client, "export.bibtex", keys),
        "ris" => run_export_content_command(client, "export.ris", keys),
        "csl-json" => {
            let response =
                client.call("export.cslJson", Some(serde_json::json!({"keys": keys})))?;
            if let Some(content) = response.get("content") {
                format_json(content, JsonStyle::Pretty)
            } else {
                format_json(&response, JsonStyle::PythonCompact)
            }
        }
        "bibliography" => {
            let response = client.call(
                "export.bibliography",
                Some(serde_json::json!({"keys": keys, "style": args.style})),
            )?;
            if let Some(object) = response.as_object() {
                let field = if args.html { "html" } else { "text" };
                if object.contains_key("html") || object.contains_key("text") {
                    return raw_value_output(
                        object.get(field).unwrap_or(&Value::String(String::new())),
                    );
                }
            }
            format_json(&response, JsonStyle::PythonCompact)
        }
        other => Err(format!(
            "INVALID_ARGS: unknown format {other:?}, expected bibtex/ris/csl-json/bibliography"
        )),
    }
}

fn run_export_content_command(
    client: &mut impl RpcCaller,
    method: &str,
    keys: Vec<String>,
) -> Result<String, String> {
    let response = client.call(method, Some(serde_json::json!({"keys": keys})))?;
    if let Some(content) = response.get("content") {
        raw_value_output(content)
    } else {
        format_json(&response, JsonStyle::PythonCompact)
    }
}

fn raw_value_output(value: &Value) -> Result<String, String> {
    let mut out = match value {
        Value::Null => String::new(),
        Value::String(content) => content.clone(),
        other => to_python_repr(other),
    };
    out.push('\n');
    Ok(out)
}

fn to_python_repr(value: &Value) -> String {
    match value {
        Value::Null => "None".to_string(),
        Value::Bool(value) => {
            if *value {
                "True".to_string()
            } else {
                "False".to_string()
            }
        }
        Value::Number(value) => value.to_string(),
        Value::String(value) => format!("'{}'", value.replace('\\', "\\\\").replace('\'', "\\'")),
        Value::Array(values) => {
            let inner = values
                .iter()
                .map(to_python_repr)
                .collect::<Vec<_>>()
                .join(", ");
            format!("[{inner}]")
        }
        Value::Object(entries) => {
            let inner = entries
                .iter()
                .map(|(key, value)| {
                    format!("'{}': {}", key.replace('\'', "\\'"), to_python_repr(value))
                })
                .collect::<Vec<_>>()
                .join(", ");
            format!("{{{inner}}}")
        }
    }
}

fn resolve_collection(client: &mut impl RpcCaller, name_or_id: &str) -> Result<Value, String> {
    let trimmed = name_or_id.trim();
    if let Ok(id) = trimmed.parse::<i64>() {
        return Ok(Value::Number(id.into()));
    }

    let collections = client.call("collections.list", None)?;
    let items = collections
        .get("items")
        .and_then(Value::as_array)
        .or_else(|| collections.as_array())
        .ok_or_else(|| "collections.list returned non-array result".to_string())?;

    if let Some(collection) = items
        .iter()
        .find(|collection| collection.get("key").and_then(Value::as_str) == Some(trimmed))
    {
        return collection_key(collection);
    }

    let exact = items
        .iter()
        .filter(|collection| collection.get("name").and_then(Value::as_str) == Some(trimmed))
        .collect::<Vec<_>>();
    if exact.len() == 1 {
        return collection_key(exact[0]);
    }

    let needle = normalize_collection_name(trimmed);
    let fuzzy = items
        .iter()
        .filter(|collection| {
            collection
                .get("name")
                .and_then(Value::as_str)
                .map(normalize_collection_name)
                .is_some_and(|name| name.contains(&needle))
        })
        .collect::<Vec<_>>();

    match fuzzy.len() {
        1 => collection_key(fuzzy[0]),
        0 => Err(format!(
            "COLLECTION_NOT_FOUND: No collection named {trimmed:?}"
        )),
        _ => Err(format!(
            "COLLECTION_AMBIGUOUS: Multiple collections match {trimmed:?}"
        )),
    }
}

fn collection_key(collection: &Value) -> Result<Value, String> {
    collection
        .get("key")
        .cloned()
        .ok_or_else(|| "collection result is missing key".to_string())
}

fn resolve_mutable_collection(
    client: &mut impl RpcCaller,
    name_or_id: &str,
    operation: &str,
) -> Result<Value, String> {
    let key = resolve_collection(client, name_or_id)?;
    if key.as_i64() == Some(0) {
        return Err(format!(
            "COLLECTION_NOT_FOUND: {name_or_id:?} resolved to library root (cannot {operation})"
        ));
    }
    Ok(key)
}

fn normalize_collection_name(name: &str) -> String {
    name.split_whitespace()
        .collect::<Vec<_>>()
        .join(" ")
        .to_lowercase()
}

fn format_json(value: &Value, style: JsonStyle) -> Result<String, String> {
    let mut out = match style {
        JsonStyle::PythonCompact => to_python_compact_json(value),
        JsonStyle::Pretty => serde_json::to_string_pretty(value).map_err(|err| err.to_string())?,
    };
    out.push('\n');
    Ok(out)
}

fn to_python_compact_json(value: &Value) -> String {
    match value {
        Value::Null => "null".to_string(),
        Value::Bool(value) => value.to_string(),
        Value::Number(value) => value.to_string(),
        Value::String(value) => {
            serde_json::to_string(value).expect("string serialization cannot fail")
        }
        Value::Array(values) => {
            let inner = values
                .iter()
                .map(to_python_compact_json)
                .collect::<Vec<_>>()
                .join(", ");
            format!("[{inner}]")
        }
        Value::Object(entries) => {
            let inner = entries
                .iter()
                .map(|(key, value)| {
                    let key = serde_json::to_string(key).expect("string serialization cannot fail");
                    format!("{key}: {}", to_python_compact_json(value))
                })
                .collect::<Vec<_>>()
                .join(", ");
            format!("{{{inner}}}")
        }
    }
}