zkv 0.3.0

Zero-knowledge encrypted personal vault: a local-first, end-to-end encrypted TUI manager for passwords, notes, and cards.
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
//! 无头(headless)CLI 命令层。对应 PRD §8(可脚本化命令行)。
//!
//! 与 TUI 路径完全解耦:不引用 `app`/`ui`,直接调用 L2/L3 层
//! ([`crate::vault`] / [`crate::store`] / [`crate::search`] / [`crate::clipboard`])。
//!
//! ## 口令来源
//! [`read_passphrase`] 按以下优先级解析口令,全部用 [`zeroize::Zeroizing`] 包裹以避免明文残留:
//! 1. 环境变量 `ZKV_PASSPHRASE`
//! 2. `--passfile <path>` 指定的文件(去掉末尾单个 `\n` / `\r\n`)
//! 3. TTY 交互式提示(`rpassword`)
//!
//! ## 解锁包装
//! [`Unlocked`] 在解锁后持有 `Database` + 派生 `MasterKey` + `KdfParams` + salt,
//! 通过 [`Unlocked::save`] 用已派生 key 落盘(不重跑 Argon2)。
//!
//! ## 命令分层
//! 本模块提供**只读**命令(`ls`/`get`/`search`/`cp`)与**写**命令(`add`/`edit`/`rm`)
//! 的纯函数实现。每个 `run_*` 接收**已类型化**的参数(非 clap 的 `ArgMatches`),
//! 便于单测与 `main.rs` 分发。写命令在变更后立即 `save` 落盘。

use std::io::{Read, Write};
use std::path::{Path, PathBuf};

use zeroize::Zeroizing;

use crate::clipboard;
use crate::crypto::{KdfParams, MasterKey};
use crate::db::Database;
use crate::error::{Error, Result};
use crate::model::{legacy_to_fields, Attachment, Category, Field, FieldKind, Item, LegacyItemData};
use crate::search::{self, Filter};
use crate::style;
use crate::store;
use crate::vault;

/// 解析口令的三种来源,按优先级:环境变量 `ZKV_PASSPHRASE` > `--passfile` > TTY 提示。
///
/// 返回 [`Zeroizing<String>`],避免明文口令在堆上长期残留。
pub fn read_passphrase(passfile: Option<&Path>) -> Result<Zeroizing<String>> {
    // 1. 环境变量(优先级最高,便于 CI/脚本注入)。
    // NOTE: 环境变量本身由调用方负责安全;这里仅在进程内复制一份并 zeroize 包裹。
    if let Some(val) = std::env::var_os("ZKV_PASSPHRASE") {
        let s = val
            .into_string()
            .map_err(|_| Error::Other("ZKV_PASSPHRASE is not valid UTF-8".into()))?;
        return Ok(Zeroizing::new(s));
    }

    // 2. --passfile:读取整个文件,去掉末尾单个换行。
    if let Some(p) = passfile {
        let raw = std::fs::read_to_string(p)
            .map_err(|e| Error::Other(format!("failed to read passfile {}: {e}", p.display())))?;
        return Ok(Zeroizing::new(strip_trailing_newline(raw)));
    }

    // 3. TTY 交互式提示。
    let pass = rpassword::prompt_password("passphrase: ")?;
    Ok(Zeroizing::new(pass))
}

/// 去掉末尾的单个 `\n` 或 `\r\n`。多换行/中间换行保留。
fn strip_trailing_newline(mut s: String) -> String {
    if s.ends_with("\r\n") {
        s.truncate(s.len() - 2);
    } else if s.ends_with('\n') {
        s.pop();
    }
    s
}

/// 读取**新**口令(`passwd` 用),按优先级:
/// 1. 环境变量 `ZKV_NEW_PASSPHRASE`
/// 2. `--new-passfile <path>` 指定的文件(去掉末尾单个 `\n` / `\r\n`)
/// 3. TTY 交互式提示两次(`new passphrase:` / `confirm new passphrase:`),
///    两次不一致返回 [`Error::Other("passphrases do not match")`]
///
/// 返回 [`Zeroizing<String>`],避免明文口令在堆上长期残留。
pub fn read_new_passphrase(new_passfile: Option<&Path>) -> Result<Zeroizing<String>> {
    // 1. 环境变量。
    if let Some(val) = std::env::var_os("ZKV_NEW_PASSPHRASE") {
        let s = val
            .into_string()
            .map_err(|_| Error::Other("ZKV_NEW_PASSPHRASE is not valid UTF-8".into()))?;
        return Ok(Zeroizing::new(s));
    }

    // 2. --new-passfile。
    if let Some(p) = new_passfile {
        let raw = std::fs::read_to_string(p).map_err(|e| {
            Error::Other(format!("failed to read new-passfile {}: {e}", p.display()))
        })?;
        return Ok(Zeroizing::new(strip_trailing_newline(raw)));
    }

    // 3. TTY 交互式:输两次并比对。
    let a = rpassword::prompt_password("new passphrase: ")?;
    let b = rpassword::prompt_password("confirm new passphrase: ")?;
    if a != b {
        return Err(Error::Other("passphrases do not match".into()));
    }
    Ok(Zeroizing::new(a))
}

/// `passwd`:修改主口令。验旧口令 → 用新口令 + 新 salt 重新加密整库。
///
/// 旧口令来源:`ZKV_PASSPHRASE` / `--passfile` / 交互(同 [`read_passphrase`])。
/// 新口令来源:`ZKV_NEW_PASSPHRASE` / `--new-passfile` / 交互输两次。
/// 允许新旧口令相同(不强制区分)。旧口令错 → `change_passphrase` 返回
/// [`Error::BadPassphrase`],经 `?` 上抛,退出非 0。成功打印 `passphrase changed`。
pub fn run_passwd(path: &Path, old_pf: Option<&Path>, new_pf: Option<&Path>) -> Result<()> {
    let old = read_passphrase(old_pf)?;
    let new = read_new_passphrase(new_pf)?;
    vault::change_passphrase(path, old.as_str(), new.as_str())?;
    // 旧口令的派生密钥已随新 salt 失效,丢弃 agent 缓存,下次解锁重新派生种入。
    crate::agent::forget(path);
    println!("{}", style::ok("passphrase changed"));
    Ok(())
}

/// 默认库路径:`~/.zkv/default.zkv`(`$HOME`,Windows 回退 `%USERPROFILE%`)。
///
/// 命令省略 `<path>` 位置参数时使用此路径。仅依赖 `std::env::var_os`,不引入新依赖。
pub fn default_vault_path() -> Result<PathBuf> {
    let home = std::env::var_os("HOME")
        .or_else(|| std::env::var_os("USERPROFILE")) // Windows
        .ok_or_else(|| Error::Other("cannot determine home dir (set $HOME)".into()))?;
    Ok(PathBuf::from(home).join(".zkv").join("default.zkv"))
}

/// 解析可选 path:`None` → [`default_vault_path`]。
///
/// 所有命令的 `path` 位置参数均为 `Option<PathBuf>`(可省略)。为避免 clap
/// 「可选位置参数出现在必填位置参数之前」的 panic,多位置参数命令(id/item/target/...)
/// 一律把标识符放前、`path` 放后(见各子命令定义)。本函数统一把 `None` 路由到默认库。
pub fn resolve_vault_path(p: Option<PathBuf>) -> Result<PathBuf> {
    match p {
        Some(x) => Ok(x),
        None => default_vault_path(),
    }
}

/// 解锁后的库包装:持有 db + 派生 key/kdf/salt,`save` 用已派生 key 落盘。
///
/// `key`/`kdf`/`salt` 设为私有:仅通过 [`Unlocked::save`] 暴露写回能力,
/// 避免调用方误用裸 key。
pub struct Unlocked {
    /// 底层数据库(可借用连接做查询)。
    pub db: Database,
    /// 库文件路径。
    pub path: PathBuf,
    key: MasterKey,
    kdf: KdfParams,
    salt: [u8; 16],
}

/// 无头建库:用口令(env `ZKV_PASSPHRASE`/`--passfile`/交互)创建一个新的空 `.zkv` 库,
/// 不进入 TUI。目标已存在则报错(不覆盖)。
///
/// 与 `new`/`open` 的 TUI 路径完全解耦:适用于 CI/脚本/远程无 TTY 环境。
pub fn run_init(path: &Path, passfile: Option<&Path>) -> Result<()> {
    // 先判重:在派生/加密之前给出清晰错误,而非依赖底层 IO 报错。
    if path.exists() {
        return Err(Error::Other(format!(
            "vault already exists: {} (refusing to overwrite)",
            path.display()
        )));
    }
    let pass = read_passphrase(passfile)?;
    // 默认 KDF(Argon2id 64MiB/3/4),生产级强度;建空库。
    vault::create(path, pass.as_str())?;
    println!(
        "{} {}",
        style::ok("created vault at"),
        path.display()
    );
    Ok(())
}

impl Unlocked {
    /// 解锁 `path`,缓存 key/kdf/salt。
    ///
    /// **agent 快路径**:若 agent 启用且缓存了该库的派生密钥,直接用之解库(跳过 Argon2id)。
    /// 命中且解密失败(库被外部用别的口令重加密过)→ 丢弃缓存,回退正常派生(fail-closed)。
    /// 正常路径派生成功后,把密钥种进 agent 供后续命令复用。
    pub fn unlock(path: &Path, passfile: Option<&Path>) -> Result<Unlocked> {
        // 1. agent 快路径。
        if crate::agent::enabled() {
            if let Some((key, ..)) = crate::agent::try_get_key(path) {
                match vault::unlock_with_key(path, key) {
                    Ok((db, key, kdf, salt)) => {
                        return Ok(Unlocked {
                            db,
                            path: path.to_path_buf(),
                            key,
                            kdf,
                            salt,
                        });
                    }
                    // 缓存密钥解不开(AEAD 失败)→ 视为过期,丢弃后走正常派生。
                    Err(_) => crate::agent::forget(path),
                }
            }
        }
        // 2. 正常路径:读口令 → Argon2id 派生 → 解库。
        let pass = read_passphrase(passfile)?;
        let (db, key, kdf, salt) = vault::unlock_full(path, pass.as_str())?;
        // 3. 种入 agent(若启用),供后续命令跳过 KDF。
        crate::agent::put_key(path, &key, &kdf, salt);
        Ok(Unlocked {
            db,
            path: path.to_path_buf(),
            key,
            kdf,
            salt,
        })
    }

    /// 用已派生 key 落盘(不重跑 Argon2)。
    pub fn save(&self) -> Result<()> {
        vault::save_with_key(&self.path, &self.key, &self.kdf, self.salt, &self.db)
    }
}

/// `ls`/`search` 的过滤参数(已类型化)。`category` 按分类**名称**(运行时解析成 id)。
#[derive(Debug, Clone, Default)]
pub struct ListFilter {
    /// 仅列出该模板 id 的条目。
    pub template_id: Option<String>,
    /// 仅列出挂有这些标签中任意一个的条目。
    pub tags: Vec<String>,
    /// 仅列出该分类名称下的条目(`None` 表示不限)。
    pub category: Option<String>,
    /// FTS5 全文检索串(`None` 表示不限)。
    pub query: Option<String>,
    /// 仅列出收藏(`true` 时透传给 [`search::Filter::favorite_only`])。
    pub favorite_only: bool,
}

/// 把 `ListFilter` + 已解析的 `category_id` 转成 [`search::Filter`]。
fn to_search_filter(list: &ListFilter, category_id: Option<i64>) -> Filter {
    Filter {
        query: list.query.clone(),
        category: category_id,
        tags: list.tags.clone(),
        template_id: list.template_id.clone(),
        favorite_only: list.favorite_only,
    }
}

/// 根据分类名解析其 id;找不到返回 `None`(调用方可决定报错或空结果)。
fn category_id_by_name(conn: &rusqlite::Connection, name: &str) -> Result<Option<i64>> {
    let cats = store::list_categories(conn)?;
    Ok(cats.into_iter().find(|c| c.name == name).and_then(|c| c.id))
}

/// 根据标签名解析其 id;找不到返回 `None`(调用方可决定报错或空结果)。
fn tag_id_by_name(conn: &rusqlite::Connection, name: &str) -> Result<Option<i64>> {
    let tags = store::list_tags(conn)?;
    Ok(tags.into_iter().find(|t| t.name == name).map(|t| t.id))
}

/// 按标题定位条目 id:**exact 命中优先**,否则**唯一前缀匹配**。
///
/// - 精确匹配某条标题 → 返回该 id。
/// - 无精确匹配但有且仅有一条标题以 `query` 为前缀 → 返回该 id。
/// - 多条前缀匹配 → `Error::Other("multiple items match '<T>' ...")`。
/// - 无任何匹配 → `Error::Other("no item matches '<T>'")`。
pub fn find_item_id_by_title(conn: &rusqlite::Connection, query: &str) -> Result<i64> {
    let items = store::list_items(conn)?;
    // exact 优先。
    if let Some(it) = items.iter().find(|i| i.title == query) {
        return Ok(it.id.unwrap_or(-1));
    }
    // 前缀匹配。
    let prefix_matches: Vec<&Item> = items.iter().filter(|i| i.title.starts_with(query)).collect();
    match prefix_matches.len() {
        0 => Err(Error::Other(format!("no item matches '{query}'"))),
        1 => Ok(prefix_matches[0].id.unwrap_or(-1)),
        _ => {
            let names: Vec<&str> = prefix_matches.iter().map(|i| i.title.as_str()).collect();
            Err(Error::Other(format!(
                "multiple items match '{query}': {}",
                names.join(", ")
            )))
        }
    }
}

/// 解析目标 id:位置参数 `id` 优先;否则用 `find` 按标题定位。
/// 二者都缺 → `Error::Other`。用于 get/edit/rm/cp/otp 五处复用。
pub fn resolve_id(
    conn: &rusqlite::Connection,
    id: Option<i64>,
    find: Option<&str>,
) -> Result<i64> {
    if let Some(n) = id {
        return Ok(n);
    }
    if let Some(q) = find {
        return find_item_id_by_title(conn, q);
    }
    Err(Error::Other("need an <id> or --find <TITLE>".into()))
}

// ---------------------------------------------------------------------------
// CLI 表格渲染器(零依赖)
// ---------------------------------------------------------------------------
// 一组把「表头 + 若干行单元格」渲染成对齐表格的小工具,供 ls/search/cat ls/tag ls/
// attach ls 复用。设计要点:
// - **ANSI 感知**:`style::paint` 包出的单元格含真彩色 SGR 转义(`\x1b[…m`),这些字节
//   不占显示宽度,列宽计算时必须剥掉,否则带色列会比实际窄、错位。
// - **宽字符感知**:标题/标签可能含 CJK 或全角字符(显示宽度为 2),用启发式区间判定。
// - 无外部依赖(项目「零新增依赖」精神),仅依赖标准库。

/// 单元格对齐方式。
#[derive(Clone, Copy)]
enum Align {
    Left,
    Right,
}

/// 把「表头 + 数据行」渲染成对齐表格,写到 `out`。
///
/// - `header`:`(列名, 对齐)`;`rows[i][j]` 是第 i 行第 j 列的文本(可含 ANSI 着色)。
/// - 列宽 = 该列「表头 + 全部单元格」的最大**可见**宽度。
/// - 输出形态:表头行(青色)→ 一行 `─` 分隔(弱化色)→ 各数据行;列间两空格、行首一空格。
/// - 被管道/重定向时 `color = false`,单元格为纯文本,表格仍正确对齐(便于日志/复制)。
fn render_table<W: Write>(
    out: &mut W,
    color: bool,
    header: &[(&str, Align)],
    rows: &[Vec<String>],
) -> Result<()> {
    let ncols = header.len();
    // 1. 求各列可见宽度。
    let mut widths = vec![0usize; ncols];
    for (i, (label, _)) in header.iter().enumerate() {
        widths[i] = widths[i].max(display_width(label));
    }
    for row in rows {
        for (i, cell) in row.iter().enumerate() {
            if i < ncols {
                widths[i] = widths[i].max(display_width(cell));
            }
        }
    }

    // 2. 表头行(整体着色为 key/青)。
    let mut header_line = String::from(" ");
    for (i, (label, align)) in header.iter().enumerate() {
        if i > 0 {
            header_line.push_str("  ");
        }
        header_line.push_str(&pad(label, widths[i], *align));
    }
    writeln!(
        out,
        "{}",
        style::paint(color, &["key"], header_line.trim_end())
    )?;

    // 3. 分隔线:每列一段 `─`(弱化色),宽度对齐表头。
    let mut sep = String::from(" ");
    for (i, w) in widths.iter().enumerate() {
        if i > 0 {
            sep.push_str("  ");
        }
        sep.push_str(&"".repeat(*w));
    }
    writeln!(out, "{}", style::paint(color, &["muted"], &sep))?;

    // 4. 数据行:单元格原样(含调用方着色),按列对齐补空格。
    for row in rows {
        let mut line = String::from(" ");
        for (i, (w, (_, align))) in widths.iter().zip(header.iter()).enumerate() {
            if i > 0 {
                line.push_str("  ");
            }
            let cell = row.get(i).map(String::as_str).unwrap_or("");
            line.push_str(&pad(cell, *w, *align));
        }
        writeln!(out, "{}", line.trim_end())?;
    }
    Ok(())
}

/// 把 `s` 补到可见宽度 `width`:`Left` 右补空格,`Right` 左补空格。
fn pad(s: &str, width: usize, align: Align) -> String {
    let gap = width.saturating_sub(display_width(s));
    match align {
        Align::Left => format!("{s}{}", " ".repeat(gap)),
        Align::Right => format!("{}{s}", " ".repeat(gap)),
    }
}

/// 字符串的**可见**宽度:剥掉 ANSI CSI 转义后,按字符宽度求和。
///
/// CSI 形如 `\x1b[38;2;r;g;bm` / `\x1b[0m`;其参数字节均为 ASCII(< 0x80),
/// 故逐字节跳过不会落到多字节 UTF-8 中间,`i` 始终停在字符边界。
fn display_width(s: &str) -> usize {
    let bytes = s.as_bytes();
    let mut width = 0usize;
    let mut i = 0usize;
    while i < bytes.len() {
        // ANSI CSI:ESC '[' ... <0x40..=0x7E 终止符>。
        if bytes[i] == 0x1b && i + 1 < bytes.len() && bytes[i + 1] == b'[' {
            i += 2;
            while i < bytes.len() && !(0x40..=0x7e).contains(&bytes[i]) {
                i += 1;
            }
            if i < bytes.len() {
                i += 1; // 跳过终止符。
            }
            continue;
        }
        // 解码一个 UTF-8 字符。SAFETY:`i` 在字符边界(见上),`s` 为合法 UTF-8。
        let ch = s[i..].chars().next().unwrap();
        width += char_width(ch);
        i += ch.len_utf8();
    }
    width
}

/// 单个字符的显示宽度:控制符 0、ASCII 1、CJK/全角/emoji 启发式为 2、其余 1。
fn char_width(c: char) -> usize {
    if c.is_control() {
        return 0;
    }
    let u = c as u32;
    if u < 0x80 {
        return 1;
    }
    if is_wide(u) {
        2
    } else {
        1
    }
}

/// 宽字符区间启发式(覆盖常见 CJK / 全角 / emoji,无需 unicode-width 依赖)。
fn is_wide(u: u32) -> bool {
    matches!(
        u,
        0x1100..=0x115F   // Hangul Jamo
        | 0x2E80..=0x303E // CJK 部首 / 标点
        | 0x3041..=0x33FF // 假名 / 谚文兼容 / CJK 符号
        | 0x3400..=0x4DBF // CJK 扩展 A
        | 0x4E00..=0x9FFF // CJK 统一表意文字
        | 0xA000..=0xA4CF // 彝文
        | 0xAC00..=0xD7A3 // 谚文音节
        | 0xF900..=0xFAFF // CJK 兼容表意
        | 0xFE30..=0xFE4F // CJK 兼容形式
        | 0xFF00..=0xFF60 // 全角 ASCII
        | 0xFFE0..=0xFFE6 // 全角符号
        | 0x1F300..=0x1FAFF // emoji / 符号
        | 0x20000..=0x3FFFD // CJK 扩展 B–F
    )
}

/// Unix 日数 → (年, 月[1-12], 日[1-31])。Howard Hinnant 的 civil_from_days,
/// 纯整数、无闰年查表、对负日数(epoch 之前)亦正确。
fn civil_from_days(z: i64) -> (i64, u32, u32) {
    let z = z + 719468;
    let era = if z >= 0 { z } else { z - 146096 } / 146097;
    let doe = z - era * 146097; // [0, 146096]
    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; // [0, 399]
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // [0, 365]
    let mp = (5 * doy + 2) / 153; // [0, 11]
    let d = (doy - (153 * mp + 2) / 5 + 1) as u32; // [1, 31]
    let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32; // [1, 12]
    let y = if m <= 2 { y + 1 } else { y };
    (y, m, d)
}

/// Unix 秒(UTC)→ `YYYY-MM-DD HH:MM`。UTC 无时区依赖、确定性;机器解析请用 `--json`。
fn fmt_timestamp(secs: i64) -> String {
    let days = secs.div_euclid(86400);
    let tod = secs.rem_euclid(86400);
    let (y, m, d) = civil_from_days(days);
    let hh = tod / 3600;
    let mm = (tod % 3600) / 60;
    format!("{y:04}-{m:02}-{d:02} {hh:02}:{mm:02}")
}

/// `ls`/`search` 公用:把条目列表格式化后写到 `out`。
///
/// - `json = true`:`serde_json::to_string_pretty`(`Item` 已 derive `Serialize`)。
/// - 否则:人类可读,渲染为对齐表格(ID/TYPE/TITLE/TAGS/UPDATED)。
fn write_items<W: Write>(out: &mut W, items: &[Item], json: bool) -> Result<()> {
    if json {
        let s = serde_json::to_string_pretty(items)?;
        writeln!(out, "{s}")?;
        return Ok(());
    }
    // 仅人类可读模式着色;json 仅供机器解析,保持纯净。被管道/重定向时 c=false 自动关闭。
    let c = style::stdout_enabled();
    if items.is_empty() {
        writeln!(out, "{}", style::paint(c, &["muted"], "(no items)"))?;
        return Ok(());
    }
    let header = [
        ("ID", Align::Right),
        ("TYPE", Align::Left),
        ("TITLE", Align::Left),
        ("TAGS", Align::Left),
        ("UPDATED", Align::Right),
    ];
    let rows: Vec<Vec<String>> = items
        .iter()
        .map(|it| {
            let id = it.id.unwrap_or(-1);
            let tags = if it.tags.is_empty() {
                String::from("-")
            } else {
                it.tags.join(", ")
            };
            vec![
                style::paint(c, &["id"], &id.to_string()),
                style::paint(c, &["key"], &it.template_id),
                it.title.clone(),
                style::paint(c, &["muted"], &tags),
                style::paint(c, &["muted"], &fmt_timestamp(it.updated_at)),
            ]
        })
        .collect();
    render_table(out, c, &header, &rows)
}

// ---------------------------------------------------------------------------
// 字段提取(供 get/cp 复用)
// ---------------------------------------------------------------------------

/// 按 `field` 名提取条目的字段值(数据驱动)。
///
/// 特殊名:
/// - `title` → item.title
/// - `type` → item.template_id
/// - `totp` / `otp` → 首个 kind=Totp 字段的值
///
/// 其余按 name 在 `item.fields` 中查首个匹配。未找到返回 [`Error::Other`]。
pub fn item_field(item: &Item, field: &str) -> Result<String> {
    match field {
        "title" => return Ok(item.title.clone()),
        "type" => return Ok(item.template_id.clone()),
        "totp" | "otp" => {
            return item
                .totp_value()
                .map(|s| s.to_string())
                .ok_or_else(|| Error::Other(format!("field '{field}' not found")));
        }
        _ => {}
    }
    item.field_value(field)
        .map(|s| s.to_string())
        .ok_or_else(|| Error::Other(format!("field '{field}' not found")))
}

/// 解析 `otpauth://totp/<label>?secret=<BASE32>&...` URI,返回 secret(base32)。
///
/// 容错:
/// - 不以 `otpauth://` 开头 → [`Error::Other`]。
/// - 无 `secret=` 查询参数(或值为空)→ [`Error::Other`]。
///
/// 实现纯字符串解析(不引入新依赖):取 `?` 后的 query,按 `&` 分割找 `secret=...`;
/// 对 secret 值做最小 percent-decode(把 `%XX` 还原),实际 base32 secret 一般无特殊字符,
/// 但此处仍容忍 `%2B` 之类的转义。
pub fn parse_otpauth(uri: &str) -> Result<String> {
    let lower_prefix = "otpauth://";
    let rest = uri
        .strip_prefix(lower_prefix)
        .ok_or_else(|| Error::Other("otpauth: uri must start with 'otpauth://'".into()))?;
    // 取 query 段(`?` 之后);若无 `?` 则无 secret。
    let query = match rest.split_once('?') {
        Some((_, q)) => q,
        None => {
            return Err(Error::Other(
                "otpauth: uri missing '?' (no query / no secret)".into(),
            ));
        }
    };
    // 查找 secret= 参数。query 可能含 `#fragment`,先裁掉。
    let query = query.split('#').next().unwrap_or(query);
    for pair in query.split('&') {
        if let Some(val) = pair.strip_prefix("secret=") {
            let decoded = percent_decode_minimal(val);
            if decoded.is_empty() {
                return Err(Error::Other("otpauth: empty secret".into()));
            }
            return Ok(decoded);
        }
    }
    Err(Error::Other("otpauth: uri missing 'secret=' parameter".into()))
}

/// 最小 percent-decoding:把 `%XX`(十六进制)还原成对应字节;非法转义原样保留。
fn percent_decode_minimal(s: &str) -> String {
    let bytes = s.as_bytes();
    let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'%' && i + 2 < bytes.len() {
            if let (Some(h), Some(l)) = (hex_digit(bytes[i + 1]), hex_digit(bytes[i + 2])) {
                out.push(h * 16 + l);
                i += 3;
                continue;
            }
        }
        // `+` 在 query 里通常表示空格,但 secret 中 `+` 非合法 base32,保留原样更安全。
        out.push(bytes[i]);
        i += 1;
    }
    String::from_utf8_lossy(&out).into_owned()
}

/// 把单个十六进制字符转成 0–15,非法返回 `None`。
fn hex_digit(b: u8) -> Option<u8> {
    match b {
        b'0'..=b'9' => Some(b - b'0'),
        b'a'..=b'f' => Some(b - b'a' + 10),
        b'A'..=b'F' => Some(b - b'A' + 10),
        _ => None,
    }
}

// ===========================================================================
// 二维码导入(2FA):从图片(本地文件 / 远程 URL / data: URL)解码出 otpauth:// URI。
// 复用现有 --otpauth 管线 —— 本节只负责「图像字节 → otpauth 文本」这一段,
// 产物最终喂给 run_add/run_edit 内现有的 parse_otpauth。
// ===========================================================================

/// 单次 HTTP 取图的大小上限(8 MiB)。二维码图片远小于此;超限即视为异常并拒绝。
const QR_FETCH_MAX_BYTES: u64 = 8 * 1024 * 1024;
/// HTTP 取图超时(秒)。避免 hang 在无响应 / 慢响应的 URL 上。
const QR_FETCH_TIMEOUT_SECS: u64 = 15;

/// 从图像字节中解码出首个 `otpauth://` 二维码,返回其原始 URI 文本。
///
/// 内部:`image::load_from_memory` → 灰度(`GrayImage`)→ `rqrr::PreparedImage` →
/// `detect_grids` → 逐个 `decode()`,返回首个以 `otpauth://` 开头的 payload。
///
/// 错误(均 → [`Error::Other`]):图像解码失败、图中无二维码、二维码内容不是 otpauth。
/// 由 [`resolve_totp_source`] 在 `--qr` / `--qr-url` 时调用。
pub fn otpauth_from_qr_bytes(bytes: &[u8]) -> Result<String> {
    // 1) 解码图像 → 灰度(支持 PNG/JPEG,由 image 的 features 决定)。
    let img = image::load_from_memory(bytes)
        .map_err(|e| Error::Other(format!("decode image: {e}")))?;
    let gray = img.to_luma8();

    // 2) rqrr 找出图中所有二维码网格并逐个解码,取首个 otpauth payload。
    let mut prepared = rqrr::PreparedImage::prepare(gray);
    for grid in prepared.detect_grids() {
        if let Ok((_meta, content)) = grid.decode() {
            if content.starts_with("otpauth://") {
                return Ok(content);
            }
        }
    }
    Err(Error::Other(
        "no otpauth qr found in image (no qr, or qr payload is not an otpauth uri)".into(),
    ))
}

/// 从 URL 取回图像字节。支持 `http`/`https`(经 ureq,blocking)与 `data:`(就地解码,不联网)。
///
/// 安全约束:15s 超时、8 MiB 大小上限、跟随重定向;非 http/https/data 的 scheme 一律拒绝
/// (避免 `file:`/`ftp:` 等被意外拉取本地资源)。
pub fn fetch_url_bytes(url: &str) -> Result<Vec<u8>> {
    // data: URL:就地解析,不触发网络。
    if let Some(rest) = url.strip_prefix("data:") {
        return decode_data_url(rest);
    }
    // 仅允许 http/https。
    if !url.starts_with("http://") && !url.starts_with("https://") {
        return Err(Error::Other(format!(
            "unsupported url scheme (use http/https/data): {url}"
        )));
    }

    let resp = ureq::get(url)
        .timeout(std::time::Duration::from_secs(QR_FETCH_TIMEOUT_SECS))
        .call()
        .map_err(|e| Error::Other(format!("fetch {url}: {e}")))?;

    // 流式读取,截断到 MAX+1 以便判断是否超限。
    let reader = resp.into_reader();
    let mut buf = Vec::new();
    reader
        .take(QR_FETCH_MAX_BYTES + 1)
        .read_to_end(&mut buf)
        .map_err(|e| Error::Other(format!("read body {url}: {e}")))?;
    if buf.len() as u64 > QR_FETCH_MAX_BYTES {
        return Err(Error::Other(format!(
            "image too large (>{QR_FETCH_MAX_BYTES} bytes): {url}"
        )));
    }
    Ok(buf)
}

/// 解析 `data:[<mediatype>][;base64],<data>` 的 payload 部分。
///
/// 取首个 `,` 之后的内容;meta 段以 `;base64` 结尾则按 base64 解码,否则按原始字节(URL
/// 解码后的文本)。base64 解码复用 `data_encoding::BASE64`(与 base32 同 crate,无新依赖),
/// 并容忍缺失的 `=` 填充。
fn decode_data_url(rest: &str) -> Result<Vec<u8>> {
    let (meta, payload) = rest
        .split_once(',')
        .ok_or_else(|| Error::Other("data: url missing ',' payload".into()))?;
    if meta.ends_with(";base64") {
        let pad = (4 - (payload.len() % 4)) % 4;
        let padded = format!("{payload}{:=<pad$}", "");
        data_encoding::BASE64
            .decode(padded.as_bytes())
            .map_err(|e| Error::Other(format!("decode data: base64: {e}")))
    } else {
        Ok(payload.as_bytes().to_vec())
    }
}

/// 把三个互斥的 2FA 来源(`--otpauth` / `--qr` / `--qr-url`)解析成一条 otpauth:// URI(或 None)。
///
/// - `--otpauth`:已是文本 URI,原样透传。
/// - `--qr <path>`:读本地图片字节 → [`otpauth_from_qr_bytes`]。
/// - `--qr-url <url>`:[`fetch_url_bytes`] 取图字节 → [`otpauth_from_qr_bytes`]。
///
/// 三者由 clap `conflicts_with_all` 保证互斥;此处防御性地「至多一个非空」。
/// 产物(otpauth URI)最终在 [`run_add`]/[`run_edit`] 内走现有 [`parse_otpauth`] 管线。
pub fn resolve_totp_source(
    otpauth: Option<&str>,
    qr_path: Option<&Path>,
    qr_url: Option<&str>,
) -> Result<Option<String>> {
    if let Some(uri) = otpauth {
        return Ok(Some(uri.to_string()));
    }
    if let Some(path) = qr_path {
        let bytes = std::fs::read(path)
            .map_err(|e| Error::Other(format!("read qr image {}: {e}", path.display())))?;
        return Ok(Some(otpauth_from_qr_bytes(&bytes)?));
    }
    if let Some(url) = qr_url {
        let bytes = fetch_url_bytes(url)?;
        return Ok(Some(otpauth_from_qr_bytes(&bytes)?));
    }
    Ok(None)
}

/// `edit`/`add` 的单字段覆盖集合:`--set name=value`(可重复)。
///
/// 按 name 写入:存在同名字段则更新值;不存在则**追加一个 Text 字段**(kind/protected
/// 取决于语义,默认 Text)。与整块 `--data` 互斥。
#[derive(Debug, Default, Clone)]
pub struct EditFields {
    /// (name, value) 有序集合,后者覆盖前者。
    pub sets: Vec<(String, String)>,
}

impl EditFields {
    /// 是否提供了任一 `--set`。
    pub fn any(&self) -> bool {
        !self.sets.is_empty()
    }

    /// 按 name 写入 `item.fields`:存在则更新值(并继承其 kind/protected);
    /// 不存在则追加一个 Text 字段。返回是否实际改动。
    pub fn apply(&self, item: &mut Item) -> bool {
        if self.sets.is_empty() {
            return false;
        }
        let mut changed = false;
        for (name, value) in &self.sets {
            if let Some(f) = item.fields.iter_mut().find(|f| &f.name == name) {
                f.value = value.clone();
            } else {
                let kind = FieldKind::Text;
                item.fields.push(Field {
                    name: name.clone(),
                    value: value.clone(),
                    kind,
                    protected: matches!(kind, FieldKind::Secret | FieldKind::Totp),
                });
            }
            changed = true;
        }
        changed
    }
}

/// 标签增量编辑:`add` 末尾追加(去重),`remove` 移除匹配项。二者均可为空。
#[derive(Debug, Default, Clone)]
pub struct TagDelta {
    /// 末尾追加的标签(已去重)。
    pub add: Vec<String>,
    /// 要移除的标签。
    pub remove: Vec<String>,
}

impl TagDelta {
    /// 是否提供了任一增删。
    pub fn any(&self) -> bool {
        !self.add.is_empty() || !self.remove.is_empty()
    }

    /// 应用到 tags:`add` 去重追加,`remove` 移除。返回新 tags。
    pub fn apply(&self, tags: &[String]) -> Vec<String> {
        let mut out: Vec<String> = tags.to_vec();
        // 先移除。
        if !self.remove.is_empty() {
            out.retain(|t| !self.remove.iter().any(|r| r == t));
        }
        // 再去重追加。
        for t in &self.add {
            if !out.iter().any(|e| e == t) {
                out.push(t.clone());
            }
        }
        out
    }
}

// ---------------------------------------------------------------------------
// 写命令(add/edit/rm)
// ---------------------------------------------------------------------------

/// 解析 `--data` 兼容 JSON 为 `(template_id, Vec<Field>)`。
///
/// 兼容顺序:
/// 1. 新形状 `Vec<Field>`(数组):template_id 取 `default_template`。
/// 2. 新形状 `Item` JSON(含 `template_id`+`fields`):取其 template_id + fields。
/// 3. 旧形状 `{"type":...,...}`(legacy ItemData):经 `legacy_to_fields` 转换。
///
/// 三者都失败返回原解析错误。
fn parse_item_data(data_json: &str, default_template: &str) -> Result<(String, Vec<Field>)> {
    // 1. Vec<Field>。
    if let Ok(fields) = serde_json::from_str::<Vec<Field>>(data_json) {
        return Ok((default_template.to_string(), fields));
    }
    // 2. 新 Item JSON(部分:仅取 template_id + fields)。
    #[derive(serde::Deserialize)]
    struct ItemShape {
        #[serde(default)]
        template_id: Option<String>,
        #[serde(default)]
        fields: Vec<Field>,
    }
    if let Ok(shape) = serde_json::from_str::<ItemShape>(data_json) {
        if !shape.fields.is_empty() || shape.template_id.is_some() {
            let tpl = shape
                .template_id
                .unwrap_or_else(|| default_template.to_string());
            return Ok((tpl, shape.fields));
        }
    }
    // 3. legacy。
    let legacy: LegacyItemData = serde_json::from_str(data_json)?;
    Ok(legacy_to_fields(legacy))
}

/// `add`:新增一条条目。
///
/// `data_json`(可选):兼容新旧形状(见 [`parse_item_data`])。为空时用 `template` 实例化空字段。
/// `sets`:额外 `--set name=value` 覆盖。
/// `gen_password = Some(len)`:覆盖 `name=="password"` 的 Secret 字段(任意模板)。
/// `otpauth = Some(uri)`:覆盖首个 kind=Totp 字段(任意模板)。
///
/// 成功后向 stdout 打印 `added item <id>: <title>` 并返回新 id。
/// 若用了 `--gen-password`,生成的明文密码打到 **stderr**,不污染 stdout。
#[allow(clippy::too_many_arguments)]
pub fn run_add(
    u: &Unlocked,
    title: &str,
    template: &str,
    data_json: Option<&str>,
    sets: &EditFields,
    tags: Vec<String>,
    favorite: bool,
    gen_password: Option<usize>,
    otpauth: Option<&str>,
) -> Result<i64> {
    // 基础 fields:优先 --data(兼容新旧形状),否则实例化 template 空字段。
    let (template_id, fields) = match data_json {
        Some(j) if !j.trim().is_empty() => parse_item_data(j, template)?,
        _ => (
            template.to_string(),
            crate::model::instantiate_template(template).unwrap_or_default(),
        ),
    };

    let mut draft = Item {
        id: None,
        template_id,
        title: title.into(),
        category_id: None,
        fields,
        favorite,
        tags,
        created_at: 0,
        updated_at: 0,
    };

    // --set 覆盖。
    sets.apply(&mut draft);

    // --gen-password:覆盖 name=="password" 的 Secret 字段。
    let generated = if let Some(len) = gen_password {
        let pw = generate_password(len, true, true)?;
        let target = draft
            .fields
            .iter_mut()
            .find(|f| f.name == "password" && f.kind == FieldKind::Secret);
        match target {
            Some(f) => {
                f.value = pw.clone();
            }
            None => {
                return Err(Error::Other(
                    "--gen-password needs a 'password' Secret field".into(),
                ));
            }
        }
        Some(pw)
    } else {
        None
    };

    // --otpauth:覆盖首个 kind=Totp 字段。
    if let Some(uri) = otpauth {
        let secret = parse_otpauth(uri)?;
        let target = draft.fields.iter_mut().find(|f| f.kind == FieldKind::Totp);
        match target {
            Some(f) => f.value = secret,
            None => {
                return Err(Error::Other("--otpauth needs a Totp field".into()));
            }
        }
    }

    let id = store::insert_item(u.db.conn(), &mut draft)?;
    u.save()?;
    println!(
        "{} {}: {}",
        style::ok("added item"),
        style::id_text(&id.to_string()),
        title
    );
    if let Some(pw) = generated {
        eprintln!(
            "{}",
            style::warn(&format!("generated password for item {id}: {pw}"))
        );
    }
    // 提供了 TOTP 来源(--otpauth / --qr / --qr-url / --set totp=)时,向 stderr 打印实时码确认。
    if otpauth.is_some() || sets.sets.iter().any(|(n, _)| n == "totp") {
        eprint_totp_hint(&draft);
    }
    Ok(id)
}

// ---------------------------------------------------------------------------
// 密码生成
// ---------------------------------------------------------------------------

/// 易混字符集(肉眼难分辨),`--no-ambiguous` 时从字符池剔除。
const AMBIGUOUS_CHARS: &[u8] = b"0Oo1lI|5S2ZB8";

/// 安全可见符号集(避免引号/反斜杠/空格,降低 shell/复制问题)。
const SYMBOL_CHARS: &[u8] = b"!@#$%^&*()-_=+[]{};:,.?/";

/// 用 CSPRNG(getrandom)生成强随机密码。
///
/// - `symbols = true` → 含 [`SYMBOL_CHARS`] 符号;`false` 仅字母 + 数字。
/// - `avoid_ambiguous = true` → 从池中剔除 [`AMBIGUOUS_CHARS`] 中的易混字符。
/// - 每个字符用**拒绝采样**(rejection sampling)从池中取,避免模偏:
///   随机字节 `>= floor(256/pool.len())*pool.len()` 时丢弃、重取。
/// - `length < 4` 或 `> 1024` 报 [`Error::Other`]。
pub fn generate_password(length: usize, symbols: bool, avoid_ambiguous: bool) -> Result<String> {
    if length < 4 {
        return Err(Error::Other("password length too short (min 4)".into()));
    }
    if length > 1024 {
        return Err(Error::Other("password length too long (max 1024)".into()));
    }

    // 构建字符池:a-z A-Z 0-9,(可选)符号。
    let mut pool: Vec<u8> = Vec::with_capacity(26 * 2 + 10 + SYMBOL_CHARS.len());
    pool.extend(b'a'..=b'z');
    pool.extend(b'A'..=b'Z');
    pool.extend(b'0'..=b'9');
    if symbols {
        pool.extend_from_slice(SYMBOL_CHARS);
    }
    if avoid_ambiguous {
        pool.retain(|c| !AMBIGUOUS_CHARS.contains(c));
    }

    let pool_len = pool.len();
    // 256 内能均匀覆盖的最大倍数:超过此阈值的字节丢弃,消除模偏。
    let limit = 256 - (256 % pool_len);

    let mut out: Vec<u8> = Vec::with_capacity(length);
    // 缓冲区:一次取一小批随机字节,逐个消费(拒绝则跳过),耗尽则补取。
    let mut buf = vec![0u8; 64];
    let mut pos = buf.len(); // 起始即耗尽,触发首次 fill
    while out.len() < length {
        if pos >= buf.len() {
            getrandom::fill(&mut buf)
                .map_err(|e| Error::Other(format!("getrandom failed: {e}")))?;
            pos = 0;
        }
        let byte = buf[pos] as usize;
        pos += 1;
        if byte < limit {
            out.push(pool[byte % pool_len]);
        }
    }
    // SAFETY: 池内均为 ASCII 字符,pool 字节即合法 UTF-8。
    String::from_utf8(out)
        .map_err(|e| Error::Other(format!("generated password not utf-8: {e}")))
}

/// `gen`:生成强随机密码并打印到 **stdout**(末尾换行),脚本友好:`pw=$(zkv gen)`。
///
/// 纯生成,不解锁库、不需要口令。
pub fn run_gen(length: usize, symbols: bool, avoid_ambiguous: bool) -> Result<()> {
    let pw = generate_password(length, symbols, avoid_ambiguous)?;
    let stdout = std::io::stdout();
    let mut out = stdout.lock();
    writeln!(out, "{pw}")?;
    Ok(())
}

/// `edit`:修改已存在条目的若干字段。每个参数为 `None` 表示「不改」。
///
/// 至少要改一处(title/data/tags/favorite/category/单字段/标签增删 之一);全 `None` 报错。
///
/// 互斥规则(调用方 `main.rs` 在分发前已校验并报错,这里仍兜底):
/// - `data_json` 与 `fields`(单字段 flag)互斥:`Error::Other("--data conflicts with field flags")`。
/// - `tags`(整体覆盖 `--tag`)与 `tag_delta`(--add-tag/--rm-tag)互斥:
///   `Error::Other("--tag conflicts with --add-tag/--rm-tag")`。
///
/// `category = Some("name")` 按分类名解析成 id 并设置(找不到报错);
/// `category = None` 表示「不动」(本期不支持清除,清除需后续 `--clear-cat`)。
/// 替换 data 时同步 `item_type`,保持与 data tag 一致。成功打印 `updated item <id>`。
#[allow(clippy::too_many_arguments)]
pub fn run_edit(
    u: &Unlocked,
    id: i64,
    title: Option<&str>,
    data_json: Option<&str>,
    tags: Option<Vec<String>>,
    favorite: Option<bool>,
    category: Option<&str>,
    fields: &EditFields,
    tag_delta: &TagDelta,
    otpauth: Option<&str>,
) -> Result<()> {
    // 互斥校验(兜底;main.rs 已校验,但 run_edit 作为公开纯函数也应自洽)。
    if data_json.is_some() && fields.any() {
        return Err(Error::Other(
            "--data conflicts with field flags".into(),
        ));
    }
    if tags.is_some() && tag_delta.any() {
        return Err(Error::Other(
            "--tag conflicts with --add-tag/--rm-tag".into(),
        ));
    }

    let conn = u.db.conn();
    let mut item = store::get_item(conn, id)?
        .ok_or_else(|| Error::Other(format!("item {id} not found")))?;

    let mut changed = false;
    if let Some(t) = title {
        item.title = t.into();
        changed = true;
    }
    if let Some(j) = data_json {
        let (tpl, fields) = parse_item_data(j, &item.template_id)?;
        item.template_id = tpl;
        item.fields = fields;
        changed = true;
    }
    if let Some(tg) = tags {
        item.tags = tg;
        changed = true;
    }
    if tag_delta.any() {
        item.tags = tag_delta.apply(&item.tags);
        changed = true;
    }
    if let Some(f) = favorite {
        item.favorite = f;
        changed = true;
    }
    if let Some(cat) = category {
        let cid = category_id_by_name(conn, cat)?
            .ok_or_else(|| Error::Other(format!("category '{cat}' not found")))?;
        item.category_id = Some(cid);
        changed = true;
    }
    // 单字段覆盖(--set name=value):按 name 更新/追加。
    if fields.any() && fields.apply(&mut item) {
        changed = true;
    }
    // --otpauth:覆盖首个 kind=Totp 字段。
    if let Some(uri) = otpauth {
        let secret = parse_otpauth(uri)?;
        let target = item.fields.iter_mut().find(|f| f.kind == FieldKind::Totp);
        match target {
            Some(f) => {
                f.value = secret;
                changed = true;
            }
            None => {
                return Err(Error::Other("--otpauth needs a Totp field".into()));
            }
        }
    }
    if !changed {
        return Err(Error::Other("edit: nothing to change".into()));
    }

    store::update_item(conn, &item)?;
    u.save()?;
    println!("{} {}", style::ok("updated item"), style::id_text(&id.to_string()));
    // 提供了 TOTP 来源(--otpauth / --qr / --qr-url / --set totp=)时,向 stderr 打印实时码确认。
    if otpauth.is_some() || fields.sets.iter().any(|(n, _)| n == "totp") {
        eprint_totp_hint(&item);
    }
    Ok(())
}

/// `rm`:删除条目。`yes = false` 时向 stderr 提示 `y/N` 确认。
///
/// 确认读首字符;非 `y`/`Y`(含 EOF/读失败)按「否」处理,打印 `aborted` 并返回 `Ok(())`。
/// 成功打印 `deleted item <id>`。
pub fn run_rm(u: &Unlocked, id: i64, yes: bool) -> Result<()> {
    use std::io::BufRead;
    let conn = u.db.conn();
    let item = store::get_item(conn, id)?
        .ok_or_else(|| Error::Other(format!("item {id} not found")))?;

    if !yes {
        let mut stderr = std::io::stderr();
        write!(stderr, "delete \"{}\"? [y/N] ", item.title)?;
        stderr.flush()?;
        let stdin = std::io::stdin();
        let lock = stdin.lock();
        // EOF/读失败按「否」处理。
        let confirm = lock
            .lines()
            .next()
            .unwrap_or(Ok(String::new()))
            .unwrap_or_default();
        let first = confirm.trim_start().chars().next();
        if !matches!(first, Some('y' | 'Y')) {
            println!("{}", style::muted("aborted"));
            return Ok(());
        }
    }

    store::delete_item(conn, id)?;
    u.save()?;
    println!("{} {}", style::ok("deleted item"), style::id_text(&id.to_string()));
    Ok(())
}

// ---------------------------------------------------------------------------
// 分类/标签管理命令(cat/tag)
// ---------------------------------------------------------------------------

/// `cat add`:新增分类。`parent` 为父分类名(可选,找不到报错);成功打印
/// `added category <id>: <name>`。
pub fn run_cat_add(u: &Unlocked, name: &str, parent: Option<&str>) -> Result<i64> {
    let conn = u.db.conn();
    let parent_id = match parent {
        Some(pn) => Some(
            category_id_by_name(conn, pn)?
                .ok_or_else(|| Error::Other(format!("parent category '{pn}' not found")))?,
        ),
        None => None,
    };
    let mut cat = Category {
        id: None,
        name: name.into(),
        parent_id,
        sort_order: 0,
    };
    let id = store::insert_category(conn, &mut cat)?;
    u.save()?;
    println!(
        "{} {}: {}",
        style::ok("added category"),
        style::id_text(&id.to_string()),
        name
    );
    Ok(id)
}

/// `cat rm`:删除分类(by id 或名)。子条目 `category_id` 由外键 `ON DELETE SET NULL` 置空。
/// 成功打印 `deleted category <id>`。
pub fn run_cat_rm(u: &Unlocked, target: &str) -> Result<()> {
    let conn = u.db.conn();
    let id = resolve_category(conn, target)?;
    store::delete_category(conn, id)?;
    u.save()?;
    println!(
        "{} {}",
        style::ok("deleted category"),
        style::id_text(&id.to_string())
    );
    Ok(())
}

/// `cat ls`:列出全部分类。渲染为对齐表格(ID/NAME/PARENT/ORDER),无父用 `-`。
pub fn run_cat_ls(u: &Unlocked) -> Result<()> {
    let conn = u.db.conn();
    let cats = store::list_categories(conn)?;
    let stdout = std::io::stdout();
    let mut out = stdout.lock();
    let c = style::stdout_enabled();
    if cats.is_empty() {
        writeln!(out, "{}", style::paint(c, &["muted"], "(no categories)"))?;
        return Ok(());
    }
    // 构一个 id→name 映射,便于把 parent_id 渲染成父分类名。
    let id_to_name: std::collections::HashMap<i64, String> = cats
        .iter()
        .filter_map(|cat| cat.id.map(|i| (i, cat.name.clone())))
        .collect();
    let header = [
        ("ID", Align::Right),
        ("NAME", Align::Left),
        ("PARENT", Align::Left),
        ("ORDER", Align::Right),
    ];
    let rows: Vec<Vec<String>> = cats
        .iter()
        .map(|cat| {
            let id = cat.id.unwrap_or(-1);
            let parent = cat
                .parent_id
                .and_then(|pid| id_to_name.get(&pid).cloned())
                .unwrap_or_else(|| "-".into());
            vec![
                style::paint(c, &["id"], &id.to_string()),
                cat.name.clone(),
                parent,
                cat.sort_order.to_string(),
            ]
        })
        .collect();
    render_table(&mut out, c, &header, &rows)
}

/// 把 target(数字 id 或分类名)解析成分类 id。两者都失败报错。
fn resolve_category(conn: &rusqlite::Connection, target: &str) -> Result<i64> {
    // 优先按数字 id 解析。
    if let Ok(n) = target.parse::<i64>() {
        return Ok(n);
    }
    // 否则按名匹配。
    category_id_by_name(conn, target)?
        .ok_or_else(|| Error::Other(format!("category '{target}' not found")))
}

/// `tag ls`:列出全部标签。渲染为对齐表格(ID/NAME)。
pub fn run_tag_ls(u: &Unlocked) -> Result<()> {
    let conn = u.db.conn();
    let tags = store::list_tags(conn)?;
    let stdout = std::io::stdout();
    let mut out = stdout.lock();
    let c = style::stdout_enabled();
    if tags.is_empty() {
        writeln!(out, "{}", style::paint(c, &["muted"], "(no tags)"))?;
        return Ok(());
    }
    let header = [("ID", Align::Right), ("NAME", Align::Left)];
    let rows: Vec<Vec<String>> = tags
        .iter()
        .map(|t| vec![style::paint(c, &["id"], &t.id.to_string()), t.name.clone()])
        .collect();
    render_table(&mut out, c, &header, &rows)
}

/// `tag rm`:删除标签(by 名)。成功打印 `deleted tag <name>`。
pub fn run_tag_rm(u: &Unlocked, name: &str) -> Result<()> {
    let conn = u.db.conn();
    let id = tag_id_by_name(conn, name)?
        .ok_or_else(|| Error::Other(format!("tag '{name}' not found")))?;
    store::delete_tag(conn, id)?;
    u.save()?;
    println!("{} {}", style::ok("deleted tag"), name);
    Ok(())
}

/// `tag mv`:改标签名。成功打印 `renamed tag <from> -> <to>`。
pub fn run_tag_mv(u: &Unlocked, from: &str, to: &str) -> Result<()> {
    let conn = u.db.conn();
    let id = tag_id_by_name(conn, from)?
        .ok_or_else(|| Error::Other(format!("tag '{from}' not found")))?;
    store::update_tag(conn, id, to)?;
    u.save()?;
    println!("{} {} -> {}", style::ok("renamed tag"), from, to);
    Ok(())
}

// ---------------------------------------------------------------------------
// 附件管理命令(attach add/ls/get/rm)
// ---------------------------------------------------------------------------

/// 按扩展名做轻量 MIME 推断。未知扩展名返回 `None`,由调用方决定是否给默认值。
///
/// 覆盖常见办公/图片/文本格式;不引入 mime_guess crate,保持依赖最小。
pub fn guess_mime(path: &Path) -> Option<String> {
    let ext = path.extension()?.to_str()?.to_ascii_lowercase();
    let mime = match ext.as_str() {
        "pdf" => "application/pdf",
        "png" => "image/png",
        "jpg" | "jpeg" => "image/jpeg",
        "gif" => "image/gif",
        "svg" => "image/svg+xml",
        "webp" => "image/webp",
        "txt" | "log" | "md" => "text/plain",
        "csv" => "text/csv",
        "html" | "htm" => "text/html",
        "json" => "application/json",
        "xml" => "application/xml",
        "zip" => "application/zip",
        "gz" | "tgz" => "application/gzip",
        "tar" => "application/x-tar",
        "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        "xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        "pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation",
        "doc" => "application/msword",
        "xls" => "application/vnd.ms-excel",
        "ppt" => "application/vnd.ms-powerpoint",
        "bin" | "dat" => "application/octet-stream",
        _ => return None,
    };
    Some(mime.to_string())
}

/// 判断附件 `att` 是否属于条目 `item`。
///
/// 查 `SELECT item_id FROM attachments WHERE id=?1`;附件不存在返回 `Ok(false)`。
fn attachment_belongs_to(conn: &rusqlite::Connection, att: i64, item: i64) -> Result<bool> {
    let row: Option<i64> = conn
        .query_row(
            "SELECT item_id FROM attachments WHERE id = ?1",
            rusqlite::params![att],
            |r| r.get::<_, i64>(0),
        )
        .ok();
    Ok(row == Some(item))
}

/// `attach add`:把本地文件读入内存,作为加密内嵌附件挂到 `item` 上。
///
/// 校验 item 存在 → 读文件 → 推断 filename/mime → insert → save。
/// 打印 `attached <id>: <filename> (<size> bytes)` 并返回新附件 id。
pub fn run_attach_add(
    u: &Unlocked,
    item: i64,
    file: &Path,
    mime: Option<&str>,
) -> Result<i64> {
    let conn = u.db.conn();
    // 校验 item 存在(不存在给清晰错误,而非依赖外键)。
    if store::get_item(conn, item)?.is_none() {
        return Err(Error::Other(format!("item {item} not found")));
    }
    let blob = std::fs::read(file)?;
    let filename = file
        .file_name()
        .and_then(|n| n.to_str())
        .map(|s| s.to_string())
        .unwrap_or_else(|| "attachment".to_string());
    let mime_type = mime.map(|s| s.to_string()).or_else(|| guess_mime(file));

    let mut att = Attachment {
        id: None,
        item_id: item,
        filename,
        mime_type,
        size: 0, // insert_attachment 会用 blob.len() 回填
        blob,
    };
    let id = store::insert_attachment(conn, &mut att)?;
    u.save()?;
    println!(
        "{} {}: {} ({} bytes)",
        style::ok("attached"),
        style::id_text(&id.to_string()),
        att.filename,
        att.size
    );
    Ok(id)
}

/// `attach ls`:列出 item 的附件元数据(**不读 blob**)。每行
/// `id\tfilename\tmime\tsize`,无附件时打印 `(no attachments)`。
pub fn run_attach_ls(u: &Unlocked, item: i64) -> Result<()> {
    let conn = u.db.conn();
    // 自己写查询,避免 list_attachments 把 blob 也读出来。
    let mut stmt = conn.prepare(
        "SELECT id, filename, mime_type, size FROM attachments
         WHERE item_id = ?1 ORDER BY id ASC",
    )?;
    let rows: Vec<(i64, String, Option<String>, i64)> = stmt
        .query_map(rusqlite::params![item], |r| {
            Ok((
                r.get::<_, i64>(0)?,
                r.get::<_, String>(1)?,
                r.get::<_, Option<String>>(2)?,
                r.get::<_, i64>(3)?,
            ))
        })?
        .filter_map(|r| r.ok())
        .collect();

    let stdout = std::io::stdout();
    let mut out = stdout.lock();
    let c = style::stdout_enabled();
    if rows.is_empty() {
        writeln!(out, "{}", style::paint(c, &["muted"], "(no attachments)"))?;
        return Ok(());
    }
    let header = [
        ("ID", Align::Right),
        ("FILENAME", Align::Left),
        ("MIME", Align::Left),
        ("SIZE", Align::Right),
    ];
    let table_rows: Vec<Vec<String>> = rows
        .iter()
        .map(|(id, filename, mime, size)| {
            vec![
                style::paint(c, &["id"], &id.to_string()),
                filename.clone(),
                mime.clone().unwrap_or_else(|| "-".into()),
                size.to_string(),
            ]
        })
        .collect();
    render_table(&mut out, c, &header, &table_rows)
}

/// `attach get`:导出附件 blob 到文件(`-o`)或 stdout。
///
/// - `output = Some(p)`:写文件(`std::fs::write`)。
/// - `output = None`:二进制安全地 `write_all` 到 stdout。
///
/// 元信息(filename/mime/size)打到 stderr,stdout 只出 blob。
/// 校验附件存在且归属 `item`,否则 `Error::Other`。
pub fn run_attach_get(
    u: &Unlocked,
    item: i64,
    att: i64,
    output: Option<&Path>,
) -> Result<()> {
    let conn = u.db.conn();
    let attachment = store::get_attachment(conn, att)?
        .ok_or_else(|| Error::Other(format!("attachment {att} not found")))?;
    if !attachment_belongs_to(conn, att, item)? {
        return Err(Error::Other(format!(
            "attachment {att} does not belong to item {item}"
        )));
    }

    let mime = attachment.mime_type.clone().unwrap_or_else(|| "-".into());
    eprintln!(
        "{}",
        style::paint(
            style::stderr_enabled(),
            &["muted"],
            &format!("{}\t{}\t{} bytes", attachment.filename, mime, attachment.size)
        )
    );

    match output {
        Some(p) => {
            std::fs::write(p, &attachment.blob)?;
            eprintln!(
                "{}",
                style::paint(
                    style::stderr_enabled(),
                    &["ok"],
                    &format!("wrote {}", p.display())
                )
            );
        }
        None => {
            let stdout = std::io::stdout();
            let mut out = stdout.lock();
            out.write_all(&attachment.blob)?;
        }
    }
    Ok(())
}

/// `attach rm`:删除附件(校验归属后)。打印 `deleted attachment <att>`。
pub fn run_attach_rm(u: &Unlocked, item: i64, att: i64) -> Result<()> {
    let conn = u.db.conn();
    // 先校验存在 + 归属,避免误删不相关附件。
    if store::get_attachment(conn, att)?.is_none() {
        return Err(Error::Other(format!("attachment {att} not found")));
    }
    if !attachment_belongs_to(conn, att, item)? {
        return Err(Error::Other(format!(
            "attachment {att} does not belong to item {item}"
        )));
    }
    store::delete_attachment(conn, att)?;
    u.save()?;
    println!(
        "{} {}",
        style::ok("deleted attachment"),
        style::id_text(&att.to_string())
    );
    Ok(())
}

// ---------------------------------------------------------------------------
// 导入/导出(import/export)
// ---------------------------------------------------------------------------

/// 导入结果:成功条数与失败条数(逐条容错,失败不中断)。
pub struct ImportResult {
    /// 成功插入的条数。
    pub ok: usize,
    /// 解析/插入失败的条数。
    pub fail: usize,
}

/// 导出格式。
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
#[value(rename_all = "lowercase")]
pub enum Format {
    /// JSON(完整、无损,推荐迁移/备份)。
    Json,
    /// CSV(扁平,仅 password 类型,人可读/表格)。
    Csv,
}

// --- 纯函数(便于单测) ---

/// 备份信封:条目 + 附件(用于完整、含附件的 JSON 导出/导入)。
///
/// 用信封包裹而非给 `Item` 加 `attachments` 字段,避免改动核心类型。
/// 字段顺序固定(`items` 在前),不附加多余字段,保持向前/向后兼容。
#[derive(serde::Serialize, serde::Deserialize)]
struct BackupEnvelope {
    items: Vec<Item>,
    #[serde(default)]
    attachments: Vec<Attachment>,
}

/// 把条目 + 附件序列化为紧凑 JSON 信封字符串(含附件,无损往返)。便于单测。
pub fn build_backup_json(items: &[Item], attachments: &[Attachment]) -> Result<String> {
    Ok(serde_json::to_string(&BackupEnvelope {
        items: items.to_vec(),
        attachments: attachments.to_vec(),
    })?)
}

/// 把条目列表序列化为紧凑 JSON 字符串(无损往返)。
pub fn export_json(items: &[Item]) -> Result<String> {
    Ok(serde_json::to_string(items)?)
}

/// 解析 JSON 字符串为 (条目列表, 可选附件列表)。
///
/// 兼容三种形状(按序尝试):
/// 1. 备份信封 `{"items":[...], "attachments":[...]}` → items + attachments。
/// 2. 新形状裸数组 `Vec<Item>`(含 `template_id`+`fields`)→ items,无附件。
/// 3. 旧形状(每条含 `item_type`+`data`):逐条把 `data`(legacy ItemData)经
///    `legacy_to_fields` 转;`template_id` 取 `item_type` 字符串 → items,无附件。
///
/// 整体解析全部失败时返回原解析错误。`attachments` 仅在信封形状下为 `Some`。
pub fn import_json(s: &str) -> Result<(Vec<Item>, Option<Vec<Attachment>>)> {
    // 1. 备份信封(含附件)。
    if let Ok(env) = serde_json::from_str::<BackupEnvelope>(s) {
        return Ok((env.items, Some(env.attachments)));
    }
    // 2. 新形状裸数组。
    match serde_json::from_str::<Vec<Item>>(s) {
        Ok(v) => Ok((v, None)),
        Err(new_err) => {
            // 3. 旧形状:逐条容错解析。
            #[derive(serde::Deserialize)]
            struct LegacyItem {
                id: Option<i64>,
                #[serde(alias = "item_type", alias = "type")]
                template_id: Option<String>,
                title: String,
                category_id: Option<i64>,
                #[serde(default)]
                favorite: bool,
                tags: Vec<String>,
                created_at: i64,
                updated_at: i64,
                // 任意其余字段(含 data)落到这里,逐条提取 data。
                #[serde(flatten)]
                extra: serde_json::Value,
            }
            if let Ok(arr) = serde_json::from_str::<Vec<LegacyItem>>(s) {
                let mut out = Vec::new();
                for li in arr {
                    let (tpl, fields) = if let Some(data) = li.extra.get("data") {
                        // 尝试 legacy ItemData;失败则尝试 Vec<Field>;都失败用空。
                        if let Ok(legacy) =
                            serde_json::from_value::<LegacyItemData>(data.clone())
                        {
                            legacy_to_fields(legacy)
                        } else if let Ok(fs) = serde_json::from_value::<Vec<Field>>(data.clone()) {
                            (li.template_id.clone().unwrap_or_else(|| "password".into()), fs)
                        } else {
                            (li.template_id.clone().unwrap_or_else(|| "password".into()), Vec::new())
                        }
                    } else {
                        (li.template_id.clone().unwrap_or_else(|| "password".into()), Vec::new())
                    };
                    out.push(Item {
                        id: li.id,
                        template_id: tpl,
                        title: li.title,
                        category_id: li.category_id,
                        fields,
                        favorite: li.favorite,
                        tags: li.tags,
                        created_at: li.created_at,
                        updated_at: li.updated_at,
                    });
                }
                Ok((out, None))
            } else {
                // 都失败:返回新形状的原始错误。
                Err(new_err.into())
            }
        }
    }
}

/// 把 password 模板的条目序列化为 CSV 字符串。
///
/// 首行 header:`title,username,password,url,totp_secret,notes,tags`。
/// 非 password 模板的条目被跳过(返回跳过计数)。字段用 CSV 双引号转义,tags 用 `;` 分隔。
///
/// 返回 `(csv, skipped)`:skipped 为被跳过的非 password 条目数。
pub fn export_csv(items: &[Item]) -> (String, usize) {
    let mut out = String::from("title,username,password,url,totp_secret,notes,tags\n");
    let mut skipped = 0usize;
    for it in items {
        if it.template_id != "password" {
            skipped += 1;
            continue;
        }
        let get = |name: &str| -> String {
            it.field_value(name).unwrap_or("").to_string()
        };
        let username = get("username");
        let password = get("password");
        let url = get("url");
        let totp_secret = get("totp");
        let notes = get("notes");
        out.push_str(&csv_join(&[
            &it.title,
            &username,
            &password,
            &url,
            &totp_secret,
            &notes,
            &it.tags.join(";"),
        ]));
        out.push('\n');
    }
    (out, skipped)
}

/// 解析 CSV 字符串为 password 条目列表。
///
/// 第一行须为 header(顺序无关,按列名取 title/username/password/url/totp_secret/notes/tags)。
/// 缺失的列按空串处理。tags 列按 `;` 分割。逐行容错:坏行计入失败。
///
/// 返回 `Result<(items, fail)>`:整体(无数据行/空输入)返回 ok+fail=0;
/// 头部完全缺失列名结构时返回 `(items, fail)`。
pub fn import_csv(s: &str) -> Result<(Vec<Item>, usize)> {
    let rows = csv_split(s);
    if rows.is_empty() {
        return Ok((Vec::new(), 0));
    }
    let header = &rows[0];
    // 列名 → 列索引。
    let idx = |name: &str| -> Option<usize> {
        header.iter().position(|h| h == name)
    };
    let Some(i_title) = idx("title") else {
        return Err(Error::Other(
            "csv header missing 'title' column".into(),
        ));
    };

    let get = |row: &[String], i: Option<usize>| -> String {
        i.and_then(|n| row.get(n).cloned()).unwrap_or_default()
    };

    let mut items = Vec::new();
    let mut fail = 0usize;
    for row in &rows[1..] {
        // 空行(全空字段)或无 title 数据 → 跳过并计入失败。
        if row.is_empty() || row.iter().all(|f| f.is_empty()) {
            fail += 1;
            continue;
        }
        // 行太短(缺 title 列)容错跳过。
        if row.len() <= i_title {
            fail += 1;
            continue;
        }
        let title = row[i_title].clone();
        let username = get(row, idx("username"));
        let password = get(row, idx("password"));
        let url = get(row, idx("url"));
        let totp_secret = get(row, idx("totp_secret"));
        let notes = get(row, idx("notes"));
        let tags_raw = get(row, idx("tags"));
        let tags: Vec<String> = tags_raw
            .split(';')
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty())
            .collect();
        let item = Item {
            id: None,
            template_id: "password".into(),
            title,
            category_id: None,
            fields: vec![
                Field { name: "username".into(), value: username, kind: FieldKind::Text, protected: false },
                Field { name: "password".into(), value: password, kind: FieldKind::Secret, protected: true },
                Field { name: "url".into(), value: url, kind: FieldKind::Text, protected: false },
                Field { name: "totp".into(), value: totp_secret, kind: FieldKind::Totp, protected: true },
                Field { name: "notes".into(), value: notes, kind: FieldKind::Multiline, protected: false },
            ],
            favorite: false,
            tags,
            created_at: 0,
            updated_at: 0,
        };
        items.push(item);
    }
    Ok((items, fail))
}

/// CSV 字段转义:含逗号/双引号/换行/回车 → 用双引号包裹,内部双引号翻倍。
fn csv_field(s: &str) -> String {
    if s.contains([',', '"', '\n', '\r']) {
        let escaped = s.replace('"', "\"\"");
        format!("\"{escaped}\"")
    } else {
        s.to_string()
    }
}

/// 把若干字段用逗号连接为一行(每个字段先转义)。
fn csv_join(fields: &[&str]) -> String {
    fields
        .iter()
        .map(|f| csv_field(f))
        .collect::<Vec<_>>()
        .join(",")
}

/// 把 CSV 文本按行解析成二维 `Vec<String>`(正确处理引号包裹与换行)。
///
/// 简易状态机:`in_quotes` 时逗号/换行视作字段内容;`""` 翻译为单个 `"`。
/// 行尾无内容(空行)仍产出一个空行向量。
fn csv_split(s: &str) -> Vec<Vec<String>> {
    let mut rows: Vec<Vec<String>> = Vec::new();
    let mut row: Vec<String> = Vec::new();
    let mut field = String::new();
    let mut in_quotes = false;
    let mut chars = s.chars().peekable();
    while let Some(c) = chars.next() {
        if in_quotes {
            if c == '"' {
                // 前瞻:连续两个引号 → 字面引号,否则结束引号段。
                if chars.peek() == Some(&'"') {
                    chars.next();
                    field.push('"');
                } else {
                    in_quotes = false;
                }
            } else {
                field.push(c);
            }
        } else if c == '"' {
            in_quotes = true;
        } else if c == ',' {
            row.push(std::mem::take(&mut field));
        } else if c == '\n' {
            // CRLF:去掉已压入的 \r。
            if field.ends_with('\r') {
                field.pop();
            }
            row.push(std::mem::take(&mut field));
            rows.push(std::mem::take(&mut row));
        } else {
            field.push(c);
        }
    }
    // 末尾残留(无换行结尾,或文件结尾)。
    if !field.is_empty() || !row.is_empty() {
        if field.ends_with('\r') {
            field.pop();
        }
        row.push(field);
        rows.push(row);
    }
    rows
}

/// `export`:把全库条目按 `format` 导出。
///
/// - JSON:完整备份信封 `{items, attachments}`(含附件),无损。
/// - CSV:仅 password 类型,扁平 7 列(不含附件)。
///
/// `output = Some(p)` → 写文件(0600);`None` → stdout。
/// **输出为明文**(命令已解锁,用户主动导出)。CSV 模式下非 password 条目被跳过,
/// 向 stderr 提示 `skipped N non-password items`。
pub fn run_export(
    u: &Unlocked,
    format: Format,
    output: Option<&Path>,
) -> Result<()> {
    let conn = u.db.conn();
    let items = store::list_items(conn)?;
    let content = match format {
        Format::Json => {
            let attachments = store::list_all_attachments(conn)?;
            build_backup_json(&items, &attachments)?
        }
        Format::Csv => {
            let (csv, skipped) = export_csv(&items);
            if skipped > 0 {
                eprintln!(
                    "{}",
                    style::warn(&format!("skipped {skipped} non-password items"))
                );
            }
            csv
        }
    };
    match output {
        Some(p) => {
            write_secret_file(p, content.as_bytes())?;
            eprintln!(
                "{}",
                style::paint(
                    style::stderr_enabled(),
                    &["ok"],
                    &format!("exported {} items to {}", items.len(), p.display())
                )
            );
        }
        None => {
            let stdout = std::io::stdout();
            let mut out = stdout.lock();
            out.write_all(content.as_bytes())?;
        }
    }
    Ok(())
}

/// `import`:从文件或 stdin 读入,按 `format` 解析并逐条 insert。
///
/// - `input = Some(p)` → 读文件;`None` → stdin。
/// - 逐条容错:解析/插入失败计入 failed,不中断其余。
/// - 每条 `id` 强制置 None(总是新建,从不覆盖;重复导入会创建重复条目)。
/// - JSON 信封里的附件会按 item id 重映射到新条目后插入(item_id 查不到 → 计 failed 跳过)。
/// - `created_at/updated_at` 为 0 时由 `insert_item` 填当前时间;否则保留原值。
/// - 成功后 `save` 落盘。打印 `imported N items (M attachments)` 或含 `K failed`。
pub fn run_import(u: &Unlocked, format: Format, input: Option<&Path>) -> Result<ImportResult> {
    let raw = match input {
        Some(p) => std::fs::read_to_string(p)?,
        None => {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s)?;
            s
        }
    };

    // 解析为候选条目列表 + 可选附件(JSON 信封才有附件;CSV 无)。
    let (candidates, attachments_opt, parse_fail): (Vec<Item>, Option<Vec<Attachment>>, usize) =
        match format {
            Format::Json => match import_json(&raw) {
                Ok((items, atts)) => (items, atts, 0),
                Err(_) => (Vec::new(), None, 1), // 整体 JSON 坏掉:1 次失败。
            },
            Format::Csv => {
                let (items, fail) = import_csv(&raw)?;
                (items, None, fail)
            }
        };

    let conn = u.db.conn();
    let mut ok = 0usize;
    let mut fail = parse_fail;
    // 解析出的旧 item id → 插入后分到的新 id(用于附件重映射)。
    let mut old_to_new: std::collections::HashMap<i64, i64> = std::collections::HashMap::new();
    for mut item in candidates {
        let old_id = item.id;
        item.id = None; // 强制新 id。
        // created/updated 为 0 由 insert_item 填当前时间;否则保留原值。
        match store::insert_item(conn, &mut item) {
            Ok(new_id) => {
                if let Some(oid) = old_id {
                    old_to_new.insert(oid, new_id);
                }
                ok += 1;
            }
            Err(_) => fail += 1,
        }
    }

    // 附件:逐条重映射 item_id 后插入(查不到映射 → 计 failed 跳过,不 panic)。
    let mut att_ok = 0usize;
    let mut att_fail = 0usize;
    if let Some(atts) = attachments_opt {
        for mut att in atts {
            let new_item_id = match old_to_new.get(&att.item_id).copied() {
                Some(nid) => nid,
                None => {
                    att_fail += 1;
                    continue;
                }
            };
            att.id = None;
            att.item_id = new_item_id;
            // size 由 insert_attachment 用 blob.len() 回填。
            match store::insert_attachment(conn, &mut att) {
                Ok(_) => att_ok += 1,
                Err(_) => att_fail += 1,
            }
        }
    }

    let changed = ok > 0 || att_ok > 0;
    if changed {
        u.save()?;
    }

    if att_fail == 0 {
        println!(
            "{}",
            style::ok(&format!("imported {ok} items ({att_ok} attachments)"))
        );
    } else {
        println!(
            "{}",
            style::warn(&format!(
                "imported {ok} items ({att_ok} attachments, {att_fail} failed)"
            ))
        );
    }
    // 聚合失败:item 失败 + 附件失败 + 整体解析失败。
    fail += att_fail;
    Ok(ImportResult { ok, fail })
}

/// 写文件并以 0600 权限收紧(导出明文落盘时降低泄漏面)。
///
/// 先 `write` 再 `set_permissions`,避免创建时被 umask 放宽。
fn write_secret_file(path: &Path, data: &[u8]) -> Result<()> {
    std::fs::write(path, data)?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let perms = std::fs::metadata(path)?.permissions();
        let mut perms = perms;
        perms.set_mode(0o600);
        std::fs::set_permissions(path, perms)?;
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// 只读命令
// ---------------------------------------------------------------------------

/// `ls`:按过滤条件列出条目。`favorite = true` 时仅返回收藏项(透传到 `ListFilter`)。
pub fn run_ls(u: &Unlocked, f: &ListFilter, favorite: bool, json: bool) -> Result<()> {
    let mut f = f.clone();
    if favorite {
        f.favorite_only = true;
    }
    let conn = u.db.conn();
    let category_id = match &f.category {
        Some(name) => Some(
            category_id_by_name(conn, name)?
                .ok_or_else(|| Error::Other(format!("category '{name}' not found")))?,
        ),
        None => None,
    };
    let sf = to_search_filter(&f, category_id);
    let items = search::search(conn, &sf)?;
    let stdout = std::io::stdout();
    let mut out = stdout.lock();
    write_items(&mut out, &items, json)
}

/// `get`:打印单条条目,或某字段原始值(末尾加换行)。
pub fn run_get(u: &Unlocked, id: i64, field: Option<&str>, json: bool) -> Result<()> {
    let conn = u.db.conn();
    let item = store::get_item(conn, id)?
        .ok_or_else(|| Error::Other(format!("item {id} not found")))?;

    let stdout = std::io::stdout();
    let mut out = stdout.lock();

    match field {
        // 字段模式:打印原始值(便于管道,如 `$(zkv get ... -f password)`)。
        Some(name) => {
            let val = item_field(&item, name)?;
            writeln!(out, "{val}")?;
        }
        // 整条模式。
        None => {
            if json {
                let s = serde_json::to_string_pretty(&item)?;
                writeln!(out, "{s}")?;
            } else {
                write_item_human(&mut out, &item)?;
            }
        }
    }
    Ok(())
}

/// `search`:全文检索,复用 `write_items` 格式化。
pub fn run_search(u: &Unlocked, query: &str, json: bool) -> Result<()> {
    let sf = Filter {
        query: Some(query.to_string()),
        category: None,
        tags: vec![],
        template_id: None,
        favorite_only: false,
    };
    let items = search::search(u.db.conn(), &sf)?;
    let stdout = std::io::stdout();
    let mut out = stdout.lock();
    write_items(&mut out, &items, json)
}

/// `cp`:复制某字段到剪贴板,`secs` 秒后自动清空。
///
/// `field` 默认为 `password`。打印 `copied <field> (clears in <n>s)` 提示。
/// 特例:`field == "otp"` 时复制**实时 TOTP 验证码**(而非 `totp` 字段返回的原始 secret),
/// 提示语相应改为 `copied otp code (...)`。
pub fn run_cp(u: &Unlocked, id: i64, field: Option<&str>, clear_secs: u64) -> Result<()> {
    let conn = u.db.conn();
    let item = store::get_item(conn, id)?
        .ok_or_else(|| Error::Other(format!("item {id} not found")))?;
    let name = field.unwrap_or("password");

    // otp 特例:复制实时验证码。
    if name == "otp" {
        let code = otp_of_item(&item)?;
        clipboard::copy_and_clear_after(&code, clear_secs)?;
        println!(
            "{}",
            style::ok(&format!("copied otp code (clears in {clear_secs}s)"))
        );
        return Ok(());
    }

    let val = item_field(&item, name)?;
    clipboard::copy_and_clear_after(&val, clear_secs)?;
    println!(
        "{}",
        style::ok(&format!("copied {name} (clears in {clear_secs}s)"))
    );
    Ok(())
}

/// 向 stderr 提示条目的实时 TOTP 验证码 + 剩余秒数(导入 / 更换 2FA 后即时确认)。
///
/// 仅在条目含**非空** Totp 字段、且能成功生成时打印;失败静默,绝不干扰主流程或污染 stdout
/// (与 `--gen-password` 把密码打 stderr 的约定一致)。供 `add` / `edit` 在提供 TOTP 来源后调用。
fn eprint_totp_hint(item: &Item) {
    let Some(secret) = item.totp_value().filter(|s| !s.trim().is_empty()) else {
        return;
    };
    let Ok(code) = crate::totp::current_totp(secret) else {
        return;
    };
    let secs = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    eprintln!(
        "{} {}  {}",
        style::warn("totp:"),
        code,
        style::paint(
            style::stderr_enabled(),
            &["muted"],
            &format!("(valid ~{}s)", 30 - secs % 30)
        )
    );
}

/// 计算单条条目的实时 TOTP 验证码(6 位)。供 `run_otp`/`run_cp` 复用。
///
/// 找首个 kind=Totp 字段且 secret 非空时可生成;否则 [`Error::Other`]。
pub fn otp_of_item(item: &Item) -> Result<String> {
    let secret = item
        .totp_value()
        .ok_or_else(|| Error::Other("item has no totp secret".into()))?;
    if secret.trim().is_empty() {
        return Err(Error::Other("item has no totp secret".into()));
    }
    crate::totp::current_totp(secret)
}

/// `otp`:打印条目的当前 TOTP 验证码(6 位 + 换行)到 stdout,脚本友好。
///
/// 仅 password 条目且 `totp_secret` 非空可生成。可选向 stderr 打印剩余有效秒数。
pub fn run_otp(u: &Unlocked, id: i64) -> Result<()> {
    let conn = u.db.conn();
    let item = store::get_item(conn, id)?
        .ok_or_else(|| Error::Other(format!("item {id} not found")))?;
    let code = otp_of_item(&item)?;

    // stdout 仅 6 位码 + 换行,便于 `code=$(zkv otp vault 3)`。
    let stdout = std::io::stdout();
    let mut out = stdout.lock();
    writeln!(out, "{code}")?;

    // 可选:向 stderr 提示当前窗口剩余秒数(不打扰 stdout 脚本捕获)。
    let secs = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    eprintln!(
        "{}",
        style::paint(style::stderr_enabled(), &["muted"], &format!(
            "(valid ~{}s)",
            30 - secs % 30
        ))
    );
    Ok(())
}

/// 人类可读地打印单条条目。
///
/// 布局:标题横幅 → 副标题(类型/收藏★/标签)→ 分隔线 → 对齐字段 KV → 时间戳。
/// 多行字段(如 notes)的续行缩进对齐到值列;值保持终端默认色(浅色背景下不掉色);
/// 时间戳格式化为 UTC `YYYY-MM-DD HH:MM`(机器解析请用 `-f`/`--json`)。
fn write_item_human<W: Write>(out: &mut W, item: &Item) -> Result<()> {
    let c = style::stdout_enabled();
    let id = item.id.unwrap_or(-1);

    // —— 标题横幅(品牌色加粗)——
    let title = style::paint(c, &["title"], &item.title);
    writeln!(out, "{title}")?;

    // —— 副标题:类型 / 收藏 / 标签(均弱化,仅作元信息)——
    let mut sub = style::paint(c, &["muted"], &item.template_id);
    if item.favorite {
        sub.push_str(&style::paint(c, &["muted"], " · "));
        sub.push_str(&style::paint(c, &["warn"], "★ favorite"));
    }
    if !item.tags.is_empty() {
        sub.push_str(&style::paint(c, &["muted"], &format!(" · {}", item.tags.join(", "))));
    }
    writeln!(out, "{sub}")?;

    // —— 分隔线:对齐到最宽行的可见宽度(至少 24)——
    let rule_w = display_width(&item.title)
        .max(display_width(&sub))
        .max(24);
    writeln!(out, "{}", style::paint(c, &["muted"], &"".repeat(rule_w)))?;

    // —— 字段 KV:先收集全部 (label, value),统一 label 列宽后对齐渲染 ——
    let mut rows: Vec<(&str, String)> = Vec::new();
    rows.push(("id", id.to_string()));
    rows.push(("type", item.template_id.clone()));
    for f in &item.fields {
        rows.push((f.name.as_str(), f.value.clone()));
    }
    rows.push(("created", fmt_timestamp(item.created_at)));
    rows.push(("updated", fmt_timestamp(item.updated_at)));

    let label_w = rows.iter().map(|(l, _)| l.chars().count()).max().unwrap_or(0);
    let indent = " ".repeat(label_w + 2); // 值列起点 = 标签宽 + 两空格。
    for (label, value) in &rows {
        let head = style::paint(c, &["key"], &format!("{:width$}", label, width = label_w));
        let mut lines = value.split('\n');
        let first = lines.next().unwrap_or("");
        writeln!(out, "{head}  {first}")?;
        // 多行值:续行缩进到值列,保持对齐。
        for ln in lines {
            writeln!(out, "{indent}{ln}")?;
        }
    }
    Ok(())
}

// ===========================================================================
// 测试
// ===========================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::{Field, FieldKind};
    use crate::store;
    use crate::test_support::{mk_item, mk_password_item};

    /// 串行化所有读写 `ZKV_PASSPHRASE` 的测试(默认并行运行器下 env 非线程隔离)。
    /// 任何会 set/remove 或语义上依赖该 env 是否存在的测试,都先拿这把锁。
    fn env_lock() -> std::sync::MutexGuard<'static, ()> {
        use std::sync::Mutex;
        static LOCK: Mutex<()> = Mutex::new(());
        // unwrap:仅 panic( poison)时失败,测试本身已失败,可接受。
        LOCK.lock().unwrap()
    }

    /// 测试用小 KDF 参数,加速派生。
    fn fast_kdf() -> KdfParams {
        KdfParams {
            m_kib: 4_096,
            t_cost: 1,
            p_cost: 1,
        }
    }

    /// 唯一临时库路径。
    fn tmp_path(tag: &str) -> PathBuf {
        use std::sync::atomic::{AtomicU64, Ordering};
        static C: AtomicU64 = AtomicU64::new(0);
        let n = C.fetch_add(1, Ordering::Relaxed);
        let mut p = std::env::temp_dir();
        p.push(format!("zkv_cli_{tag}_{}_{}", std::process::id(), n));
        p
    }

    fn cleanup(p: &Path) {
        let _ = std::fs::remove_file(p);
        let mut t = p.as_os_str().to_owned();
        t.push(".tmp");
        let _ = std::fs::remove_file(PathBuf::from(t));
    }

    /// 写一个口令文件(内容 "pw\n"),供 `Unlocked::unlock` 的 `--passfile` 路径,
    /// 避免在无 TTY 的测试环境里落到 `rpassword` 提示。
    fn write_passfile(tag: &str) -> PathBuf {
        let p = tmp_path(&format!("pf_{tag}"));
        std::fs::write(&p, "pw\n").unwrap();
        p
    }    /// 构建一个含已知条目(password + note,带标签)的临时库,返回路径与口令。
    fn make_vault(tag: &str) -> PathBuf {
        let p = tmp_path(tag);
        cleanup(&p);
        let kdf = fast_kdf();
        vault::create_with_params(&p, "pw", &kdf).unwrap();
        // 解锁 → 插条目 → 落盘。
        let (db, key, kdf2, salt) = vault::unlock_full(&p, "pw").unwrap();
        {
            let conn = db.conn();
            let mut pw = Item {
        id: None,
        template_id: "password".into(),
        title: "GitHub".into(),
        category_id: None,
        fields: vec![
                Field { name: "username".into(), value: "alice".into(), kind: FieldKind::Text, protected: false },
                Field { name: "password".into(), value: "s3cret".into(), kind: FieldKind::Secret, protected: true },
                Field { name: "url".into(), value: "https://github.com".into(), kind: FieldKind::Text, protected: false },
                Field { name: "totp".into(), value: "JBSWY3DPEHPK3PXP".into(), kind: FieldKind::Totp, protected: true },
                Field { name: "notes".into(), value: "main".into(), kind: FieldKind::Multiline, protected: false },
            ],
        favorite: false,
        tags: vec!["work".into(), "vip".into()],
        created_at: 0,
        updated_at: 0,
    };
            store::insert_item(conn, &mut pw).unwrap();

            let mut note = Item {
        id: None,
        template_id: "note".into(),
        title: "Ideas".into(),
        category_id: None,
        fields: vec![
                Field { name: "format".into(), value: "markdown".into(), kind: FieldKind::Text, protected: false },
                Field { name: "content".into(), value: "# hello world".into(), kind: FieldKind::Multiline, protected: false },
            ],
        favorite: false,
        tags: vec!["work".into()],
        created_at: 0,
        updated_at: 0,
    };
            store::insert_item(conn, &mut note).unwrap();
        }
        vault::save_with_key(&p, &key, &kdf2, salt, &db).unwrap();
        // borrow checker:db drop 在 save 之后。
        drop(db);
        p
    }

    // --- 纯函数测试 ---

    #[test]
    fn strip_trailing_newline_both_styles() {
        assert_eq!(strip_trailing_newline("abc\n".into()), "abc");
        assert_eq!(strip_trailing_newline("abc\r\n".into()), "abc");
        assert_eq!(strip_trailing_newline("abc".into()), "abc");
        // 只去末尾单个换行,中间保留。
        assert_eq!(strip_trailing_newline("a\nb\n".into()), "a\nb");
    }

    #[test]
    fn display_width_strips_ansi_and_counts_cjk() {
        // 纯 ASCII。
        assert_eq!(display_width("GitHub"), 6);
        // CJK 每字宽度 2。
        assert_eq!(display_width("微信"), 4);
        // ANSI SGR 转义不计入宽度(着色后与纯文本同宽)。
        let colored = style::paint(true, &["id"], "42");
        assert_eq!(display_width(&colored), 2);
        // 真彩色 + reset 也不影响宽度。
        let ok = style::paint(true, &["ok"], "ok");
        assert_eq!(display_width(&ok), 2);
        // 混合:着色 id + 普通文本 + 着色 muted。
        let mixed = format!(
            "{}-{}",
            style::paint(true, &["id"], "1"),
            style::paint(true, &["muted"], "hi")
        );
        assert_eq!(display_width(&mixed), 4);
        // 控制符宽度 0。
        assert_eq!(display_width("\u{1}"), 0);
    }

    #[test]
    fn render_table_plain_when_color_off() {
        // color=false:无 ANSI、行首空格 + 列间两空格,末尾不留空格。
        let mut buf = Vec::<u8>::new();
        render_table(
            &mut buf,
            false,
            &[("ID", Align::Right), ("NAME", Align::Left)],
            &[
                vec!["1".into(), "GitHub".into()],
                vec!["12".into(), "Ideas".into()],
            ],
        )
        .unwrap();
        let out = String::from_utf8(buf).unwrap();
        assert_eq!(
            out,
            " ID  NAME\n ──  ──────\n  1  GitHub\n 12  Ideas\n"
        );
    }

    #[test]
    fn fmt_timestamp_known_epochs() {
        // epoch + 现代日期(UTC),验证 civil_from_days 正确性。
        assert_eq!(fmt_timestamp(0), "1970-01-01 00:00");
        assert_eq!(fmt_timestamp(1_735_689_600), "2025-01-01 00:00");
        // +1h 1m 1s → 时分正确(秒被截断)。
        assert_eq!(fmt_timestamp(1_735_689_600 + 3661), "2025-01-01 01:01");
    }

    #[test]
    fn write_item_human_renders_banner_dates_and_multiline() {
        let item = Item {
            id: Some(7),
            template_id: "password".into(),
            title: "GitHub".into(),
            category_id: None,
            fields: vec![
                Field { name: "username".into(), value: "alice".into(), kind: FieldKind::Text, protected: false },
                Field { name: "notes".into(), value: "a\nb".into(), kind: FieldKind::Multiline, protected: false },
            ],
            favorite: true,
            tags: vec!["work".into()],
            created_at: 1_735_689_600,
            updated_at: 1_735_689_600,
        };
        let mut buf = Vec::<u8>::new();
        write_item_human(&mut buf, &item).unwrap();
        let out = String::from_utf8(buf).unwrap();
        // 标题横幅 + 副标题(类型/收藏/标签)。
        assert!(out.starts_with("GitHub\n"));
        assert!(out.contains("password · ★ favorite · work"));
        // 分隔线。
        assert!(out.contains("────"));
        // 字段 KV 对齐。
        assert!(out.contains("username  alice"));
        // 多行字段续行缩进到值列(10 空格)。
        assert!(out.contains("          b"));
        // 时间戳已格式化(非原始 epoch)。
        assert!(out.contains("created   2025-01-01 00:00"));
        assert!(out.contains("updated   2025-01-01 00:00"));
        assert!(!out.contains("1735689600"));
    }

    #[test]
    fn item_field_password_mapping() {
        let item = Item {
        id: Some(1),
        template_id: "password".into(),
        title: "T".into(),
        category_id: None,
        fields: vec![
                Field { name: "username".into(), value: "u".into(), kind: FieldKind::Text, protected: false },
                Field { name: "password".into(), value: "p".into(), kind: FieldKind::Secret, protected: true },
                Field { name: "url".into(), value: "https://x".into(), kind: FieldKind::Text, protected: false },
                Field { name: "totp".into(), value: "TOTP".into(), kind: FieldKind::Totp, protected: true },
                Field { name: "notes".into(), value: "n".into(), kind: FieldKind::Multiline, protected: false },
            ],
        favorite: false,
        tags: vec![],
        created_at: 0,
        updated_at: 0,
    };
        assert_eq!(item_field(&item, "title").unwrap(), "T");
        assert_eq!(item_field(&item, "username").unwrap(), "u");
        assert_eq!(item_field(&item, "password").unwrap(), "p");
        assert_eq!(item_field(&item, "url").unwrap(), "https://x");
        assert_eq!(item_field(&item, "totp").unwrap(), "TOTP");
        assert_eq!(item_field(&item, "notes").unwrap(), "n");
    }

    #[test]
    fn item_field_note_and_card_mapping() {
        let note = Item {
        id: Some(1),
        template_id: "note".into(),
        title: "N".into(),
        category_id: None,
        fields: vec![
                Field { name: "format".into(), value: "markdown".into(), kind: FieldKind::Text, protected: false },
                Field { name: "content".into(), value: "body".into(), kind: FieldKind::Multiline, protected: false },
            ],
        favorite: false,
        tags: vec![],
        created_at: 0,
        updated_at: 0,
    };
        assert_eq!(item_field(&note, "format").unwrap(), "markdown");
        assert_eq!(item_field(&note, "content").unwrap(), "body");

        let card = Item {
        id: Some(2),
        template_id: "card".into(),
        title: "C".into(),
        category_id: None,
        fields: vec![
                Field { name: "holder".into(), value: "H".into(), kind: FieldKind::Text, protected: false },
                Field { name: "number".into(), value: "4111".into(), kind: FieldKind::Secret, protected: true },
                Field { name: "expiry".into(), value: "12/29".into(), kind: FieldKind::Text, protected: false },
                Field { name: "cvv".into(), value: "123".into(), kind: FieldKind::Secret, protected: true },
                Field { name: "bank".into(), value: "B".into(), kind: FieldKind::Text, protected: false },
                Field { name: "notes".into(), value: "cn".into(), kind: FieldKind::Multiline, protected: false },
            ],
        favorite: false,
        tags: vec![],
        created_at: 0,
        updated_at: 0,
    };
        assert_eq!(item_field(&card, "holder").unwrap(), "H");
        assert_eq!(item_field(&card, "number").unwrap(), "4111");
        assert_eq!(item_field(&card, "expiry").unwrap(), "12/29");
        assert_eq!(item_field(&card, "cvv").unwrap(), "123");
        assert_eq!(item_field(&card, "bank").unwrap(), "B");
        assert_eq!(item_field(&card, "notes").unwrap(), "cn");
    }

    #[test]
    fn item_field_unknown_field_errors() {
        let item = Item {
        id: Some(1),
        template_id: "note".into(),
        title: "N".into(),
        category_id: None,
        fields: vec![
                Field { name: "format".into(), value: "text".into(), kind: FieldKind::Text, protected: false },
                Field { name: "content".into(), value: "c".into(), kind: FieldKind::Multiline, protected: false },
            ],
        favorite: false,
        tags: vec![],
        created_at: 0,
        updated_at: 0,
    };
        // note 条目请求 password 字段 → 类型不匹配。
        assert!(item_field(&item, "password").is_err());
        // 完全未知字段。
        assert!(item_field(&item, "nope").is_err());
    }

    #[test]
    fn to_search_filter_maps_fields() {
        let lf = ListFilter {
            template_id: Some("password".into()),
            tags: vec!["a".into()],
            category: Some("Personal".into()),
            query: Some("q".into()),
            favorite_only: true,
        };
        let sf = to_search_filter(&lf, Some(7));
        assert_eq!(sf.template_id.as_deref(), Some("password"));
        assert_eq!(sf.tags, vec!["a".to_string()]);
        assert_eq!(sf.category, Some(7));
        assert_eq!(sf.query.as_deref(), Some("q"));
        assert!(sf.favorite_only);
    }

    // --- 端到端(只读命令返回 Ok/Err 路径) ---

    #[test]
    fn run_ls_returns_ok() {
        let p = make_vault("ls");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        let f = ListFilter::default();
        assert!(run_ls(&u, &f, false, false).is_ok());
        assert!(run_ls(&u, &f, false, true).is_ok());
        cleanup(&p);
    }

    #[test]
    fn run_ls_filter_by_type_and_tag() {
        let p = make_vault("lsfilt");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        let f = ListFilter {
            template_id: Some("note".into()),
            ..Default::default()
        };
        // 直接查 search 验证过滤语义(避免依赖 stdout 捕获)。
        let sf = to_search_filter(&f, None);
        let items = search::search(u.db.conn(), &sf).unwrap();
        assert!(items.iter().all(|i| i.template_id == "note"));

        let f2 = ListFilter {
            tags: vec!["vip".into()],
            ..Default::default()
        };
        let sf2 = to_search_filter(&f2, None);
        let items2 = search::search(u.db.conn(), &sf2).unwrap();
        assert!(items2.iter().all(|i| i.tags.contains(&"vip".to_string())));
        cleanup(&p);
    }

    #[test]
    fn run_ls_unknown_category_errors() {
        let p = make_vault("lscat");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        let f = ListFilter {
            category: Some("Nonexistent".into()),
            ..Default::default()
        };
        let err = run_ls(&u, &f, false, false);
        assert!(matches!(err, Err(Error::Other(_))));
        cleanup(&p);
    }

    #[test]
    fn run_get_found_and_missing() {
        let p = make_vault("get");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        // id=1 存在(GitHub)。
        assert!(run_get(&u, 1, Some("password"), false).is_ok());
        assert!(run_get(&u, 1, None, false).is_ok());
        assert!(run_get(&u, 1, None, true).is_ok());
        // 不存在的 id。
        assert!(matches!(
            run_get(&u, 9999, None, false),
            Err(Error::Other(_))
        ));
        // 未知字段。
        assert!(matches!(
            run_get(&u, 1, Some("nope"), false),
            Err(Error::Other(_))
        ));
        cleanup(&p);
    }

    #[test]
    fn run_search_ok() {
        let p = make_vault("search");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        assert!(run_search(&u, "hello", false).is_ok());
        assert!(run_search(&u, "hello", true).is_ok());
        cleanup(&p);
    }

    #[test]
    fn run_cp_missing_item_errors() {
        let p = make_vault("cp");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        // 不存在的 item → 报错(在剪贴板调用之前)。
        assert!(matches!(
            run_cp(&u, 9999, None, 1),
            Err(Error::Other(_))
        ));
        cleanup(&p);
    }

    #[test]
    fn otp_of_item_returns_six_digits() {
        // id=1 是 GitHub password,totp_secret = "JBSWY3DPEHPK3PXP"。
        let p = make_vault("otp");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        let conn = u.db.conn();
        let item = store::get_item(conn, 1).unwrap().unwrap();
        let code = otp_of_item(&item).unwrap();
        assert_eq!(code.len(), 6);
        assert!(code.chars().all(|c| c.is_ascii_digit()));
        cleanup(&p);
    }

    #[test]
    fn otp_of_item_no_secret_errors() {
        // note 条目无 totp_secret。
        let note = Item {
        id: Some(2),
        template_id: "note".into(),
        title: "N".into(),
        category_id: None,
        fields: vec![
                Field { name: "format".into(), value: "text".into(), kind: FieldKind::Text, protected: false },
                Field { name: "content".into(), value: "c".into(), kind: FieldKind::Multiline, protected: false },
            ],
        favorite: false,
        tags: vec![],
        created_at: 0,
        updated_at: 0,
    };
        assert!(matches!(otp_of_item(&note), Err(Error::Other(_))));

        // 空 secret 也报错。
        let pw = Item {
        id: Some(3),
        template_id: "password".into(),
        title: "P".into(),
        category_id: None,
        fields: vec![
                Field { name: "username".into(), value: "u".into(), kind: FieldKind::Text, protected: false },
                Field { name: "password".into(), value: "p".into(), kind: FieldKind::Secret, protected: true },
                Field { name: "url".into(), value: "".into(), kind: FieldKind::Text, protected: false },
                Field { name: "totp".into(), value: "   ".into(), kind: FieldKind::Totp, protected: true },
                Field { name: "notes".into(), value: "".into(), kind: FieldKind::Multiline, protected: false },
            ],
        favorite: false,
        tags: vec![],
        created_at: 0,
        updated_at: 0,
    };
        assert!(matches!(otp_of_item(&pw), Err(Error::Other(_))));
    }

    #[test]
    fn run_otp_ok_and_missing_errors() {
        let p = make_vault("runotp");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        // id=1 存在且有 secret → Ok。
        assert!(run_otp(&u, 1).is_ok());
        // 不存在的 id → 报错。
        assert!(matches!(run_otp(&u, 9999), Err(Error::Other(_))));
        cleanup(&p);
    }

    // --- 无头建库(init) ---

    #[test]
    fn run_init_creates_unlockable_empty_vault() {
        // 默认 KDF(64MiB)一次派生约 0.3–1s;这是唯一一个默认 KDF 的 init 测试,可接受。
        // 用 ZKV_PASSPHRASE 绕开 rpassword(无 TTY 测试环境)。
        let _g = env_lock();
        let p = tmp_path("init_ok");
        cleanup(&p);

        // SAFETY: 持 env_lock,本函数内串行 set/remove,无并发竞态。
        unsafe {
            std::env::set_var("ZKV_PASSPHRASE", "pw");
        }
        let res = run_init(&p, None);
        // SAFETY: 同上。
        unsafe {
            std::env::remove_var("ZKV_PASSPHRASE");
        }

        res.unwrap();
        assert!(p.exists(), "vault file should exist after init");

        // 空库可解锁,items 为 0。
        let db = vault::unlock(&p, "pw").unwrap();
        let items = search::search(db.conn(), &Filter::default()).unwrap();
        assert!(items.is_empty());
        cleanup(&p);
    }

    #[test]
    fn run_init_refuses_existing_vault() {
        // 先用 fast KDF 建一个库,再 init 同路径 → 报错且信息含 "already exists"。
        let p = tmp_path("init_exists");
        cleanup(&p);
        vault::create_with_params(&p, "pw", &fast_kdf()).unwrap();
        assert!(p.exists());

        let pf = write_passfile("init_exists");
        let err = run_init(&p, Some(&pf));
        assert!(matches!(err, Err(Error::Other(_))));
        let msg = match err {
            Err(Error::Other(m)) => m,
            _ => String::new(),
        };
        assert!(
            msg.contains("already exists"),
            "expected 'already exists' in error, got: {msg}"
        );
        cleanup(&p);
    }

    // --- 口令来源 ---
    //
    // 涉及 `ZKV_PASSPHRASE` 环境变量的用例合并到单个测试中,避免默认并行测试运行器下
    // 多个测试并发 set/remove 同一环境变量造成的竞态(env 非线程隔离)。
    // passfile/纯函数用例不受影响,保持独立。

    #[test]
    fn read_passphrase_env_paths() {
        let _g = env_lock();
        // 1. 环境变量优先级最高。
        // SAFETY: 该测试独占对 ZKV_PASSPHRASE 的 set/remove(本函数内串行)。
        unsafe {
            std::env::set_var("ZKV_PASSPHRASE", "env-secret");
        }
        let got = read_passphrase(None).unwrap();
        assert_eq!(got.as_str(), "env-secret");

        // 2. 环境变量优先级高于 passfile。
        let pf = tmp_path("passfile_prec");
        std::fs::write(&pf, "file-loses\n").unwrap();
        let got = read_passphrase(Some(&pf)).unwrap();
        assert_eq!(got.as_str(), "env-secret");
        cleanup(&pf);

        // 清理:之后走 passfile/TTY 路径。
        // SAFETY: 同上。
        unsafe {
            std::env::remove_var("ZKV_PASSPHRASE");
        }

        // 3. passfile 路径(去末尾换行,LF 与 CRLF)。
        let p = tmp_path("passfile");
        std::fs::write(&p, "file-secret\n").unwrap();
        let got = read_passphrase(Some(&p)).unwrap();
        assert_eq!(got.as_str(), "file-secret");
        cleanup(&p);

        let p2 = tmp_path("passfile2");
        std::fs::write(&p2, "crlf-secret\r\n").unwrap();
        let got2 = read_passphrase(Some(&p2)).unwrap();
        assert_eq!(got2.as_str(), "crlf-secret");
        cleanup(&p2);
    }

    #[test]
    fn read_passphrase_missing_passfile_errors() {
        // 必须串行:若并行测试此刻设置了 ZKV_PASSPHRASE,本测试会错误地走 env 路径。
        let _g = env_lock();
        // 兜底:确保本测试开始时 env 未设置。
        // SAFETY: 已持 env_lock,无并发访问。
        unsafe {
            std::env::remove_var("ZKV_PASSPHRASE");
        }
        let p = tmp_path("nope_passfile");
        cleanup(&p);
        assert!(read_passphrase(Some(&p)).is_err());
    }

    #[test]
    fn read_new_passphrase_env_paths() {
        // 串行:涉及 ZKV_NEW_PASSPHRASE 环境变量。
        let _g = env_lock();
        // 1. 环境变量优先级最高。
        // SAFETY: 持 env_lock,本函数内串行 set/remove。
        unsafe {
            std::env::set_var("ZKV_NEW_PASSPHRASE", "new-env-secret");
        }
        let got = read_new_passphrase(None).unwrap();
        assert_eq!(got.as_str(), "new-env-secret");

        // 2. 环境变量优先级高于 --new-passfile。
        let pf = tmp_path("new_pf_prec");
        std::fs::write(&pf, "file-loses\n").unwrap();
        let got = read_new_passphrase(Some(&pf)).unwrap();
        assert_eq!(got.as_str(), "new-env-secret");
        cleanup(&pf);

        // SAFETY: 同上。
        unsafe {
            std::env::remove_var("ZKV_NEW_PASSPHRASE");
        }

        // 3. --new-passfile 路径(去末尾换行)。
        let p = tmp_path("new_pf");
        std::fs::write(&p, "new-file-secret\n").unwrap();
        let got = read_new_passphrase(Some(&p)).unwrap();
        assert_eq!(got.as_str(), "new-file-secret");
        cleanup(&p);
    }

    #[test]
    fn run_passwd_roundtrip_and_old_fails() {
        // fast KDF 库 → passwd → 新口令解锁 Ok、旧口令 Err(BadPassphrase)。
        // 串行:read_passphrase/read_new_passphrase 读 ZKV_PASSPHRASE/
        // ZKV_NEW_PASSPHRASE 环境变量,须防止与其他 env 测试并发竞态。
        let _g = env_lock();
        // 兜底:确保开始时两个 env 均未设置。
        // SAFETY: 持 env_lock,无并发访问。
        unsafe {
            std::env::remove_var("ZKV_PASSPHRASE");
            std::env::remove_var("ZKV_NEW_PASSPHRASE");
        }
        let p = tmp_path("passwd_cli");
        cleanup(&p);
        let kdf = fast_kdf();
        vault::create_with_params(&p, "pw", &kdf).unwrap();

        // 旧口令错 → BadPassphrase,且库未变(原口令仍可用)。
        // 注:run_passwd 先读旧/新口令再调 change_passphrase,故此处也需提供
        // new-passfile,否则会落到无 TTY 的 rpassword 提示。
        let pf_old = tmp_path("pf_old_bad");
        std::fs::write(&pf_old, "wrong\n").unwrap();
        let pf_new_dummy = tmp_path("pf_new_dummy");
        std::fs::write(&pf_new_dummy, "whatever\n").unwrap();
        assert!(matches!(
            run_passwd(&p, Some(&pf_old), Some(&pf_new_dummy)),
            Err(Error::BadPassphrase)
        ));
        assert!(vault::unlock(&p, "pw").is_ok());
        cleanup(&pf_old);
        cleanup(&pf_new_dummy);

        // 改口令:旧用 passfile、新用 passfile。
        let pf_old_ok = tmp_path("pf_old_ok");
        std::fs::write(&pf_old_ok, "pw\n").unwrap();
        let pf_new = tmp_path("pf_new");
        std::fs::write(&pf_new, "newpw\n").unwrap();
        run_passwd(&p, Some(&pf_old_ok), Some(&pf_new)).unwrap();

        // 旧口令失败、新口令成功。
        assert!(matches!(
            vault::unlock(&p, "pw"),
            Err(Error::BadPassphrase)
        ));
        assert!(vault::unlock(&p, "newpw").is_ok());
        cleanup(&pf_old_ok);
        cleanup(&pf_new);
        cleanup(&p);
    }

    #[test]
    fn unlocked_save_roundtrips() {
        let p = make_vault("save");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        // 再保存一次(用已派生 key)应成功。
        assert!(u.save().is_ok());
        // 再次解锁仍可读。
        let pf2 = write_passfile("u2");
        let u2 = Unlocked::unlock(&p, Some(&pf2)).unwrap();
        let items = search::search(u2.db.conn(), &Filter::default()).unwrap();
        assert_eq!(items.len(), 2);
        cleanup(&p);
    }

    // --- 写命令(add/edit/rm) ---

    #[test]
    fn run_add_inserts_and_persists() {
        let p = make_vault("add");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        let data = r#"{"type":"password","username":"bob","password":"pw1","url":"https://x","totp_secret":"","notes":""}"#;
        let id = run_add(&u, "Server", "password", Some(data), &EditFields::default(), vec!["ops".into()], true, None, None).unwrap();
        assert!(id > 0);

        // 内存中能取到正确字段。
        let got = store::get_item(u.db.conn(), id).unwrap().unwrap();
        assert_eq!(got.title, "Server");
        assert_eq!(got.template_id, "password");
        assert!(got.favorite);
        assert_eq!(got.tags, vec!["ops".to_string()]);
        assert_eq!(item_field(&got, "username").unwrap(), "bob");

        // 落盘后重新解锁读回(原 2 条 + 新增 1 条)。
        drop(u);
        let pf2 = write_passfile("u2");
        let u2 = Unlocked::unlock(&p, Some(&pf2)).unwrap();
        let got2 = store::get_item(u2.db.conn(), id).unwrap().unwrap();
        assert_eq!(got2.title, "Server");
        assert_eq!(got2.template_id, "password");
        let items = search::search(u2.db.conn(), &Filter::default()).unwrap();
        assert_eq!(items.len(), 3);
        cleanup(&p);
    }

    #[test]
    fn run_add_bad_data_json_errors() {
        let p = make_vault("addbad");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        // 缺 type tag → serde 报错(非 Error::Other,但仍是 Err)。
        assert!(run_add(&u, "X", "password", Some("{ not json"), &EditFields::default(), vec![], false, None, None).is_err());
        cleanup(&p);
    }

    #[test]
    fn run_edit_updates_fields_and_type() {
        let p = make_vault("edit");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        // id=1 是 GitHub password。
        let new_data =
            r#"{"type":"note","format":"text","content":"moved"}"#;
        run_edit(
            &u,
            1,
            Some("Renamed"),
            Some(new_data),
            Some(vec!["archive".into()]),
            Some(false),
            None,
            &EditFields::default(),
            &TagDelta::default(),
            None,
        )
        .unwrap();

        let got = store::get_item(u.db.conn(), 1).unwrap().unwrap();
        assert_eq!(got.title, "Renamed");
        assert_eq!(got.template_id, "note"); // 随 data 同步
        assert_eq!(got.tags, vec!["archive".to_string()]);
        assert!(!got.favorite);
        assert_eq!(item_field(&got, "content").unwrap(), "moved");

        // 落盘读回。
        drop(u);
        let pf2 = write_passfile("u2");
        let u2 = Unlocked::unlock(&p, Some(&pf2)).unwrap();
        let got2 = store::get_item(u2.db.conn(), 1).unwrap().unwrap();
        assert_eq!(got2.title, "Renamed");
        assert_eq!(got2.template_id, "note");
        cleanup(&p);
    }

    #[test]
    fn run_edit_partial_title_only() {
        let p = make_vault("edit2");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        run_edit(&u, 1, Some("JustTitle"), None, None, None, None, &EditFields::default(), &TagDelta::default(), None).unwrap();
        let got = store::get_item(u.db.conn(), 1).unwrap().unwrap();
        assert_eq!(got.title, "JustTitle");
        // data 未动,仍是 password。
        assert_eq!(got.template_id, "password");
        cleanup(&p);
    }

    #[test]
    fn run_edit_nothing_to_change_errors() {
        let p = make_vault("editnone");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        let err = run_edit(&u, 1, None, None, None, None, None, &EditFields::default(), &TagDelta::default(), None);
        assert!(matches!(err, Err(Error::Other(_))));
    }

    #[test]
    fn run_edit_missing_item_errors() {
        let p = make_vault("editmissing");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        let err = run_edit(&u, 9999, Some("x"), None, None, None, None, &EditFields::default(), &TagDelta::default(), None);
        assert!(matches!(err, Err(Error::Other(_))));
    }

    #[test]
    fn run_rm_yes_deletes() {
        let p = make_vault("rmyes");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        run_rm(&u, 1, true).unwrap();
        // 删除后取不到。
        assert!(store::get_item(u.db.conn(), 1).unwrap().is_none());

        // 落盘读回:仅剩 1 条。
        drop(u);
        let pf2 = write_passfile("u2");
        let u2 = Unlocked::unlock(&p, Some(&pf2)).unwrap();
        assert!(store::get_item(u2.db.conn(), 1).unwrap().is_none());
        let items = search::search(u2.db.conn(), &Filter::default()).unwrap();
        assert_eq!(items.len(), 1);
        cleanup(&p);
    }

    #[test]
    fn run_rm_missing_item_errors() {
        let p = make_vault("rmmissing");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        // yes=true 仍要先确认 item 存在 → 报错。
        let err = run_rm(&u, 9999, true);
        assert!(matches!(err, Err(Error::Other(_))));
        cleanup(&p);
    }

    // --- 分类/标签管理(cat/tag)+ edit --cat + ls -F ---

    #[test]
    fn run_cat_add_ls_rm_roundtrip() {
        let p = make_vault("cat");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();

        // add 一个顶层分类。
        let cid = run_cat_add(&u, "Personal", None).unwrap();
        assert!(cid > 0);
        // add 一个带父分类的子分类。
        let sub = run_cat_add(&u, "Banking", Some("Personal")).unwrap();
        assert!(sub > 0);

        // ls 不报错且能看到两个分类(直接查 store 验证,避免依赖 stdout 捕获)。
        assert!(run_cat_ls(&u).is_ok());
        let cats = store::list_categories(u.db.conn()).unwrap();
        assert_eq!(cats.len(), 2);
        assert!(cats.iter().any(|c| c.name == "Personal"));
        assert!(cats.iter().any(|c| c.name == "Banking" && c.parent_id == Some(cid)));

        // rm by 名。
        run_cat_rm(&u, "Banking").unwrap();
        assert_eq!(store::list_categories(u.db.conn()).unwrap().len(), 1);
        // rm by id。
        run_cat_rm(&u, &cid.to_string()).unwrap();
        assert!(store::list_categories(u.db.conn()).unwrap().is_empty());

        // rm 不存在的分类 → 报错。
        assert!(run_cat_rm(&u, "Nope").is_err());

        // 落盘读回:分类确实删除持久化。
        drop(u);
        let pf2 = write_passfile("u2");
        let u2 = Unlocked::unlock(&p, Some(&pf2)).unwrap();
        assert!(store::list_categories(u2.db.conn()).unwrap().is_empty());
        cleanup(&p);
    }

    #[test]
    fn run_cat_add_bad_parent_errors() {
        let p = make_vault("catbad");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        // 父分类不存在 → 报错。
        assert!(run_cat_add(&u, "X", Some("Nope")).is_err());
        cleanup(&p);
    }

    #[test]
    fn run_tag_ls_rm_mv_roundtrip() {
        let p = make_vault("tag");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();

        // 初始库已含 work / vip 标签(make_vault 注入)。
        assert!(run_tag_ls(&u).is_ok());
        let tags = store::list_tags(u.db.conn()).unwrap();
        assert!(tags.iter().any(|t| t.name == "work"));
        assert!(tags.iter().any(|t| t.name == "vip"));

        // mv:work → work2。
        run_tag_mv(&u, "work", "work2").unwrap();
        let tags = store::list_tags(u.db.conn()).unwrap();
        assert!(tags.iter().any(|t| t.name == "work2"));
        assert!(!tags.iter().any(|t| t.name == "work"));

        // rm:删除 work2。
        run_tag_rm(&u, "work2").unwrap();
        let tags = store::list_tags(u.db.conn()).unwrap();
        assert!(!tags.iter().any(|t| t.name == "work2"));

        // rm 不存在的标签 → 报错。
        assert!(run_tag_rm(&u, "ghost").is_err());
        // mv 不存在的标签 → 报错。
        assert!(run_tag_mv(&u, "ghost", "x").is_err());

        // 落盘读回:改名持久化。
        drop(u);
        let pf2 = write_passfile("u2");
        let u2 = Unlocked::unlock(&p, Some(&pf2)).unwrap();
        let tags2 = store::list_tags(u2.db.conn()).unwrap();
        assert!(tags2.iter().any(|t| t.name == "vip"));
        assert!(!tags2.iter().any(|t| t.name == "work2"));
        cleanup(&p);
    }

    #[test]
    fn run_edit_sets_category() {
        let p = make_vault("editcat");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();

        // 先建一个分类,再把 id=1 的 item 设到该分类下。
        let cid = run_cat_add(&u, "Work", None).unwrap();
        run_edit(&u, 1, None, None, None, None, Some("Work"), &EditFields::default(), &TagDelta::default(), None).unwrap();

        let got = store::get_item(u.db.conn(), 1).unwrap().unwrap();
        assert_eq!(got.category_id, Some(cid));

        // 未知分类名 → 报错。
        assert!(run_edit(&u, 1, None, None, None, None, Some("Ghost"), &EditFields::default(), &TagDelta::default(), None).is_err());
        cleanup(&p);
    }

    #[test]
    fn run_ls_favorite_only_returns_favorites() {
        let p = make_vault("lsfav");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        // make_vault 的两条 item 都不是收藏;add 一条收藏项。
        let data = r#"{"type":"password","username":"bob","password":"pw","url":"","totp_secret":"","notes":""}"#;
        let _fav_id = run_add(&u, "Fav", "password", Some(data), &EditFields::default(), vec![], true, None, None).unwrap();

        let f = ListFilter::default();
        // favorite=false:返回全部 3 条。
        let sf_all = to_search_filter(&f, None);
        let all = search::search(u.db.conn(), &sf_all).unwrap();
        assert_eq!(all.len(), 3);

        // favorite=true:只返回 1 条(收藏项)。
        assert!(run_ls(&u, &f, true, false).is_ok());
        let mut f2 = f.clone();
        f2.favorite_only = true;
        let sf_fav = to_search_filter(&f2, None);
        let favs = search::search(u.db.conn(), &sf_fav).unwrap();
        assert_eq!(favs.len(), 1);
        assert!(favs.iter().all(|i| i.favorite));
        cleanup(&p);
    }

    // --- 附件管理(attach add/ls/get/rm) ---

    /// 构造一个临时附件文件,内容 = `bytes`,**文件名保持 `name`**(含扩展名),
    /// 放在临时目录下。文件名决定了 filename/mime 推断,故不能用带计数器的 tmp_path。
    fn write_att_file(name: &str, bytes: &[u8]) -> PathBuf {
        let mut p = std::env::temp_dir();
        p.push(format!("zkv_att_{}_{}", std::process::id(), name));
        std::fs::write(&p, bytes).unwrap();
        p
    }

    /// 直接查 attachments 表行数(不含 blob 列),用于断言。
    fn count_attachments(conn: &rusqlite::Connection, item_id: i64) -> i64 {
        conn.query_row(
            "SELECT COUNT(*) FROM attachments WHERE item_id = ?1",
            rusqlite::params![item_id],
            |r| r.get::<_, i64>(0),
        )
        .unwrap()
    }

    #[test]
    fn guess_mime_known_and_unknown() {
        // 已知扩展名。
        assert_eq!(
            guess_mime(Path::new("a.pdf")).as_deref(),
            Some("application/pdf")
        );
        assert_eq!(
            guess_mime(Path::new("b.PNG")).as_deref(),
            Some("image/png")
        );
        assert_eq!(
            guess_mime(Path::new("c.jpeg")).as_deref(),
            Some("image/jpeg")
        );
        assert_eq!(
            guess_mime(Path::new("d.json")).as_deref(),
            Some("application/json")
        );
        assert_eq!(
            guess_mime(Path::new("e.docx")).as_deref(),
            Some("application/vnd.openxmlformats-officedocument.wordprocessingml.document")
        );
        // 未知扩展 / 无扩展 → None。
        assert_eq!(guess_mime(Path::new("f.xyz")), None);
        assert_eq!(guess_mime(Path::new("noext")), None);
    }

    #[test]
    fn attachment_belongs_to_logic() {
        let p = make_vault("att_belongs");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        let conn = u.db.conn();
        // 插一个附件到 item 1。
        let mut att = Attachment {
            id: None,
            item_id: 1,
            filename: "x.bin".into(),
            mime_type: None,
            size: 0,
            blob: vec![1, 2, 3],
        };
        let aid = store::insert_attachment(conn, &mut att).unwrap();
        // 归属正确 / 不归属其它 item / 不存在。
        assert!(attachment_belongs_to(conn, aid, 1).unwrap());
        assert!(!attachment_belongs_to(conn, aid, 2).unwrap());
        assert!(!attachment_belongs_to(conn, 99999, 1).unwrap());
        cleanup(&p);
    }

    #[test]
    fn run_attach_add_ls_get_rm_roundtrip() {
        let p = make_vault("att_flow");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();

        // 1. add:把一个临时文件挂到 item 1。
        let blob = b"\x00hello-attachment\xff".to_vec();
        let att_file = write_att_file("src.txt", &blob);
        let aid = run_attach_add(&u, 1, &att_file, Some("text/plain")).unwrap();
        assert!(aid > 0);
        assert_eq!(count_attachments(u.db.conn(), 1), 1);

        // 验证落库的元数据(filename 保留 basename、size/mime/blob)。
        let got = store::get_attachment(u.db.conn(), aid).unwrap().unwrap();
        let basename = att_file
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("");
        assert_eq!(got.filename, basename);
        assert_eq!(got.size, blob.len() as i64);
        assert_eq!(got.mime_type.as_deref(), Some("text/plain"));
        assert_eq!(got.blob, blob);
        cleanup(&att_file);

        // 2. ls:不报错,且 item 1 有 1 条;item 2 为空。
        assert!(run_attach_ls(&u, 1).is_ok());
        assert_eq!(count_attachments(u.db.conn(), 1), 1);
        assert_eq!(count_attachments(u.db.conn(), 2), 0);

        // 3. get -o <out>:读回对比 blob 一致。
        let out = tmp_path("att_out");
        run_attach_get(&u, 1, aid, Some(&out)).unwrap();
        let read_back = std::fs::read(&out).unwrap();
        assert_eq!(read_back, blob);
        cleanup(&out);

        // get 归属错误(item 不匹配)→ 报错。
        assert!(matches!(
            run_attach_get(&u, 2, aid, None),
            Err(Error::Other(_))
        ));
        // get 不存在的附件 → 报错。
        assert!(matches!(
            run_attach_get(&u, 1, 99999, None),
            Err(Error::Other(_))
        ));

        // 4. rm:删除后再 ls 为空。
        run_attach_rm(&u, 1, aid).unwrap();
        assert_eq!(count_attachments(u.db.conn(), 1), 0);
        assert!(matches!(
            run_attach_rm(&u, 1, aid),
            Err(Error::Other(_))
        ));

        // 落盘读回:删除持久化。
        drop(u);
        let pf2 = write_passfile("u2");
        let u2 = Unlocked::unlock(&p, Some(&pf2)).unwrap();
        assert_eq!(count_attachments(u2.db.conn(), 1), 0);
        cleanup(&p);
    }

    #[test]
    fn run_attach_add_missing_item_errors() {
        let p = make_vault("att_baditem");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        let f = write_att_file("x", b"data");
        // item 不存在 → Error::Other。
        let err = run_attach_add(&u, 9999, &f, None);
        assert!(matches!(err, Err(Error::Other(_))));
        cleanup(&f);
        cleanup(&p);
    }

    #[test]
    fn run_attach_add_missing_file_errors() {
        let p = make_vault("att_badfile");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        // 源文件不存在 → 读文件失败(冒泡为 Err)。
        let f = tmp_path("does_not_exist");
        cleanup(&f);
        assert!(run_attach_add(&u, 1, &f, None).is_err());
        cleanup(&p);
    }

    #[test]
    fn run_attach_ls_empty_prints_no_attachments() {
        let p = make_vault("att_ls_empty");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        // item 1 无附件 → Ok(打印 (no attachments))。
        assert!(run_attach_ls(&u, 1).is_ok());
        assert_eq!(count_attachments(u.db.conn(), 1), 0);
        cleanup(&p);
    }

    #[test]
    fn run_attach_add_guesses_mime_from_extension() {
        let p = make_vault("att_mime");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        // 不传 --mime,由扩展名推断 .json。
        let f = write_att_file("data.json", b"{}");
        let aid = run_attach_add(&u, 1, &f, None).unwrap();
        let got = store::get_attachment(u.db.conn(), aid).unwrap().unwrap();
        assert_eq!(got.mime_type.as_deref(), Some("application/json"));
        cleanup(&f);
        cleanup(&p);
    }

    // --- 密码生成(generate_password / run_gen / add --gen-password) ---

    /// 字符池基集(字母 + 数字)。
    fn is_alnum(c: char) -> bool {
        c.is_ascii_alphanumeric()
    }
    /// 是否属于符号集。
    fn is_symbol(c: char) -> bool {
        "!@#$%^&*()-_=+[]{};:,.?/".contains(c)
    }
    /// 是否属于易混集。
    fn is_ambiguous(c: char) -> bool {
        "0Oo1lI|5S2ZB8".contains(c)
    }

    #[test]
    fn generate_password_default_length_and_charset() {
        let pw = generate_password(20, true, false).unwrap();
        assert_eq!(pw.len(), 20);
        // 默认含符号 → 池里每个字符应来自 alnum 或符号集。
        assert!(pw.chars().all(|c| is_alnum(c) || is_symbol(c)));
    }

    #[test]
    fn generate_password_no_symbols() {
        let pw = generate_password(40, false, false).unwrap();
        assert_eq!(pw.len(), 40);
        // 不含符号:全字母数字,且不含任何符号集字符。
        assert!(pw.chars().all(is_alnum));
        assert!(!pw.chars().any(is_symbol));
    }

    #[test]
    fn generate_password_no_ambiguous() {
        let pw = generate_password(40, true, true).unwrap();
        assert_eq!(pw.len(), 40);
        // 不含任何易混字符。
        assert!(!pw.chars().any(is_ambiguous));
    }

    #[test]
    fn generate_password_length_respected() {
        for &len in &[4usize, 5, 16, 32, 100] {
            let pw = generate_password(len, true, false).unwrap();
            assert_eq!(pw.len(), len);
        }
    }

    #[test]
    fn generate_password_two_runs_differ() {
        // 概率性:两次独立生成应(几乎必然)不同。
        let a = generate_password(32, true, false).unwrap();
        let b = generate_password(32, true, false).unwrap();
        assert_ne!(a, b);
    }

    #[test]
    fn generate_password_too_short_errors() {
        assert!(matches!(
            generate_password(3, true, false),
            Err(Error::Other(m)) if m.contains("too short")
        ));
    }

    #[test]
    fn generate_password_too_long_errors() {
        assert!(matches!(
            generate_password(2000, true, false),
            Err(Error::Other(m)) if m.contains("too long")
        ));
    }

    #[test]
    fn run_gen_prints_password() {
        // run_gen 写到 stdout;验证返回 Ok(不在此捕获 stdout,仅断言不报错)。
        assert!(run_gen(16, true, false).is_ok());
        assert!(run_gen(8, false, true).is_ok());
    }

    #[test]
    fn run_add_gen_password_overrides_field() {
        let p = make_vault("addgen");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        // --data 里 password 是占位 "old",--gen-password 12 应覆盖。
        let data = r#"{"type":"password","username":"bob","password":"old","url":"https://x","totp_secret":"","notes":""}"#;
        let id = run_add(&u, "Gen", "password", Some(data), &EditFields::default(), vec![], false, Some(12), None).unwrap();
        assert!(id > 0);

        let got = store::get_item(u.db.conn(), id).unwrap().unwrap();
        let pw = item_field(&got, "password").unwrap();
        assert_eq!(pw.len(), 12);
        assert_ne!(pw, "old");
        // 默认 generate_password(len, true, true) → 含符号、去易混。
        assert!(pw.chars().all(|c| is_alnum(c) || is_symbol(c)));
        assert!(!pw.chars().any(is_ambiguous));
        cleanup(&p);
    }

    #[test]
    fn run_add_gen_password_non_password_errors() {
        let p = make_vault("addgennp");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        // note 条目 + --gen-password → 报错。
        let data = r#"{"type":"note","format":"text","content":"hi"}"#;
        let err = run_add(&u, "N", "password", Some(data), &EditFields::default(), vec![], false, Some(20), None);
        assert!(matches!(err, Err(Error::Other(m)) if m.contains("--gen-password")));
        cleanup(&p);
    }

    // --- 导入/导出(export/import) ---

    /// 构造一组混合类型条目(含特殊字符用于 CSV 转义测试)。
    fn sample_items() -> Vec<Item> {
        vec![
            Item {
        id: Some(1),
        template_id: "password".into(),
        title: "GitHub".into(),
        category_id: None,
        fields: vec![
                Field { name: "username".into(), value: "alice".into(), kind: FieldKind::Text, protected: false },
                Field { name: "password".into(), value: "p,ass\"word".into(), kind: FieldKind::Secret, protected: true },
                Field { name: "url".into(), value: "https://github.com".into(), kind: FieldKind::Text, protected: false },
                Field { name: "totp".into(), value: "JBSWY3DPEHPK3PXP".into(), kind: FieldKind::Totp, protected: true },
                Field { name: "notes".into(), value: "main\nline2".into(), kind: FieldKind::Multiline, protected: false },
            ],
        favorite: true,
        tags: vec!["work".into(), "vip".into()],
        created_at: 1_700_000_000,
        updated_at: 1_700_000_100,
    },
            Item {
        id: Some(2),
        template_id: "note".into(),
        title: "Ideas".into(),
        category_id: None,
        fields: vec![
                Field { name: "format".into(), value: "markdown".into(), kind: FieldKind::Text, protected: false },
                Field { name: "content".into(), value: "hello".into(), kind: FieldKind::Multiline, protected: false },
            ],
        favorite: false,
        tags: vec![],
        created_at: 0,
        updated_at: 0,
    },
            Item {
        id: Some(3),
        template_id: "password".into(),
        title: "Bank".into(),
        category_id: None,
        fields: vec![
                Field { name: "username".into(), value: "bob".into(), kind: FieldKind::Text, protected: false },
                Field { name: "password".into(), value: "plain".into(), kind: FieldKind::Secret, protected: true },
                Field { name: "url".into(), value: "".into(), kind: FieldKind::Text, protected: false },
                Field { name: "totp".into(), value: "".into(), kind: FieldKind::Totp, protected: true },
                Field { name: "notes".into(), value: "".into(), kind: FieldKind::Multiline, protected: false },
            ],
        favorite: false,
        tags: vec!["finance".into()],
        created_at: 0,
        updated_at: 0,
    },
        ]
    }

    #[test]
    fn json_roundtrip_lossless() {
        let items = sample_items();
        let json = export_json(&items).unwrap();
        let (back, atts) = import_json(&json).unwrap();
        assert_eq!(back.len(), items.len());
        // 裸数组形状无附件。
        assert!(atts.is_none());
        // 字段逐一对比(id 也保留)。
        for (a, b) in items.iter().zip(back.iter()) {
            assert_eq!(a.title, b.title);
            assert_eq!(a.template_id, b.template_id);
            assert_eq!(a.fields, b.fields);
            assert_eq!(a.tags, b.tags);
            assert_eq!(a.favorite, b.favorite);
        }
    }

    #[test]
    fn import_json_bad_overall_errors() {
        // 非 JSON 数组 → Err。
        assert!(import_json("{ not json").is_err());
        assert!(import_json("not an array").is_err());
        // 空数组 → Ok 空 items,无附件。
        let (items, atts) = import_json("[]").unwrap();
        assert!(items.is_empty());
        assert!(atts.is_none());
    }

    #[test]
    fn csv_export_passwords_only_and_escapes() {
        let items = sample_items();
        let (csv, skipped) = export_csv(&items);
        // note 条目被跳过。
        assert_eq!(skipped, 1);
        // header 行存在。
        assert!(csv.starts_with("title,username,password"));
        // 引号包裹的字段:含逗号/引号/换行 → 被引号包裹,内部引号翻倍。
        assert!(csv.contains("\"p,ass\"\"word\""));
        assert!(csv.contains("\"main\nline2\""));
        // tags 用 ; 分隔。
        assert!(csv.contains("work;vip"));
        // 往返解析:恰好 header + 2 个 password 记录。
        let (back, fail) = import_csv(&csv).unwrap();
        assert_eq!(fail, 0);
        assert_eq!(back.len(), 2);
    }

    #[test]
    fn csv_roundtrip_password_fields() {
        let items = sample_items();
        let (csv, _) = export_csv(&items);
        let (back, fail) = import_csv(&csv).unwrap();
        assert_eq!(fail, 0);
        // 只导出了 2 个 password。
        assert_eq!(back.len(), 2);
        assert!(back.iter().all(|i| i.template_id == "password"));

        // GitHub 行字段一致(含特殊字符)。
        let gh = back.iter().find(|i| i.title == "GitHub").unwrap();
        assert_eq!(item_field(gh, "username").unwrap(), "alice");
        assert_eq!(item_field(gh, "password").unwrap(), "p,ass\"word");
        assert_eq!(item_field(gh, "notes").unwrap(), "main\nline2");
        assert_eq!(gh.tags, vec!["work".to_string(), "vip".to_string()]);
    }

    #[test]
    fn csv_import_skips_bad_rows() {
        // header + 1 好行 + 1 坏行(title 列索引越界 → 计入 fail)。
        let csv = "title,username,password\nok,u,p\n\n";
        let (items, fail) = import_csv(csv).unwrap();
        assert_eq!(items.len(), 1);
        assert_eq!(items[0].title, "ok");
        // 空行计为 fail(无 title 列数据)。
        assert_eq!(fail, 1);
    }

    #[test]
    fn csv_import_missing_title_header_errors() {
        let csv = "username,password\nu,p\n";
        assert!(import_csv(csv).is_err());
        // 空输入 → Ok 空,不报错。
        let (items, fail) = import_csv("").unwrap();
        assert!(items.is_empty());
        assert_eq!(fail, 0);
    }

    #[test]
    fn csv_import_missing_columns_default_empty() {
        // 只给 title 列,其余缺列按空串处理。
        let csv = "title\nOnly\n";
        let (items, fail) = import_csv(csv).unwrap();
        assert_eq!(fail, 0);
        assert_eq!(items.len(), 1);
        assert_eq!(items[0].title, "Only");
        assert_eq!(item_field(&items[0], "password").unwrap(), "");
        assert!(items[0].tags.is_empty());
    }

    /// 端到端:导出 JSON 到新库导入,条数/字段一致。
    #[test]
    fn export_import_json_end_to_end() {
        let p = make_vault("exp_json");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        // 原库 2 条(make_vault)。
        let src = store::list_items(u.db.conn()).unwrap();
        assert_eq!(src.len(), 2);
        let json = export_json(&src).unwrap();
        drop(u);

        // 新库 + 导入。
        let p2 = tmp_path("exp_json_dst");
        cleanup(&p2);
        vault::create_with_params(&p2, "pw", &fast_kdf()).unwrap();
        let pf2 = write_passfile("u2");
        let u2 = Unlocked::unlock(&p2, Some(&pf2)).unwrap();
        // 写到临时输入文件,经 run_import 文件路径。
        let inp = tmp_path("exp_json_in");
        std::fs::write(&inp, json).unwrap();
        let res = run_import(&u2, Format::Json, Some(&inp)).unwrap();
        assert_eq!(res.ok, 2);
        assert_eq!(res.fail, 0);
        cleanup(&inp);

        // 验证导入后字段一致(按标题找)。
        let dst = store::list_items(u2.db.conn()).unwrap();
        assert_eq!(dst.len(), 2);
        let gh = dst.iter().find(|i| i.title == "GitHub").unwrap();
        assert_eq!(gh.template_id, "password");
        assert_eq!(item_field(gh, "username").unwrap(), "alice");
        assert_eq!(gh.tags, vec!["vip".to_string(), "work".to_string()]);

        // 导入的 id 应是新建(不等于导出源 id 的 None→被填)。
        assert!(gh.id.is_some());
        cleanup(&p);
        cleanup(&p2);
    }

    /// 端到端:CSV 导入到库,password 条目字段一致。
    #[test]
    fn export_import_csv_end_to_end() {
        let p = make_vault("exp_csv");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        // 原库含 1 个 password(GitHub)+ 1 个 note(被跳过)。
        let src = store::list_items(u.db.conn()).unwrap();
        let (csv, skipped) = export_csv(&src);
        assert_eq!(skipped, 1); // note 跳过
        drop(u);

        let p2 = tmp_path("exp_csv_dst");
        cleanup(&p2);
        vault::create_with_params(&p2, "pw", &fast_kdf()).unwrap();
        let pf2 = write_passfile("u2");
        let u2 = Unlocked::unlock(&p2, Some(&pf2)).unwrap();
        let inp = tmp_path("exp_csv_in");
        std::fs::write(&inp, csv).unwrap();
        let res = run_import(&u2, Format::Csv, Some(&inp)).unwrap();
        assert_eq!(res.ok, 1);
        assert_eq!(res.fail, 0);
        cleanup(&inp);

        let dst = store::list_items(u2.db.conn()).unwrap();
        assert_eq!(dst.len(), 1);
        assert_eq!(dst[0].title, "GitHub");
        assert_eq!(item_field(&dst[0], "username").unwrap(), "alice");
        cleanup(&p);
        cleanup(&p2);
    }

    /// 容错:JSON 含一条坏数据,整体解析失败(计入 fail)。
    #[test]
    fn run_import_json_bad_data_counts_failed() {
        let p = make_vault("imp_bad");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        // 整体坏 JSON → 解析失败,fail=1,ok=0,不 panic。
        let inp = tmp_path("imp_bad_in");
        std::fs::write(&inp, "{ not valid json array").unwrap();
        let res = run_import(&u, Format::Json, Some(&inp)).unwrap();
        assert_eq!(res.ok, 0);
        assert_eq!(res.fail, 1);
        cleanup(&inp);
        cleanup(&p);
    }

    /// 容错:CSV 含坏行,好行仍导入。
    #[test]
    fn run_import_csv_partial_success() {
        let p = make_vault("imp_csv_partial");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        let inp = tmp_path("imp_csv_in");
        // 1 好 + 1 空(fail)。
        std::fs::write(&inp, "title,username,password\nGood,u,p\n\n").unwrap();
        let res = run_import(&u, Format::Csv, Some(&inp)).unwrap();
        assert_eq!(res.ok, 1);
        assert_eq!(res.fail, 1);
        cleanup(&inp);

        // make_vault 已含 2 条,导入新增 1 条 → 共 3 条,含 Good。
        let dst = store::list_items(u.db.conn()).unwrap();
        assert_eq!(dst.len(), 3);
        assert!(dst.iter().any(|i| i.title == "Good"));
        cleanup(&p);
    }

    // --- 附件导出/导入(信封 + id 重映射)---

    /// build_backup_json 产出 items + attachments 双层结构。
    #[test]
    fn build_backup_json_has_envelope_shape() {
        let items = sample_items();
        let atts = vec![Attachment {
            id: Some(99),
            item_id: 1,
            filename: "a.bin".into(),
            mime_type: Some("application/octet-stream".into()),
            size: 3,
            blob: vec![0x01, 0x02, 0x03],
        }];
        let json = build_backup_json(&items, &atts).unwrap();
        let v: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert!(v.get("items").unwrap().is_array());
        assert_eq!(v["items"].as_array().unwrap().len(), items.len());
        let a = v.get("attachments").unwrap().as_array().unwrap();
        assert_eq!(a.len(), 1);
        assert_eq!(a[0]["filename"], "a.bin");
        assert_eq!(a[0]["item_id"], 1);
        // blob 序列化为字节数字数组。
        assert_eq!(a[0]["blob"].as_array().unwrap().len(), 3);
    }

    /// 往返核心:建库 → 插 item + 挂附件(已知 blob)→ export json → 新库 import json
    /// → 断言:item 在、附件在且 blob 字节一致、附件挂到正确的新 item。
    #[test]
    fn backup_json_roundtrip_preserves_attachment_blob() {
        let p = make_vault("backup_rt");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        // make_vault 的 GitHub 是 id=1。挂一个已知 blob 的附件。
        let known_blob = vec![0xDE, 0xAD, 0xBE, 0xEF, 0xCA, 0xFE];
        let mut att = Attachment {
            id: None,
            item_id: 1, // GitHub
            filename: "secret.bin".into(),
            mime_type: Some("application/octet-stream".into()),
            size: 0,
            blob: known_blob.clone(),
        };
        store::insert_attachment(u.db.conn(), &mut att).unwrap();
        u.save().unwrap();
        drop(u);

        // 导出 JSON(信封)。
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        let items = store::list_items(u.db.conn()).unwrap();
        let atts = store::list_all_attachments(u.db.conn()).unwrap();
        assert_eq!(atts.len(), 1);
        let json = build_backup_json(&items, &atts).unwrap();
        drop(u);

        // 新库导入。
        let p2 = tmp_path("backup_rt_dst");
        cleanup(&p2);
        vault::create_with_params(&p2, "pw", &fast_kdf()).unwrap();
        let pf2 = write_passfile("u2");
        let u2 = Unlocked::unlock(&p2, Some(&pf2)).unwrap();
        let inp = tmp_path("backup_rt_in");
        std::fs::write(&inp, json).unwrap();
        let res = run_import(&u2, Format::Json, Some(&inp)).unwrap();
        assert_eq!(res.ok, 2); // make_vault 的 2 条
        assert_eq!(res.fail, 0);
        cleanup(&inp);

        // 新库里 GitHub 的新 id。
        let dst = store::list_items(u2.db.conn()).unwrap();
        let gh = dst.iter().find(|i| i.title == "GitHub").unwrap();
        let new_gh_id = gh.id.unwrap();

        // 附件挂到正确的新 item 且 blob 字节一致。
        let new_atts = store::list_attachments(u2.db.conn(), new_gh_id).unwrap();
        assert_eq!(new_atts.len(), 1);
        let na = &new_atts[0];
        assert_eq!(na.filename, "secret.bin");
        assert_eq!(na.mime_type.as_deref(), Some("application/octet-stream"));
        assert_eq!(na.size, known_blob.len() as i64);
        assert_eq!(na.blob, known_blob);
        // 附件 item_id 必须重映射到新 id(而非旧的 1)。
        assert_eq!(na.item_id, new_gh_id);

        cleanup(&p);
        cleanup(&p2);
    }

    /// 向后兼容:旧裸数组 `[{...}]`(无附件)仍正常导入。
    #[test]
    fn import_json_plain_array_backward_compat() {
        let raw = r#"[{"id":5,"template_id":"password","title":"Legacy","category_id":null,"fields":[{"name":"username","value":"u","kind":"text","protected":false}],"favorite":false,"tags":[],"created_at":0,"updated_at":0}]"#;
        let (items, atts) = import_json(raw).unwrap();
        assert_eq!(items.len(), 1);
        assert_eq!(items[0].title, "Legacy");
        assert!(atts.is_none(), "裸数组形状应无附件");
    }

    /// 信封解析:items + attachments 都能取到。
    #[test]
    fn import_json_envelope_yields_attachments() {
        let raw = r#"{"items":[{"id":1,"template_id":"password","title":"X","category_id":null,"fields":[],"favorite":false,"tags":[],"created_at":0,"updated_at":0}],"attachments":[{"id":null,"item_id":1,"filename":"f.txt","mime_type":null,"size":0,"blob":[65,66]}]}"#;
        let (items, atts) = import_json(raw).unwrap();
        assert_eq!(items.len(), 1);
        let atts = atts.expect("信封应有附件");
        assert_eq!(atts.len(), 1);
        assert_eq!(atts[0].filename, "f.txt");
        assert_eq!(atts[0].blob, vec![0x41, 0x42]);
    }

    /// 容错:信封里一个坏 attachment(item_id 指向不存在的 item)→ 计 failed,
    /// 其余成功;item 正常导入。
    #[test]
    fn run_import_envelope_bad_attachment_counts_failed() {
        // 手工构造信封:1 个 item(id=1),2 个附件——其一 item_id=1(命中),
        // 另一 item_id=999(孤立项 → failed)。
        let raw = r#"{"items":[{"id":1,"template_id":"password","title":"H","category_id":null,"fields":[],"favorite":false,"tags":[],"created_at":0,"updated_at":0}],"attachments":[{"id":null,"item_id":1,"filename":"ok.bin","mime_type":null,"size":0,"blob":[1,2]},{"id":null,"item_id":999,"filename":"orphan.bin","mime_type":null,"size":0,"blob":[3,4]}]}"#;
        let p = make_vault("imp_env_bad");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        let inp = tmp_path("imp_env_in");
        std::fs::write(&inp, raw).unwrap();
        let res = run_import(&u, Format::Json, Some(&inp)).unwrap();
        assert_eq!(res.ok, 1); // 1 个 item
        assert_eq!(res.fail, 1); // 1 个孤儿附件
        cleanup(&inp);

        // 命中的附件确实挂到了新 item。
        let dst = store::list_items(u.db.conn()).unwrap();
        let h = dst.iter().find(|i| i.title == "H").unwrap();
        let new_id = h.id.unwrap();
        let atts = store::list_attachments(u.db.conn(), new_id).unwrap();
        assert_eq!(atts.len(), 1);
        assert_eq!(atts[0].filename, "ok.bin");
        assert_eq!(atts[0].blob, vec![0x01, 0x02]);
        cleanup(&p);
    }

    /// export -o 写文件;空库导出不报错。
    #[test]
    fn run_export_to_file_empty_vault() {
        let p = tmp_path("exp_empty");
        cleanup(&p);
        vault::create_with_params(&p, "pw", &fast_kdf()).unwrap();
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        let out = tmp_path("exp_empty_out");
        // JSON 信封导出(空 items + 空 attachments)。
        run_export(&u, Format::Json, Some(&out)).unwrap();
        let body = std::fs::read_to_string(&out).unwrap();
        assert_eq!(body.trim(), "{\"items\":[],\"attachments\":[]}");
        cleanup(&out);
        cleanup(&p);
    }

    /// import 不覆盖:重复导入创建重复条目。
    #[test]
    fn run_import_creates_duplicates() {
        let p = tmp_path("imp_dup");
        cleanup(&p);
        vault::create_with_params(&p, "pw", &fast_kdf()).unwrap();
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();

        let inp = tmp_path("imp_dup_in");
        std::fs::write(&inp, "title,username,password\nDup,u,p\n").unwrap();

        run_import(&u, Format::Csv, Some(&inp)).unwrap();
        run_import(&u, Format::Csv, Some(&inp)).unwrap();

        let dst = store::list_items(u.db.conn()).unwrap();
        // 两次导入 → 两条重复。
        assert_eq!(dst.len(), 2);
        assert!(dst.iter().all(|i| i.title == "Dup"));
        cleanup(&inp);
        cleanup(&p);
    }

    // ===========================================================================
    // 增强:otpauth 解析 / 单字段 / 标签增删 / 标题定位
    // ===========================================================================

    // --- Task 1: parse_otpauth ---

    #[test]
    fn parse_otpauth_extracts_secret() {
        let uri = "otpauth://totp/Example:alice@google.com?secret=JBSWY3DPEHPK3PXP&issuer=Example&digits=6&period=30";
        assert_eq!(parse_otpauth(uri).unwrap(), "JBSWY3DPEHPK3PXP");
    }

    #[test]
    fn parse_otpauth_without_other_params() {
        // 仅 secret 参数。
        let uri = "otpauth://totp/Foo?secret=JBSWY3DPEHPK3PXP";
        assert_eq!(parse_otpauth(uri).unwrap(), "JBSWY3DPEHPK3PXP");
    }

    #[test]
    fn parse_otpauth_bad_prefix_errors() {
        assert!(parse_otpauth("https://example.com?secret=x").is_err());
        assert!(parse_otpauth("totp/Example?secret=x").is_err());
    }

    #[test]
    fn parse_otpauth_no_secret_errors() {
        // 无 secret= 参数。
        assert!(parse_otpauth("otpauth://totp/Example?issuer=Example").is_err());
        // 无 ? query。
        assert!(parse_otpauth("otpauth://totp/Example").is_err());
        // 空 secret 值。
        assert!(parse_otpauth("otpauth://totp/Example?secret=").is_err());
    }

    #[test]
    fn parse_otpauth_percent_decodes_secret() {
        // %2F = '/',%3D = '=';解码后应还原。
        let uri = "otpauth://totp/X?secret=AB%3DCD";
        assert_eq!(parse_otpauth(uri).unwrap(), "AB=CD");
    }

    // --- 二维码导入(2FA)---

    /// (仅测试)用 qrcode dev-dep 把 payload 编码成黑模块/白底的二维码,输出 PNG 字节,
    /// 供 [`otpauth_from_qr_bytes`] / [`fetch_url_bytes`] 做离线往返验证。
    fn make_qr_png(payload: &str) -> Vec<u8> {
        let code = qrcode::QrCode::new(payload.as_bytes()).unwrap();
        let gray: image::GrayImage = code.render::<image::Luma<u8>>().build();
        let dyn_img = image::DynamicImage::ImageLuma8(gray);
        let mut buf = Vec::new();
        let mut cursor = std::io::Cursor::new(&mut buf);
        dyn_img
            .write_to(&mut cursor, image::ImageFormat::Png)
            .unwrap();
        buf
    }

    #[test]
    fn otpauth_from_qr_bytes_roundtrip() {
        let uri = "otpauth://totp/Example:alice@google.com?secret=JBSWY3DPEHPK3PXP&issuer=Example";
        let png = make_qr_png(uri);
        let got = otpauth_from_qr_bytes(&png).unwrap();
        assert_eq!(got, uri);
        // 产物能继续喂给现有 parse_otpauth 管线。
        assert_eq!(parse_otpauth(&got).unwrap(), "JBSWY3DPEHPK3PXP");
    }

    #[test]
    fn otpauth_from_qr_bytes_not_an_image() {
        // 随机字节不是合法图像 → 图像解码失败。
        assert!(otpauth_from_qr_bytes(&[0u8; 32]).is_err());
    }

    #[test]
    fn otpauth_from_qr_bytes_wrong_payload() {
        // 合法二维码但内容不是 otpauth → 报错。
        let png = make_qr_png("hello world");
        assert!(matches!(
            otpauth_from_qr_bytes(&png),
            Err(Error::Other(m)) if m.contains("no otpauth qr")
        ));
    }

    #[test]
    fn fetch_url_bytes_rejects_unsupported_scheme() {
        // file:/ftp: 等非 http/https/data 一律拒绝(顺带防止 file: 读本地文件)。
        assert!(fetch_url_bytes("file:///etc/passwd").is_err());
        assert!(fetch_url_bytes("ftp://x/y.png").is_err());
    }

    #[test]
    fn fetch_url_bytes_data_url_base64_full_chain() {
        // 真实二维码 → PNG → base64 → data: URL → 取图 → 解码:全链路(data: 不联网)。
        let uri = "otpauth://totp/X?secret=JBSWY3DPEHPK3PXP";
        let png = make_qr_png(uri);
        let b64 = data_encoding::BASE64.encode(&png);
        let data_url = format!("data:image/png;base64,{b64}");
        let bytes = fetch_url_bytes(&data_url).unwrap();
        assert_eq!(bytes, png);
        assert_eq!(otpauth_from_qr_bytes(&bytes).unwrap(), uri);
    }

    #[test]
    fn fetch_url_bytes_data_url_missing_payload() {
        // data: URL 缺 `,` payload → 报错。
        assert!(fetch_url_bytes("data:image/png;base64").is_err());
    }

    #[test]
    fn run_add_otpauth_overrides_totp_secret() {
        let p = make_vault("addotp");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        // --data 里 totp_secret 占位为空,--otpauth 应覆盖。
        let data = r#"{"type":"password","username":"bob","password":"pw","url":"https://x","totp_secret":"","notes":""}"#;
        let uri = "otpauth://totp/Example:alice@google.com?secret=JBSWY3DPEHPK3PXP&issuer=Example";
        let id = run_add(&u, "Totp", "password", Some(data), &EditFields::default(), vec![], false, None, Some(uri)).unwrap();
        let got = store::get_item(u.db.conn(), id).unwrap().unwrap();
        assert_eq!(item_field(&got, "totp").unwrap(), "JBSWY3DPEHPK3PXP");
        // 覆盖的 secret 能直接生成 TOTP。
        assert!(otp_of_item(&got).is_ok());
        cleanup(&p);
    }

    #[test]
    fn run_add_otpauth_non_password_errors() {
        let p = make_vault("addotpnp");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        let data = r#"{"type":"note","format":"text","content":"hi"}"#;
        let uri = "otpauth://totp/X?secret=JBSWY3DPEHPK3PXP";
        let err = run_add(&u, "N", "password", Some(data), &EditFields::default(), vec![], false, None, Some(uri));
        assert!(matches!(err, Err(Error::Other(m)) if m.contains("--otpauth")));
        cleanup(&p);
    }

    #[test]
    fn run_add_otpauth_coexists_with_gen_password() {
        // --gen-password 填 password,--otpauth 填 totp_secret,两者共存。
        let p = make_vault("addotpgen");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        let data = r#"{"type":"password","username":"bob","password":"old","url":"","totp_secret":"","notes":""}"#;
        let uri = "otpauth://totp/X?secret=JBSWY3DPEHPK3PXP";
        let id = run_add(&u, "Both", "password", Some(data), &EditFields::default(), vec![], false, Some(12), Some(uri)).unwrap();
        let got = store::get_item(u.db.conn(), id).unwrap().unwrap();
        let pw = item_field(&got, "password").unwrap();
        assert_eq!(pw.len(), 12);
        assert_ne!(pw, "old");
        assert_eq!(item_field(&got, "totp").unwrap(), "JBSWY3DPEHPK3PXP");
        cleanup(&p);
    }

    #[test]
    fn run_edit_otpauth_overrides_totp_secret() {
        let p = make_vault("editotp");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        // id=1 GitHub 原 totp_secret = JBSWY3DPEHPK3PXP;改成新的。
        let uri = "otpauth://totp/X?secret=GEZDGNBVGY3TQOJQ";
        run_edit(
            &u,
            1,
            None,
            None,
            None,
            None,
            None,
            &EditFields::default(),
            &TagDelta::default(),
            Some(uri),
        )
        .unwrap();
        let got = store::get_item(u.db.conn(), 1).unwrap().unwrap();
        assert_eq!(item_field(&got, "totp").unwrap(), "GEZDGNBVGY3TQOJQ");
        cleanup(&p);
    }

    // --- Task 2: 单字段 flag(EditFields) ---

    #[test]
    fn edit_fields_apply_password() {
        let mut item = mk_password_item("u", "p");
        let f = EditFields { sets: vec![("username".into(), "bob".into()), ("url".into(), "https://y".into())] };
        assert!(f.apply(&mut item));
        assert_eq!(item_field(&item, "username").unwrap(), "bob");
        assert_eq!(item_field(&item, "url").unwrap(), "https://y");
    }

    #[test]
    fn edit_fields_apply_note_content() {
        let mut item = mk_item(
            "note",
            "",
            &[("format", "text", FieldKind::Text), ("content", "old", FieldKind::Multiline)],
        );
        let f = EditFields { sets: vec![("content".into(), "new body".into())] };
        assert!(f.apply(&mut item));
        assert_eq!(item_field(&item, "content").unwrap(), "new body");
    }

    #[test]
    fn edit_fields_apply_card_fields() {
        let mut item = mk_item(
            "card",
            "",
            &[
                ("holder", "h", FieldKind::Text),
                ("number", "n", FieldKind::Secret),
                ("expiry", "e", FieldKind::Text),
                ("cvv", "c", FieldKind::Secret),
                ("bank", "b", FieldKind::Text),
                ("notes", "", FieldKind::Multiline),
            ],
        );
        let f = EditFields { sets: vec![("holder".into(), "HH".into()), ("cvv".into(), "999".into())] };
        assert!(f.apply(&mut item));
        assert_eq!(item_field(&item, "holder").unwrap(), "HH");
        assert_eq!(item_field(&item, "cvv").unwrap(), "999");
    }

    #[test]
    fn run_edit_single_field_username() {
        let p = make_vault("editfield");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        let f = EditFields { sets: vec![("username".into(), "bob".into())] };
        run_edit(
            &u,
            1,
            None,
            None,
            None,
            None,
            None,
            &f,
            &TagDelta::default(),
            None,
        )
        .unwrap();
        let got = store::get_item(u.db.conn(), 1).unwrap().unwrap();
        assert_eq!(item_field(&got, "username").unwrap(), "bob");
        // 其余字段未动。
        assert_eq!(item_field(&got, "password").unwrap(), "s3cret");
        cleanup(&p);
    }

    #[test]
    fn run_edit_data_conflicts_with_field_flags() {
        let p = make_vault("editconf");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        let f = EditFields { sets: vec![("username".into(), "bob".into())] };
        let err = run_edit(
            &u,
            1,
            None,
            Some(r#"{"type":"note","format":"text","content":"x"}"#),
            None,
            None,
            None,
            &f,
            &TagDelta::default(),
            None,
        );
        assert!(matches!(err, Err(Error::Other(m)) if m.contains("conflicts with field flags")));
        cleanup(&p);
    }

    // --- Task 3: 单标签增删(TagDelta) ---

    #[test]
    fn tag_delta_add_dedup_and_remove() {
        let d = TagDelta {
            add: vec!["c".into()],
            remove: vec![],
        };
        // 追加 c。
        assert_eq!(d.apply(&["a".into(), "b".into()]), vec!["a", "b", "c"]);
        // 已存在则跳过(去重)。
        assert_eq!(d.apply(&["a".into(), "c".into()]), vec!["a", "c"]);

        let d2 = TagDelta {
            add: vec![],
            remove: vec!["a".into()],
        };
        // 移除 a。
        assert_eq!(d2.apply(&["a".into(), "b".into()]), vec!["b"]);
    }

    #[test]
    fn run_edit_add_and_rm_tag() {
        let p = make_vault("edittagdelta");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        // id=1 GitHub tags=[work,vip];add c,rm a(不存在,无害)。
        let d = TagDelta {
            add: vec!["c".into()],
            remove: vec!["a".into()],
        };
        run_edit(
            &u,
            1,
            None,
            None,
            None,
            None,
            None,
            &EditFields::default(),
            &d,
            None,
        )
        .unwrap();
        let got = store::get_item(u.db.conn(), 1).unwrap().unwrap();
        // store 按 tag 名升序回读:c < vip < work。
        assert_eq!(got.tags, vec!["c".to_string(), "vip".to_string(), "work".into()]);

        // 再 rm vip。
        let d2 = TagDelta {
            add: vec![],
            remove: vec!["vip".into()],
        };
        run_edit(
            &u,
            1,
            None,
            None,
            None,
            None,
            None,
            &EditFields::default(),
            &d2,
            None,
        )
        .unwrap();
        let got = store::get_item(u.db.conn(), 1).unwrap().unwrap();
        assert_eq!(got.tags, vec!["c".to_string(), "work".into()]);
        cleanup(&p);
    }

    #[test]
    fn run_edit_tag_conflicts_with_delta() {
        let p = make_vault("edittagconf");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        let d = TagDelta {
            add: vec!["c".into()],
            remove: vec![],
        };
        let err = run_edit(
            &u,
            1,
            None,
            None,
            Some(vec!["x".into()]), // --tag 整体覆盖
            None,
            None,
            &EditFields::default(),
            &d,
            None,
        );
        assert!(matches!(err, Err(Error::Other(m)) if m.contains("--tag conflicts")));
        cleanup(&p);
    }

    // --- Task 4: 标题定位(find_item_id_by_title / resolve_id) ---

    #[test]
    fn find_item_id_exact_then_prefix() {
        let p = make_vault("find");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        let conn = u.db.conn();
        // exact 命中 GitHub(id=1)。
        assert_eq!(find_item_id_by_title(conn, "GitHub").unwrap(), 1);
        // 前缀唯一:Git -> GitHub。
        assert_eq!(find_item_id_by_title(conn, "Git").unwrap(), 1);
        cleanup(&p);
    }

    #[test]
    fn find_item_id_ambiguous_and_none() {
        // 造两条同前缀的条目。
        let p = make_vault("findamb");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        let data = r#"{"type":"password","username":"x","password":"p","url":"","totp_secret":"","notes":""}"#;
        let _id1 = run_add(&u, "GitLab", "password", Some(data), &EditFields::default(), vec![], false, None, None).unwrap();
        let conn = u.db.conn();
        // 现在 Git* 有 GitHub + GitLab → 歧义。
        let err = find_item_id_by_title(conn, "Git");
        assert!(matches!(err, Err(Error::Other(m)) if m.contains("multiple items match 'Git'")));
        // 无匹配。
        let err2 = find_item_id_by_title(conn, "NopeXYZ");
        assert!(matches!(err2, Err(Error::Other(m)) if m.contains("no item matches")));
        cleanup(&p);
    }

    #[test]
    fn resolve_id_prefers_positional_then_find() {
        let p = make_vault("resolve");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        let conn = u.db.conn();
        // 位置 id 优先。
        assert_eq!(resolve_id(conn, Some(2), Some("GitHub")).unwrap(), 2);
        // 仅 find → 解析到 GitHub(1)。
        assert_eq!(resolve_id(conn, None, Some("GitHub")).unwrap(), 1);
        // 都缺 → 报错。
        assert!(resolve_id(conn, None, None).is_err());
        cleanup(&p);
    }

    #[test]
    fn run_get_via_find_locates_item() {
        // 端到端:get 经 resolve_id(--find) 定位,只验证 run_get 返回 Ok。
        let p = make_vault("getfind");
        let pf = write_passfile("u");
        let u = Unlocked::unlock(&p, Some(&pf)).unwrap();
        let conn = u.db.conn();
        let id = resolve_id(conn, None, Some("Git")).unwrap();
        assert_eq!(id, 1);
        assert!(run_get(&u, id, Some("username"), false).is_ok());
        cleanup(&p);
    }

    /// `default_vault_path`:`HOME` 决定 → `<home>/.zkv/default.zkv`。
    #[test]
    fn default_vault_path_uses_home() {
        let _g = env_lock();
        let dir = std::env::temp_dir();
        let fake_home = dir.join(format!(
            "zkv_home_{}_{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        // SAFETY: 持 env_lock,串行 set/remove HOME,无并发竞态。
        unsafe {
            std::env::set_var("HOME", &fake_home);
        }
        let got = default_vault_path();
        unsafe {
            std::env::remove_var("HOME");
        }
        let got = got.unwrap();
        assert_eq!(got, fake_home.join(".zkv").join("default.zkv"));
    }

    /// `default_vault_path`:无 HOME/USERPROFILE → 报错。
    #[test]
    fn default_vault_path_missing_home_errors() {
        let _g = env_lock();
        // SAFETY: 持 env_lock,串行 remove,无并发竞态。
        unsafe {
            std::env::remove_var("HOME");
            std::env::remove_var("USERPROFILE");
        }
        let got = default_vault_path();
        assert!(got.is_err(), "expected error when no home dir available");
    }

    /// `resolve_vault_path`:Some → 原样;None → 默认库。
    #[test]
    fn resolve_vault_path_some_and_none() {
        let _g = env_lock();
        // Some:直接返回,不看 HOME。
        unsafe {
            std::env::remove_var("HOME");
        }
        let explicit = PathBuf::from("/tmp/explicit.zkv");
        assert_eq!(resolve_vault_path(Some(explicit.clone())).unwrap(), explicit);

        // None → 默认库(依赖 HOME)。
        let dir = std::env::temp_dir();
        let fake_home = dir.join(format!(
            "zkv_home2_{}_{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        // SAFETY: 持 env_lock,串行。
        unsafe {
            std::env::set_var("HOME", &fake_home);
        }
        let r = resolve_vault_path(None).unwrap();
        unsafe {
            std::env::remove_var("HOME");
        }
        assert_eq!(r, fake_home.join(".zkv").join("default.zkv"));
    }

    /// 集成性往返:把 HOME 指向 temp dir,init(默认路径)→ 解锁 → ls。
    #[test]
    fn default_path_init_then_ls_roundtrip() {
        let _g = env_lock();
        let root = std::env::temp_dir().join(format!(
            "zkv_rt_{}_{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        // SAFETY: 持 env_lock,串行 set/remove HOME,无并发竞态。
        unsafe {
            std::env::set_var("HOME", &root);
            std::env::set_var("ZKV_PASSPHRASE", "pw");
        }
        let res = (|| -> Result<()> {
            let p = resolve_vault_path(None)?;
            // 模拟 main.rs 的 ensure_parent_dir:init 前建好 ~/.zkv。
            if let Some(parent) = p.parent() {
                std::fs::create_dir_all(parent)?;
            }
            run_init(&p, None)?;
            // 默认库应存在并可走 unlock 路径。
            assert!(p.exists());
            let u = Unlocked::unlock(&p, None)?;
            // 空库无条目。
            let items = search::search(u.db.conn(), &Filter::default())?;
            assert!(items.is_empty());
            Ok(())
        })();
        unsafe {
            std::env::remove_var("HOME");
            std::env::remove_var("ZKV_PASSPHRASE");
        }
        let _ = std::fs::remove_dir_all(&root);
        res.unwrap();
    }
}