raffi 0.23.0

A simple fuzzel launcher based on YAML file
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
use std::{
    collections::{HashMap, HashSet},
    fmt::Write as _,
    fs::{self, File},
    io::{Read, Write},
    path::{Path, PathBuf},
    process::Command,
};

use anyhow::{Context, Result};
use gumdrop::Options;
use schemars::JsonSchema;
use serde::Deserialize;
use serde_yaml::Value;

pub mod debug;
pub mod ui;

/// Represents the configuration for each Raffi entry.
#[derive(Deserialize, JsonSchema, Debug, PartialEq, Clone, Default)]
pub struct RaffiConfig {
    pub binary: Option<String>,
    pub args: Option<Vec<String>>,
    pub icon: Option<String>,
    pub description: Option<String>,
    pub ifenveq: Option<Vec<String>>,
    pub ifenvset: Option<String>,
    pub ifenvnotset: Option<String>,
    pub ifexist: Option<String>,
    pub disabled: Option<bool>,
    pub script: Option<String>,
}

/// Configuration for the currency addon
#[derive(Deserialize, JsonSchema, Debug, Clone)]
pub struct CurrencyAddonConfig {
    #[serde(default = "default_true")]
    pub enabled: bool,
    #[serde(default)]
    pub currencies: Option<Vec<String>>,
    #[serde(default)]
    pub default_currency: Option<String>,
    #[serde(default)]
    pub trigger: Option<String>,
}

impl Default for CurrencyAddonConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            currencies: None,
            default_currency: None,
            trigger: None,
        }
    }
}

/// Configuration for the calculator addon
#[derive(Deserialize, JsonSchema, Debug, Clone)]
pub struct CalculatorAddonConfig {
    #[serde(default = "default_true")]
    pub enabled: bool,
}

impl Default for CalculatorAddonConfig {
    fn default() -> Self {
        Self { enabled: true }
    }
}

/// Configuration for the file browser addon
#[derive(Deserialize, JsonSchema, Debug, Clone)]
pub struct FileBrowserAddonConfig {
    #[serde(default = "default_true")]
    pub enabled: bool,
    #[serde(default)]
    pub show_hidden: Option<bool>,
}

impl Default for FileBrowserAddonConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            show_hidden: None,
        }
    }
}

/// Default data file names downloaded from the rofimoji project when
/// the user does not provide an explicit `data_files` list.
pub const DEFAULT_EMOJI_FILES: &[&str] = &[
    "emojis_smileys_emotion",
    "emojis_people_body",
    "emojis_animals_nature",
    "emojis_food_drink",
    "emojis_travel_places",
    "emojis_activities",
    "emojis_objects",
    "emojis_symbols",
    "emojis_flags",
    "emojis_component",
];

/// Configuration for the emoji picker addon
#[derive(Deserialize, JsonSchema, Debug, Clone)]
pub struct EmojiAddonConfig {
    #[serde(default = "default_true")]
    pub enabled: bool,
    #[serde(default)]
    pub trigger: Option<String>,
    #[serde(default)]
    pub action: Option<String>,
    #[serde(default)]
    pub secondary_action: Option<String>,
    #[serde(default)]
    pub data_files: Option<Vec<String>>,
}

impl Default for EmojiAddonConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            trigger: None,
            action: None,
            secondary_action: None,
            data_files: None,
        }
    }
}

/// Configuration for a script filter addon
#[derive(Deserialize, JsonSchema, Debug, Clone)]
pub struct ScriptFilterConfig {
    pub name: String,
    pub command: String,
    pub keyword: String,
    pub icon: Option<String>,
    #[serde(default)]
    pub args: Vec<String>,
    pub action: Option<String>,
    pub secondary_action: Option<String>,
    #[serde(default)]
    pub env: std::collections::HashMap<String, String>,
    pub min_query_length: Option<usize>,
}

/// Configuration for a web search addon
#[derive(Deserialize, JsonSchema, Debug, Clone)]
pub struct WebSearchConfig {
    pub name: String,
    pub keyword: String,
    pub url: String,
    pub icon: Option<String>,
}

/// A single text snippet entry
#[derive(Deserialize, JsonSchema, Debug, Clone, PartialEq)]
pub struct TextSnippet {
    pub name: String,
    pub value: String,
}

/// Configuration for a text snippet source
#[derive(Deserialize, JsonSchema, Debug, Clone)]
pub struct TextSnippetSourceConfig {
    pub name: String,
    pub keyword: String,
    #[serde(default)]
    pub icon: Option<String>,
    #[serde(default)]
    pub snippets: Option<Vec<TextSnippet>>,
    #[serde(default)]
    pub file: Option<String>,
    #[serde(default)]
    pub command: Option<String>,
    #[serde(default)]
    pub directory: Option<String>,
    #[serde(default)]
    pub args: Vec<String>,
    #[serde(default)]
    pub action: Option<String>,
    #[serde(default)]
    pub secondary_action: Option<String>,
}

/// Container for all addon configurations
#[derive(Deserialize, JsonSchema, Debug, Clone, Default)]
pub struct AddonsConfig {
    #[serde(default)]
    pub currency: CurrencyAddonConfig,
    #[serde(default)]
    pub calculator: CalculatorAddonConfig,
    #[serde(default)]
    pub file_browser: FileBrowserAddonConfig,
    #[serde(default)]
    pub emoji: EmojiAddonConfig,
    #[serde(default)]
    pub script_filters: Vec<ScriptFilterConfig>,
    #[serde(default)]
    pub web_searches: Vec<WebSearchConfig>,
    #[serde(default)]
    pub text_snippets: Vec<TextSnippetSourceConfig>,
}

fn default_true() -> bool {
    true
}

/// Per-colour overrides for the native UI theme.
#[derive(Deserialize, JsonSchema, Debug, Clone, Default)]
pub struct ThemeColorsConfig {
    pub bg_base: Option<String>,
    pub bg_input: Option<String>,
    pub accent: Option<String>,
    pub accent_hover: Option<String>,
    pub text_main: Option<String>,
    pub text_muted: Option<String>,
    pub selection_bg: Option<String>,
    pub border: Option<String>,
}

/// Sort mode for launcher entries when no search query is active
#[derive(Deserialize, JsonSchema, Debug, Clone, Default, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum SortMode {
    /// Sort by launch count (most frequently used first)
    Frequency,
    /// Sort by last-used time (most recently used first)
    Recency,
    /// Combined score: 40% frequency + 60% recency
    #[default]
    Hybrid,
}

/// General configuration for persistent defaults
#[derive(Deserialize, JsonSchema, Debug, Clone, Default)]
pub struct GeneralConfig {
    #[serde(default)]
    pub ui_type: Option<String>,
    #[serde(default)]
    pub default_script_shell: Option<String>,
    #[serde(default)]
    pub no_icons: Option<bool>,
    #[serde(default)]
    pub theme: Option<String>,
    #[serde(default)]
    pub theme_colors: Option<ThemeColorsConfig>,
    #[serde(default)]
    pub max_history: Option<u32>,
    #[serde(default)]
    pub font_size: Option<f32>,
    #[serde(default)]
    pub font_family: Option<String>,
    #[serde(default)]
    pub window_width: Option<f32>,
    #[serde(default)]
    pub window_height: Option<f32>,
    #[serde(default)]
    pub padding: Option<f32>,
    #[serde(default)]
    pub sort_mode: SortMode,
    #[serde(default)]
    pub fallbacks: Vec<String>,
}

/// Complete parsed configuration
pub struct ParsedConfig {
    pub general: GeneralConfig,
    pub addons: AddonsConfig,
    pub entries: Vec<RaffiConfig>,
}

/// Represents the top-level configuration structure (v1 format).
#[derive(Deserialize)]
struct Config {
    #[serde(default)]
    #[allow(dead_code)]
    version: u32,
    #[serde(default)]
    general: GeneralConfig,
    #[serde(default)]
    addons: AddonsConfig,
    #[serde(default)]
    launchers: HashMap<String, Value>,
}

/// Public schema representation of the v1 config format, used for JSON Schema generation.
#[derive(JsonSchema)]
pub struct ConfigSchema {
    /// Config format version (currently 1)
    pub version: u32,
    /// General settings (UI, theme, font, etc.)
    #[serde(default)]
    pub general: GeneralConfig,
    /// Addon configurations (script filters, web searches, etc.)
    #[serde(default)]
    pub addons: AddonsConfig,
    /// Launcher entries keyed by name
    #[serde(default)]
    pub launchers: HashMap<String, RaffiConfig>,
}

/// UI type selection
#[derive(Debug, Clone, PartialEq)]
pub enum UIType {
    Fuzzel,
    #[cfg(feature = "wayland")]
    Native,
}

/// Theme mode selection
#[derive(Debug, Clone, PartialEq)]
pub enum ThemeMode {
    Dark,
    Light,
}

impl std::str::FromStr for ThemeMode {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "dark" => Ok(ThemeMode::Dark),
            "light" => Ok(ThemeMode::Light),
            _ => Err(format!(
                "Invalid theme: {}. Valid options are: dark, light",
                s
            )),
        }
    }
}

impl std::str::FromStr for UIType {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "fuzzel" => Ok(UIType::Fuzzel),
            #[cfg(feature = "wayland")]
            "native" | "wayland" | "iced" => Ok(UIType::Native),
            #[cfg(not(feature = "wayland"))]
            "native" | "wayland" | "iced" => Err(
                "Native UI is not available. Build with the 'wayland' feature to enable it."
                    .to_string(),
            ),
            _ => {
                #[cfg(feature = "wayland")]
                {
                    Err(format!(
                        "Invalid UI type: {}. Valid options are: fuzzel, native",
                        s
                    ))
                }
                #[cfg(not(feature = "wayland"))]
                {
                    Err(format!("Invalid UI type: {}. Valid options are: fuzzel", s))
                }
            }
        }
    }
}

/// Command-line arguments structure.
#[derive(Debug, Options, Clone)]
pub struct Args {
    #[options(help = "print help message")]
    pub help: bool,
    #[options(help = "print version")]
    pub version: bool,
    #[options(help = "config file location", short = "c")]
    pub configfile: Option<String>,
    #[options(help = "print command to stdout, do not run it", short = "p")]
    pub print_only: bool,
    #[options(help = "refresh cache", short = "r")]
    pub refresh_cache: bool,
    #[options(help = "do not show icons", short = "I")]
    pub no_icons: bool,
    #[options(help = "default shell when using scripts", short = "P")]
    pub default_script_shell: Option<String>,
    #[options(help = "UI type to use: fuzzel, native (default: fuzzel)", short = "u")]
    pub ui_type: Option<String>,
    #[options(help = "initial search query (native mode only)", short = "i")]
    pub initial_query: Option<String>,
    #[options(help = "theme: dark, light (default: dark)", short = "t")]
    pub theme: Option<String>,
    #[options(help = "print JSON Schema for the config format to stdout")]
    pub schema: bool,
    #[options(help = "write debug log to FILE")]
    pub debug_file: Option<String>,
}

/// A trait for checking environment variables.
pub trait EnvProvider {
    fn var(&self, key: &str) -> Result<String, std::env::VarError>;
}

/// The default environment provider.
pub struct DefaultEnvProvider;

impl EnvProvider for DefaultEnvProvider {
    fn var(&self, key: &str) -> Result<String, std::env::VarError> {
        std::env::var(key)
    }
}

/// A trait for checking if a binary exists.
pub trait BinaryChecker {
    fn exists(&self, binary: &str) -> bool;
}

/// The default binary checker.
pub struct DefaultBinaryChecker;

impl BinaryChecker for DefaultBinaryChecker {
    fn exists(&self, binary: &str) -> bool {
        find_binary(binary)
    }
}

/// A trait for providing an icon map.
pub trait IconMapProvider {
    fn get_icon_map(&self) -> Result<HashMap<String, String>>;
}

/// The default icon map provider.
pub struct DefaultIconMapProvider;

impl IconMapProvider for DefaultIconMapProvider {
    fn get_icon_map(&self) -> Result<HashMap<String, String>> {
        read_icon_map()
    }
}

/// Extract icon size from path (e.g., "/usr/share/icons/Papirus/48x48/apps/icon.svg" -> 48).
/// Returns 0 if size cannot be determined.
fn extract_icon_size(path: &std::path::Path) -> u32 {
    for component in path.components() {
        if let std::path::Component::Normal(s) = component {
            if let Some(s_str) = s.to_str() {
                // Match patterns like "48x48", "64x64", "scalable"
                if s_str == "scalable" {
                    return 512; // Treat scalable as large
                }
                if let Some((w, _)) = s_str.split_once('x') {
                    if let Ok(size) = w.parse::<u32>() {
                        return size;
                    }
                }
            }
        }
    }
    0
}

/// Get the icon mapping from system directories.
/// Prefers larger icons (48x48+) since raffi renders at 48x48.
fn get_icon_map() -> Result<HashMap<String, String>> {
    let mut icon_map: HashMap<String, String> = HashMap::new();
    let mut icon_sizes: HashMap<String, u32> = HashMap::new();
    let mut data_dirs =
        std::env::var("XDG_DATA_DIRS").unwrap_or("/usr/local/share/:/usr/share/".to_string());
    let data_home = std::env::var("XDG_DATA_HOME").unwrap_or_else(|_| {
        format!(
            "{}/.local/share/",
            std::env::var("HOME").unwrap_or_default()
        )
    });
    write!(&mut data_dirs, ":{data_home}")?;

    for datadir in std::env::split_paths(&data_dirs) {
        for subdir in &["icons", "pixmaps"] {
            let mut dir = datadir.clone();
            dir.push(subdir);
            for entry in walkdir::WalkDir::new(dir)
                .follow_links(true)
                .into_iter()
                .filter_map(Result::ok)
            {
                let fname = entry.file_name().to_string_lossy().to_string();
                if let Some(ext) = entry.path().extension().and_then(|s| s.to_str()) {
                    if ext == "png" || ext == "svg" {
                        let icon_name = fname.rsplit_once('.').unwrap().0.to_string();
                        let icon_path = entry.path().to_string_lossy().to_string();
                        let new_size = extract_icon_size(entry.path());
                        let current_size = icon_sizes.get(&icon_name).copied().unwrap_or(0);

                        // Prefer icons >= 48px, or larger than current
                        if new_size >= current_size || (new_size >= 48 && current_size < 48) {
                            icon_map.insert(icon_name.clone(), icon_path);
                            icon_sizes.insert(icon_name, new_size);
                        }
                    }
                }
            }
        }
    }
    Ok(icon_map)
}

/// Expand `~/` prefix to the user's HOME directory.
pub(crate) fn expand_tilde(s: &str) -> String {
    if let Some(stripped) = s.strip_prefix("~/") {
        format!("{}/{}", std::env::var("HOME").unwrap_or_default(), stripped)
    } else {
        s.to_string()
    }
}

/// Expand `${VAR}` references to their environment variable values.
/// Unknown or unset variables expand to an empty string.
fn expand_env_vars(s: &str) -> String {
    let mut result = String::with_capacity(s.len());
    let mut chars = s.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '$' && chars.peek() == Some(&'{') {
            chars.next(); // consume '{'
            let var_name: String = chars.by_ref().take_while(|&c| c != '}').collect();
            result.push_str(&std::env::var(&var_name).unwrap_or_default());
        } else {
            result.push(c);
        }
    }
    result
}

/// Expand both `~/` and `${VAR}` in a config value.
pub(crate) fn expand_config_value(s: &str) -> String {
    expand_env_vars(&expand_tilde(s))
}

/// Migrate a v0 config (launcher entries as top-level keys) to v1 format
/// (entries under a `launchers` key with an explicit `version` field).
/// Returns `Ok(true)` if migration was performed, `Ok(false)` if already v1+.
pub fn migrate_config_v0_to_v1(config_path: &str, raw: &mut Value) -> Result<bool> {
    let mapping = match raw.as_mapping_mut() {
        Some(m) => m,
        None => return Ok(false),
    };

    // If version key exists, no migration needed
    if mapping.contains_key(Value::String("version".to_string())) {
        return Ok(false);
    }

    let reserved = ["general", "addons", "version"];
    let mut launchers = serde_yaml::Mapping::new();
    let mut keys_to_move = Vec::new();

    for (key, _) in mapping.iter() {
        if let Some(k) = key.as_str() {
            if !reserved.contains(&k) {
                keys_to_move.push(Value::String(k.to_string()));
            }
        }
    }

    for key in &keys_to_move {
        if let Some(val) = mapping.remove(key) {
            launchers.insert(key.clone(), val);
        }
    }

    mapping.insert(
        Value::String("version".to_string()),
        Value::Number(serde_yaml::Number::from(1u64)),
    );
    mapping.insert(
        Value::String("launchers".to_string()),
        Value::Mapping(launchers),
    );

    // Back up original file
    let backup_path = format!("{config_path}.bak");
    fs::copy(config_path, &backup_path)
        .context(format!("Failed to create backup at {backup_path}"))?;

    // Write migrated config
    let migrated_yaml =
        serde_yaml::to_string(&raw).context("Failed to serialize migrated config")?;
    fs::write(config_path, &migrated_yaml)
        .context(format!("Failed to write migrated config to {config_path}"))?;

    eprintln!("Config migrated to v1 format. Backup saved as {backup_path}");
    Ok(true)
}

/// Read the configuration file and return a ParsedConfig.
pub fn read_config(filename: &str, args: &Args) -> Result<ParsedConfig> {
    let contents =
        fs::read_to_string(filename).context(format!("cannot open config file {filename}"))?;
    let mut raw: Value = serde_yaml::from_str(&contents).context("cannot parse config as YAML")?;

    migrate_config_v0_to_v1(filename, &mut raw)?;

    let config: Config = serde_yaml::from_value(raw).context("cannot parse config")?;

    process_config(config, args)
}

/// Read config from a reader, accepting both v0 (flat) and v1 (launchers) formats.
/// Used primarily for tests where no file path is available for migration.
pub fn read_config_from_reader<R: Read>(reader: R, args: &Args) -> Result<ParsedConfig> {
    let mut contents = String::new();
    let mut reader = reader;
    reader
        .read_to_string(&mut contents)
        .context("cannot read config")?;
    let mut raw: Value = serde_yaml::from_str(&contents).context("cannot parse config")?;

    // For reader-based configs, do an in-memory migration (no file write)
    if let Some(mapping) = raw.as_mapping_mut() {
        if !mapping.contains_key(Value::String("version".to_string())) {
            let reserved = ["general", "addons", "version"];
            let mut launchers = serde_yaml::Mapping::new();
            let mut keys_to_move = Vec::new();

            for (key, _) in mapping.iter() {
                if let Some(k) = key.as_str() {
                    if !reserved.contains(&k) {
                        keys_to_move.push(Value::String(k.to_string()));
                    }
                }
            }

            for key in &keys_to_move {
                if let Some(val) = mapping.remove(key) {
                    launchers.insert(key.clone(), val);
                }
            }

            mapping.insert(
                Value::String("version".to_string()),
                Value::Number(serde_yaml::Number::from(1u64)),
            );
            mapping.insert(
                Value::String("launchers".to_string()),
                Value::Mapping(launchers),
            );
        }
    }

    let config: Config = serde_yaml::from_value(raw).context("cannot parse config")?;
    process_config(config, args)
}

/// Common config processing logic shared by read_config and read_config_from_reader.
fn process_config(config: Config, args: &Args) -> Result<ParsedConfig> {
    let mut rafficonfigs = Vec::new();

    for value in config.launchers.values() {
        if value.is_mapping() {
            let mut mc: RaffiConfig = serde_yaml::from_value(value.clone())
                .context("cannot parse config entry".to_string())?;
            mc.binary = mc.binary.map(|s| expand_config_value(&s));
            mc.icon = mc.icon.map(|s| expand_config_value(&s));
            mc.ifexist = mc.ifexist.map(|s| expand_config_value(&s));
            mc.args = mc
                .args
                .map(|v| v.into_iter().map(|s| expand_config_value(&s)).collect());
            if mc.disabled.unwrap_or(false)
                || !is_valid_config(&mut mc, args, &DefaultEnvProvider, &DefaultBinaryChecker)
            {
                continue;
            }
            rafficonfigs.push(mc);
        }
    }

    let mut addons = config.addons;
    for sf in &mut addons.script_filters {
        sf.command = expand_config_value(&sf.command);
        sf.icon = sf.icon.as_ref().map(|s| expand_config_value(s));
        sf.action = sf.action.as_ref().map(|s| expand_config_value(s));
        sf.secondary_action = sf.secondary_action.as_ref().map(|s| expand_config_value(s));
    }
    for ws in &mut addons.web_searches {
        ws.url = expand_config_value(&ws.url);
        ws.icon = ws.icon.as_ref().map(|s| expand_config_value(s));
    }
    for ts in &mut addons.text_snippets {
        ts.icon = ts.icon.as_ref().map(|s| expand_config_value(s));
        ts.file = ts.file.as_ref().map(|s| expand_config_value(s));
        ts.command = ts.command.as_ref().map(|s| expand_config_value(s));
        ts.directory = ts.directory.as_ref().map(|s| expand_config_value(s));
    }

    Ok(ParsedConfig {
        general: config.general,
        addons,
        entries: rafficonfigs,
    })
}

/// Validate the RaffiConfig based on various conditions.
fn is_valid_config(
    mc: &mut RaffiConfig,
    args: &Args,
    env_provider: &impl EnvProvider,
    binary_checker: &impl BinaryChecker,
) -> bool {
    if let Some(_script) = &mc.script {
        if !binary_checker.exists(
            mc.binary
                .as_deref()
                .unwrap_or(args.default_script_shell.as_deref().unwrap_or("bash")),
        ) {
            return false;
        }
    } else if let Some(binary) = &mc.binary {
        if !binary_checker.exists(binary) {
            return false;
        }
    } else if let Some(description) = &mc.description {
        mc.binary = Some(description.clone());
    } else {
        return false;
    }

    mc.ifenveq
        .as_ref()
        .is_none_or(|eq| eq.len() == 2 && env_provider.var(&eq[0]).unwrap_or_default() == eq[1])
        && mc
            .ifenvset
            .as_ref()
            .is_none_or(|var| env_provider.var(var).is_ok())
        && mc
            .ifenvnotset
            .as_ref()
            .is_none_or(|var| env_provider.var(var).is_err())
        && mc
            .ifexist
            .as_ref()
            .is_none_or(|exist| binary_checker.exists(exist))
}

/// Check if a binary exists in the PATH.
fn find_binary(binary: &str) -> bool {
    if binary.contains('/') {
        return Path::new(binary).exists();
    }

    std::env::var("PATH")
        .unwrap_or_default()
        .split(':')
        .any(|path| Path::new(&format!("{path}/{binary}")).exists())
}

fn xdg_data_dirs() -> Vec<PathBuf> {
    let mut dirs = Vec::new();

    if let Ok(data_home) = std::env::var("XDG_DATA_HOME") {
        dirs.push(PathBuf::from(data_home));
    } else if let Ok(home) = std::env::var("HOME") {
        dirs.push(PathBuf::from(home).join(".local/share"));
    }

    let system_dirs = std::env::var("XDG_DATA_DIRS")
        .unwrap_or_else(|_| "/usr/local/share:/usr/share".to_string());
    dirs.extend(std::env::split_paths(&system_dirs));

    dirs
}

fn desktop_entry_dirs() -> Vec<PathBuf> {
    xdg_data_dirs()
        .into_iter()
        .map(|dir| dir.join("applications"))
        .collect()
}

fn parse_bool(value: &str) -> bool {
    matches!(
        value.trim().to_ascii_lowercase().as_str(),
        "true" | "1" | "yes"
    )
}

fn parse_desktop_entry_keys(contents: &str) -> HashMap<String, String> {
    let mut in_desktop_entry = false;
    let mut keys = HashMap::new();

    for line in contents.lines() {
        let trimmed = line.trim();

        if trimmed.is_empty() || trimmed.starts_with('#') {
            continue;
        }

        if trimmed.starts_with('[') && trimmed.ends_with(']') {
            if trimmed == "[Desktop Entry]" {
                in_desktop_entry = true;
                continue;
            }

            if in_desktop_entry {
                break;
            }

            continue;
        }

        if !in_desktop_entry {
            continue;
        }

        if let Some((key, value)) = trimmed.split_once('=') {
            keys.insert(key.trim().to_string(), value.trim().to_string());
        }
    }

    keys
}

fn split_desktop_exec(exec: &str) -> Vec<String> {
    let mut tokens = Vec::new();
    let mut current = String::new();
    let mut chars = exec.chars().peekable();
    let mut in_single = false;
    let mut in_double = false;

    while let Some(ch) = chars.next() {
        match ch {
            '\\' => {
                if let Some(next) = chars.next() {
                    current.push(next);
                }
            }
            '\'' if !in_double => in_single = !in_single,
            '"' if !in_single => in_double = !in_double,
            c if c.is_whitespace() && !in_single && !in_double => {
                if !current.is_empty() {
                    tokens.push(std::mem::take(&mut current));
                }
            }
            _ => current.push(ch),
        }
    }

    if !current.is_empty() {
        tokens.push(current);
    }

    tokens
}

fn strip_desktop_exec_field_codes(token: &str) -> String {
    let mut cleaned = String::with_capacity(token.len());
    let mut chars = token.chars().peekable();

    while let Some(ch) = chars.next() {
        if ch == '%' {
            match chars.peek().copied() {
                Some('%') => {
                    cleaned.push('%');
                    chars.next();
                }
                Some(code) if "fFuUdDnNickvm".contains(code) => {
                    chars.next();
                }
                _ => cleaned.push(ch),
            }
        } else {
            cleaned.push(ch);
        }
    }

    cleaned.trim().to_string()
}

fn parse_desktop_exec(exec: &str) -> Option<(String, Vec<String>)> {
    let mut tokens = split_desktop_exec(exec)
        .into_iter()
        .map(|token| strip_desktop_exec_field_codes(&token))
        .filter(|token| !token.is_empty())
        .collect::<Vec<_>>();

    if tokens.is_empty() {
        return None;
    }

    let binary = tokens.remove(0);
    Some((binary, tokens))
}

fn parse_desktop_entry_file(
    path: &Path,
    binary_checker: &impl BinaryChecker,
) -> Option<RaffiConfig> {
    let contents = fs::read_to_string(path).ok()?;
    let keys = parse_desktop_entry_keys(&contents);

    if keys.get("Type").map(String::as_str) != Some("Application") {
        return None;
    }
    if keys.get("Hidden").is_some_and(|value| parse_bool(value))
        || keys.get("NoDisplay").is_some_and(|value| parse_bool(value))
        || keys.get("Terminal").is_some_and(|value| parse_bool(value))
    {
        return None;
    }

    let exec = keys.get("Exec")?;
    let name = keys.get("Name")?;
    let (binary, args) = parse_desktop_exec(exec)?;

    if let Some(try_exec) = keys.get("TryExec") {
        if !binary_checker.exists(try_exec) {
            return None;
        }
    }
    if !binary_checker.exists(&binary) {
        return None;
    }

    Some(RaffiConfig {
        binary: Some(binary),
        args: (!args.is_empty()).then_some(args),
        icon: keys.get("Icon").cloned(),
        description: Some(name.clone()),
        ..Default::default()
    })
}

fn detect_desktop_entries_from_dirs(
    dirs: &[PathBuf],
    binary_checker: &impl BinaryChecker,
) -> Vec<RaffiConfig> {
    let mut seen = HashSet::new();
    let mut entries = Vec::new();

    for dir in dirs {
        if !dir.exists() {
            continue;
        }

        for entry in walkdir::WalkDir::new(dir)
            .follow_links(true)
            .into_iter()
            .filter_map(Result::ok)
        {
            if !entry.file_type().is_file() {
                continue;
            }
            if entry.path().extension().and_then(|ext| ext.to_str()) != Some("desktop") {
                continue;
            }

            let Some(config) = parse_desktop_entry_file(entry.path(), binary_checker) else {
                continue;
            };

            let key = format!(
                "{}\u{1f}{}\u{1f}{}",
                config.description.as_deref().unwrap_or_default(),
                config.binary.as_deref().unwrap_or_default(),
                config.args.as_deref().unwrap_or(&[]).join("\u{1f}")
            );
            if seen.insert(key) {
                entries.push(config);
            }
        }
    }

    entries.sort_by(|left, right| {
        left.description
            .as_deref()
            .unwrap_or_default()
            .cmp(right.description.as_deref().unwrap_or_default())
    });
    entries
}

fn detect_desktop_entries(binary_checker: &impl BinaryChecker) -> Vec<RaffiConfig> {
    detect_desktop_entries_from_dirs(&desktop_entry_dirs(), binary_checker)
}

const DEFAULT_ICON_PATH: &str = "assets/default_icon.svg";
const DEFAULT_ICON_BYTES: &[u8] = include_bytes!("../assets/default_icon.svg");
const GENERIC_ICON_NAMES: &[&str] = &[
    "application-x-executable",
    "application-default-icon",
    "application-x-desktop",
];

fn icon_cache_dir() -> PathBuf {
    PathBuf::from(
        std::env::var("XDG_CACHE_HOME")
            .unwrap_or_else(|_| format!("{}/.cache", std::env::var("HOME").unwrap_or_default())),
    )
    .join("raffi")
}

fn is_supported_icon_extension(path: &Path) -> bool {
    matches!(
        path.extension().and_then(|ext| ext.to_str()),
        Some("png" | "svg")
    )
}

fn is_icon_file(path: &Path) -> bool {
    path.is_file() && is_supported_icon_extension(path)
}

fn push_icon_candidate(candidates: &mut Vec<String>, seen: &mut HashSet<String>, candidate: &str) {
    let trimmed = candidate.trim();
    if trimmed.is_empty() {
        return;
    }

    let owned = trimmed.to_string();
    if seen.insert(owned.clone()) {
        candidates.push(owned);
    }

    let Some(file_name) = Path::new(trimmed)
        .file_name()
        .and_then(|name| name.to_str())
    else {
        return;
    };
    if file_name == trimmed {
        return;
    }

    let basename = file_name.to_string();
    if seen.insert(basename.clone()) {
        candidates.push(basename);
    }
}

fn launcher_icon_candidates(config: &RaffiConfig) -> Vec<String> {
    let mut candidates = Vec::new();
    let mut seen = HashSet::new();

    if let Some(icon) = config.icon.as_deref() {
        push_icon_candidate(&mut candidates, &mut seen, icon);
    }
    if let Some(binary) = config.binary.as_deref() {
        push_icon_candidate(&mut candidates, &mut seen, binary);
    }
    if let Some(args) = config.args.as_deref() {
        for arg in args {
            if arg.starts_with('-') || arg.contains("://") {
                continue;
            }
            push_icon_candidate(&mut candidates, &mut seen, arg);
        }
    }

    candidates
}

fn is_exec_wrapper_binary(candidate: &str) -> bool {
    matches!(
        Path::new(candidate)
            .file_name()
            .and_then(|name| name.to_str())
            .unwrap_or(candidate),
        "env" | "sh" | "bash" | "dash" | "zsh"
    )
}

fn desktop_exec_icon_candidates(exec: &str, binary_checker: &impl BinaryChecker) -> Vec<String> {
    let mut candidates = Vec::new();
    let mut seen = HashSet::new();

    for token in split_desktop_exec(exec)
        .into_iter()
        .map(|token| strip_desktop_exec_field_codes(&token))
        .filter(|token| !token.is_empty())
    {
        if token.starts_with('-') || token.contains('=') || is_exec_wrapper_binary(&token) {
            continue;
        }
        if !binary_checker.exists(&token) {
            continue;
        }
        push_icon_candidate(&mut candidates, &mut seen, &token);
    }

    candidates
}

fn desktop_entry_icon_map_from_dirs(
    dirs: &[PathBuf],
    binary_checker: &impl BinaryChecker,
) -> HashMap<String, String> {
    let mut icon_map = HashMap::new();

    for dir in dirs {
        if !dir.exists() {
            continue;
        }

        for entry in walkdir::WalkDir::new(dir)
            .max_depth(2)
            .follow_links(true)
            .into_iter()
            .filter_map(Result::ok)
        {
            if !entry.file_type().is_file() {
                continue;
            }
            if entry.path().extension().and_then(|ext| ext.to_str()) != Some("desktop") {
                continue;
            }

            let Ok(contents) = fs::read_to_string(entry.path()) else {
                continue;
            };
            let keys = parse_desktop_entry_keys(&contents);

            if keys.get("Type").map(String::as_str) != Some("Application") {
                continue;
            }
            if keys.get("Hidden").is_some_and(|value| parse_bool(value))
                || keys.get("NoDisplay").is_some_and(|value| parse_bool(value))
                || keys.get("Terminal").is_some_and(|value| parse_bool(value))
            {
                continue;
            }

            let Some(icon) = keys.get("Icon").cloned() else {
                continue;
            };

            let mut candidates = keys
                .get("Exec")
                .map(|exec| desktop_exec_icon_candidates(exec, binary_checker))
                .unwrap_or_default();

            if let Some(try_exec) = keys.get("TryExec") {
                if binary_checker.exists(try_exec) && !is_exec_wrapper_binary(try_exec) {
                    let mut try_exec_seen = candidates.iter().cloned().collect::<HashSet<_>>();
                    push_icon_candidate(&mut candidates, &mut try_exec_seen, try_exec);
                }
            }

            for candidate in candidates {
                icon_map.entry(candidate).or_insert_with(|| icon.clone());
            }
        }
    }

    icon_map
}

pub(crate) fn read_desktop_icon_map() -> HashMap<String, String> {
    desktop_entry_icon_map_from_dirs(&desktop_entry_dirs(), &DefaultBinaryChecker)
}

fn resolve_icon_reference(icon: &str, icon_map: &HashMap<String, String>) -> Option<String> {
    let expanded = expand_config_value(icon);
    if is_icon_file(Path::new(&expanded)) {
        return Some(expanded);
    }

    icon_map.get(icon).cloned().or_else(|| {
        Path::new(icon)
            .file_stem()
            .and_then(|stem| stem.to_str())
            .and_then(|stem| icon_map.get(stem).cloned())
    })
}

fn bundled_default_icon_path() -> Option<String> {
    let cache_dir = icon_cache_dir();
    fs::create_dir_all(&cache_dir).ok()?;

    let path = cache_dir.join(Path::new(DEFAULT_ICON_PATH).file_name().unwrap_or_default());
    let needs_write = fs::read(&path)
        .map(|contents| contents != DEFAULT_ICON_BYTES)
        .unwrap_or(true);
    if needs_write {
        fs::write(&path, DEFAULT_ICON_BYTES).ok()?;
    }

    Some(path.to_string_lossy().into_owned())
}

pub(crate) fn default_icon_path(icon_map: &HashMap<String, String>) -> Option<String> {
    GENERIC_ICON_NAMES
        .iter()
        .find_map(|icon| icon_map.get(*icon).cloned())
        .or_else(bundled_default_icon_path)
}

pub(crate) fn resolve_launcher_icon_path(
    config: &RaffiConfig,
    icon_map: &HashMap<String, String>,
    desktop_icon_map: &HashMap<String, String>,
) -> Option<String> {
    let candidates = launcher_icon_candidates(config);

    for candidate in &candidates {
        if let Some(path) = resolve_icon_reference(candidate, icon_map) {
            return Some(path);
        }
    }

    for candidate in &candidates {
        if let Some(icon) = desktop_icon_map.get(candidate) {
            if let Some(path) = resolve_icon_reference(icon, icon_map) {
                return Some(path);
            }
        }
    }

    default_icon_path(icon_map)
}

fn no_valid_config_message(configfile: &str) -> String {
    format!(
        "No valid launchers found.\nChecked: {configfile}\nExpected a YAML config using `version: 1` and a `launchers:` section.\nYou can copy `examples/raffi.yaml` as a starting point, or install desktop applications so Raffi can auto-detect them."
    )
}

/// Save the icon map to a cache file.
fn save_to_cache_file(map: &HashMap<String, String>) -> Result<()> {
    let cache_dir = icon_cache_dir();
    fs::create_dir_all(&cache_dir).context("Failed to create cache directory")?;

    let cache_file_path = cache_dir.join("icon.cache");
    let mut cache_file = File::create(&cache_file_path).context("Failed to create cache file")?;
    cache_file
        .write_all(
            serde_json::to_string(map)
                .context("Failed to serialize icon map")?
                .as_bytes(),
        )
        .context("Failed to write to cache file")?;
    Ok(())
}

/// Clear the icon cache file to force regeneration.
pub fn clear_icon_cache() -> Result<()> {
    let cache_path = icon_cache_dir().join("icon.cache");
    if Path::new(&cache_path).exists() {
        fs::remove_file(&cache_path).context("Failed to remove icon cache file")?;
    }
    Ok(())
}

/// Clear the cached emoji data files to force re-download.
pub fn clear_emoji_cache() -> Result<()> {
    let emoji_dir = icon_cache_dir().join("emoji");
    if Path::new(&emoji_dir).exists() {
        fs::remove_dir_all(&emoji_dir).context("Failed to remove emoji cache directory")?;
    }
    Ok(())
}

/// Read the icon map from the cache file or generate it if it doesn't exist.
pub fn read_icon_map() -> Result<HashMap<String, String>> {
    let cache_path = icon_cache_dir().join("icon.cache");

    if !Path::new(&cache_path).exists() {
        let icon_map = get_icon_map()?;
        save_to_cache_file(&icon_map)?;
        return Ok(icon_map);
    }

    let mut cache_file = File::open(&cache_path).context("Failed to open cache file")?;
    let mut contents = String::new();
    cache_file
        .read_to_string(&mut contents)
        .context("Failed to read cache file")?;
    serde_json::from_str(&contents).context("Failed to deserialize cache file")
}

/// Quote a string for safe use as a single POSIX shell word.
/// Already-safe tokens are left as-is so the output stays readable.
fn shell_quote(value: &str) -> String {
    let is_safe = !value.is_empty()
        && value
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b"_./:=@%+-".contains(&b));
    if is_safe {
        return value.to_string();
    }
    format!("'{}'", value.replace('\'', r"'\''"))
}

/// Render a word that appears in command position.
///
/// The exec path uses `Command::new`, which always runs an external program, while a shell would
/// first resolve the name as an alias, function, reserved word or builtin. Bare names are therefore
/// routed through `env`, which performs the same `PATH` lookup, so that a launcher named `echo` or
/// `source` behaves the same whether Raffi runs it or a shell does.
fn format_command_word(value: &str) -> String {
    if value.contains('/') {
        // A path is never resolved as an alias, function, reserved word or builtin.
        return shell_quote(value);
    }
    if value.contains('=') {
        // `env` would read this as an environment assignment. Quoting is enough on its own here,
        // because no alias, function name, reserved word or builtin can contain '='.
        return format!("'{}'", value.replace('\'', r"'\''"));
    }
    format!("env -- {}", shell_quote(value))
}

/// Format the command that would be run as a shell-ready, quoted command line.
///
/// The output is meant to be evaluated by a shell (`sh -c "$cmd"`, `swaymsg exec -- "$cmd"`,
/// `hyprctl dispatch exec "$cmd"`), not to be word-split by `xargs`. Script entries are rendered as
/// `<interpreter> -c '<script>' [<interpreter> <args>...]`, mirroring how [`execute_chosen_command`]
/// spawns them; a multi-line script therefore stays multi-line inside its quotes.
fn format_print_only_command(mc: &RaffiConfig, interpreter: &str) -> Result<String> {
    let mut parts = Vec::new();

    if let Some(script) = &mc.script {
        parts.push(format_command_word(interpreter));
        parts.push("-c".to_string());
        parts.push(shell_quote(script));
        if let Some(args) = &mc.args {
            // Passed as $0 by the exec path, so the script can reference $1..$n.
            parts.push(shell_quote(interpreter));
            parts.extend(args.iter().map(|arg| shell_quote(arg)));
        }
    } else {
        let binary = mc.binary.as_deref().context("Binary not found")?;
        parts.push(format_command_word(binary));
        parts.extend(
            mc.args
                .as_deref()
                .unwrap_or(&[])
                .iter()
                .map(|arg| shell_quote(arg)),
        );
    }

    Ok(parts.join(" "))
}

/// Execute the chosen command or script.
pub fn execute_chosen_command(mc: &RaffiConfig, args: &Args, interpreter: &str) -> Result<()> {
    if args.print_only {
        println!("{}", format_print_only_command(mc, interpreter)?);
        return Ok(());
    }
    if let Some(script) = &mc.script {
        let mut command = Command::new(interpreter);
        command.arg("-c").arg(script);
        if let Some(args) = &mc.args {
            command.arg(interpreter);
            command.args(args);
        }
        command.spawn().context("cannot launch script")?;
    } else {
        Command::new(mc.binary.as_deref().context("Binary not found")?)
            .args(mc.args.as_deref().unwrap_or(&[]))
            .spawn()
            .context("cannot launch command")?;
    }
    Ok(())
}

/// Percent-encode a query string for use in URLs.
/// Encodes all characters except unreserved ones (A-Z, a-z, 0-9, '-', '.', '_', '~').
pub fn url_encode_query(query: &str) -> String {
    let mut encoded = String::with_capacity(query.len() * 3);
    for byte in query.bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
                encoded.push(byte as char);
            }
            _ => {
                write!(encoded, "%{:02X}", byte).unwrap();
            }
        }
    }
    encoded
}

/// Build a web search URL by replacing `{query}` in the template with the percent-encoded query,
/// then open it with `xdg-open`.
pub fn execute_web_search_url(url_template: &str, query: &str) -> Result<()> {
    let encoded = url_encode_query(query);
    let url = url_template.replace("{query}", &encoded);
    Command::new("xdg-open")
        .arg(&url)
        .spawn()
        .context("cannot open web search URL")?;
    Ok(())
}

/// Generate the JSON Schema for the raffi config format.
fn generate_schema() -> String {
    let schema = schemars::schema_for!(ConfigSchema);
    serde_json::to_string_pretty(&schema).expect("Failed to serialize JSON Schema")
}

pub fn run(args: Args) -> Result<()> {
    if let Some(ref path) = args.debug_file {
        debug::init(path);
        debug_log!("raffi starting, debug log: {path}");
    }

    if args.version {
        println!("raffi version 0.1.0");
        return Ok(());
    }

    if args.schema {
        println!("{}", generate_schema());
        return Ok(());
    }

    if args.refresh_cache {
        clear_icon_cache()?;
        clear_emoji_cache()?;
    }

    let default_config_path = format!(
        "{}/.config/raffi/raffi.yaml",
        std::env::var("HOME").unwrap_or_default()
    );
    let configfile = args.configfile.as_deref().unwrap_or(&default_config_path);
    debug_log!("config: using file {configfile}");
    let config_exists = Path::new(configfile).exists();

    // Write schema file if it doesn't exist yet
    let config_dir = Path::new(configfile).parent().unwrap_or(Path::new("."));
    let schema_path = config_dir.join("raffi-schema.json");
    if !schema_path.exists() && fs::create_dir_all(config_dir).is_ok() {
        if let Err(e) = fs::write(&schema_path, generate_schema()) {
            eprintln!(
                "Warning: could not write schema file {}: {e}",
                schema_path.display()
            );
        }
    }

    let mut parsed_config = if config_exists {
        read_config(configfile, &args).context("Failed to read config")?
    } else {
        ParsedConfig {
            general: GeneralConfig::default(),
            addons: AddonsConfig::default(),
            entries: Vec::new(),
        }
    };
    debug_log!("config: loaded {} entries", parsed_config.entries.len());

    if parsed_config.entries.is_empty() {
        let detected_entries = detect_desktop_entries(&DefaultBinaryChecker);
        if detected_entries.is_empty() {
            eprintln!("{}", no_valid_config_message(configfile));
            std::process::exit(1);
        }

        eprintln!(
            "No valid launchers found in {configfile}; using {} auto-detected desktop applications.",
            detected_entries.len()
        );
        parsed_config.entries = detected_entries;
    }

    // Merge general config: CLI flags override config values
    let general = &parsed_config.general;
    let no_icons = args.no_icons || general.no_icons.unwrap_or(false);
    let ui_type_str = args.ui_type.as_ref().or(general.ui_type.as_ref());
    let default_script_shell = args
        .default_script_shell
        .as_deref()
        .or(general.default_script_shell.as_deref())
        .unwrap_or("bash")
        .to_string();

    // Determine theme
    let theme_str = args.theme.as_ref().or(general.theme.as_ref());
    let theme = if let Some(theme_str) = theme_str {
        theme_str
            .parse::<ThemeMode>()
            .map_err(|e| anyhow::anyhow!(e))?
    } else {
        ThemeMode::Dark
    };
    debug_log!("config: theme={theme:?}");

    // Determine UI type
    let ui_type = if let Some(ui_type_str) = ui_type_str {
        ui_type_str
            .parse::<UIType>()
            .map_err(|e| anyhow::anyhow!(e))?
    } else if find_binary("fuzzel") && general.fallbacks.is_empty() {
        UIType::Fuzzel
    } else {
        #[cfg(feature = "wayland")]
        {
            UIType::Native
        }
        #[cfg(not(feature = "wayland"))]
        {
            return Err(anyhow::anyhow!(
                "No UI backend available. Install 'fuzzel' or build with the 'wayland' feature."
            ));
        }
    };

    if ui_type == UIType::Fuzzel && !general.fallbacks.is_empty() {
        eprintln!("Warning: fallbacks are configured but ui_type is fuzzel — fallbacks require the native UI. Set ui_type: native to use fallbacks.");
    }

    debug_log!("config: ui_type={ui_type:?}");

    // Determine max history size
    let max_history = general.max_history.unwrap_or(10);

    // Determine font sizes (and proportional paddings)
    let mut font_sizes = if let Some(base) = general.font_size {
        ui::FontSizes::from_base(base)
    } else {
        ui::FontSizes::default_sizes()
    };

    // Override outer padding if explicitly set
    if let Some(padding) = general.padding {
        font_sizes.outer_padding = padding;
    }

    // Build UI settings
    let ui_settings = ui::UISettings {
        no_icons,
        initial_query: args.initial_query.clone(),
        theme,
        theme_colors: parsed_config.general.theme_colors.clone(),
        max_history,
        font_sizes,
        font_family: general.font_family.clone(),
        window_width: general.window_width.unwrap_or(800.0),
        window_height: general.window_height.unwrap_or(600.0),
        sort_mode: general.sort_mode.clone(),
        fallbacks: general.fallbacks.clone(),
    };

    debug_log!(
        "ui: settings: no_icons={} window={}x{} max_history={} sort_mode={:?}",
        ui_settings.no_icons,
        ui_settings.window_width,
        ui_settings.window_height,
        ui_settings.max_history,
        ui_settings.sort_mode
    );

    // Get the appropriate UI implementation
    let ui = ui::get_ui(ui_type);
    let chosen = ui
        .show(&parsed_config.entries, &parsed_config.addons, &ui_settings)
        .context("Failed to show UI")?;

    let chosen_name = chosen.trim();
    debug_log!("ui: chosen={chosen_name:?}");
    if chosen_name.is_empty() {
        std::process::exit(0);
    }
    let mc = parsed_config
        .entries
        .iter()
        .find(|mc| {
            mc.description.as_deref() == Some(chosen_name)
                || mc.binary.as_deref() == Some(chosen_name)
        })
        .context("No matching configuration found")?;

    let interpreter = if mc.script.is_some() {
        mc.binary.as_deref().unwrap_or(&default_script_shell)
    } else {
        // Not used for binary commands
        ""
    };
    debug_log!(
        "exec: binary={:?} script={} args={:?}",
        mc.binary,
        mc.script.is_some(),
        mc.args
    );
    execute_chosen_command(mc, &args, interpreter).context("Failed to execute command")?;

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Cursor;
    use std::os::unix::fs::PermissionsExt;
    use std::time::{SystemTime, UNIX_EPOCH};

    fn temp_test_dir(name: &str) -> PathBuf {
        let unique = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let path = std::env::temp_dir().join(format!("raffi-{name}-{unique}"));
        fs::create_dir_all(&path).unwrap();
        path
    }

    fn script_config(script: &str, args: Option<Vec<&str>>) -> RaffiConfig {
        RaffiConfig {
            script: Some(script.to_string()),
            args: args.map(|args| args.iter().map(|arg| arg.to_string()).collect()),
            ..Default::default()
        }
    }

    fn binary_config(binary: Option<&str>, args: Option<Vec<&str>>) -> RaffiConfig {
        RaffiConfig {
            binary: binary.map(str::to_string),
            args: args.map(|args| args.iter().map(|arg| arg.to_string()).collect()),
            ..Default::default()
        }
    }

    #[test]
    fn test_print_only_script_without_args_has_no_dollar_zero() {
        let config = script_config("echo hello", None);
        assert_eq!(
            format_print_only_command(&config, "bash").unwrap(),
            "env -- bash -c 'echo hello'"
        );
    }

    #[test]
    fn test_print_only_script_with_empty_args_keeps_dollar_zero() {
        // Matches the exec path: Some(vec![]) still pushes the interpreter as $0.
        let config = script_config("echo hello", Some(vec![]));
        assert_eq!(
            format_print_only_command(&config, "bash").unwrap(),
            "env -- bash -c 'echo hello' bash"
        );
    }

    #[test]
    fn test_print_only_script_quotes_args() {
        let config = script_config("echo \"$1\"", Some(vec!["foo", "bar baz"]));
        assert_eq!(
            format_print_only_command(&config, "bash").unwrap(),
            "env -- bash -c 'echo \"$1\"' bash foo 'bar baz'"
        );
    }

    #[test]
    fn test_print_only_script_escapes_single_quotes() {
        let config = script_config("echo 'hi there'", None);
        assert_eq!(
            format_print_only_command(&config, "bash").unwrap(),
            r#"env -- bash -c 'echo '\''hi there'\'''"#
        );
    }

    #[test]
    fn test_print_only_script_preserves_newlines() {
        let config = script_config("echo one\necho two", None);
        assert_eq!(
            format_print_only_command(&config, "sh").unwrap(),
            "env -- sh -c 'echo one\necho two'"
        );
    }

    #[test]
    fn test_print_only_binary_with_safe_args_is_unquoted() {
        let config = binary_config(
            Some("/usr/bin/firefox"),
            Some(vec!["--new-window", "--width=100"]),
        );
        assert_eq!(
            format_print_only_command(&config, "").unwrap(),
            "/usr/bin/firefox --new-window --width=100"
        );
    }

    #[test]
    fn test_print_only_binary_quotes_unsafe_args() {
        let config = binary_config(Some("kitty"), Some(vec!["hello world", "; rm -rf /tmp/x"]));
        assert_eq!(
            format_print_only_command(&config, "").unwrap(),
            "env -- kitty 'hello world' '; rm -rf /tmp/x'"
        );
    }

    #[test]
    fn test_print_only_formats_command_position_words() {
        // Bare names are routed through env so a PATH lookup happens, as Command::new does.
        assert_eq!(format_command_word("firefox"), "env -- firefox");
        assert_eq!(format_command_word("source"), "env -- source");
        // Paths cannot be resolved as an alias, function, reserved word or builtin.
        assert_eq!(format_command_word("/usr/bin/firefox"), "/usr/bin/firefox");
        assert_eq!(format_command_word("./my app"), "'./my app'");
        // env would read this as an environment assignment, so quoting is used instead.
        assert_eq!(format_command_word("FOO=bar"), "'FOO=bar'");
        // Only command position is affected; arguments may safely contain '='.
        assert_eq!(shell_quote("--width=100"), "--width=100");
    }

    #[test]
    fn test_print_only_missing_binary_errors() {
        let config = binary_config(None, None);
        assert!(format_print_only_command(&config, "").is_err());
    }

    #[test]
    fn test_print_only_script_round_trips_through_shell() {
        let config = script_config(
            "printf '%s|%s|%s' \"$0\" \"$1\" \"$2\"",
            Some(vec!["first arg", "it's second"]),
        );
        let formatted = format_print_only_command(&config, "sh").unwrap();

        let output = Command::new("sh")
            .arg("-c")
            .arg(&formatted)
            .output()
            .expect("failed to run formatted command");

        assert_eq!(
            String::from_utf8_lossy(&output.stdout),
            "sh|first arg|it's second"
        );
    }

    #[test]
    fn test_print_only_binary_round_trips_through_shell() {
        let config = binary_config(Some("printf"), Some(vec!["%s|%s", "hello world", "a'b"]));
        let formatted = format_print_only_command(&config, "").unwrap();

        let output = Command::new("sh")
            .arg("-c")
            .arg(&formatted)
            .output()
            .expect("failed to run formatted command");

        assert_eq!(String::from_utf8_lossy(&output.stdout), "hello world|a'b");
    }

    /// Put `dir` ahead of the standard directories so its executables shadow the real ones.
    fn shadowed_path(dir: &Path) -> String {
        format!("{}:/usr/bin:/bin", dir.display())
    }

    /// Write an executable that prints each argument it receives on its own line.
    fn write_argv_printer(dir: &Path, name: &str) {
        let path = dir.join(name);
        fs::write(
            &path,
            "#!/bin/sh\nprintf 'EXTERNAL\\n'\nfor a in \"$@\"; do printf '[%s]\\n' \"$a\"; done\n",
        )
        .unwrap();
        let mut perms = fs::metadata(&path).unwrap().permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&path, perms).unwrap();
    }

    /// A `binary` that collides with a shell builtin must still run the external program, the way
    /// `Command::new` does, and its arguments must never be evaluated as shell syntax.
    #[test]
    fn test_print_only_binary_shadowing_builtin_runs_external_program() {
        let dir = temp_test_dir("builtin-collision");
        write_argv_printer(&dir, "printf");

        let config = binary_config(Some("printf"), Some(vec!["$(id -u)", "a b; echo pwned"]));
        let formatted = format_print_only_command(&config, "").unwrap();

        let output = Command::new("/bin/sh")
            .arg("-c")
            .arg(&formatted)
            .env("PATH", shadowed_path(&dir))
            .output()
            .expect("failed to run formatted command");
        let stdout = String::from_utf8_lossy(&output.stdout);

        assert_eq!(stdout, "EXTERNAL\n[$(id -u)]\n[a b; echo pwned]\n");
        assert!(!stdout.contains("pwned\n[") && !stdout.ends_with("pwned\n"));

        let _ = fs::remove_dir_all(&dir);
    }

    /// `source` is a builtin in Bash but not in every shell, which is why the rule cannot rely on a
    /// list of builtin names.
    #[test]
    fn test_print_only_binary_shadowing_shell_specific_builtin_runs_external_program() {
        let dir = temp_test_dir("source-collision");
        write_argv_printer(&dir, "source");

        let config = binary_config(Some("source"), Some(vec!["/etc/hostname"]));
        let formatted = format_print_only_command(&config, "").unwrap();

        let output = Command::new("/bin/sh")
            .arg("-c")
            .arg(&formatted)
            .env("PATH", shadowed_path(&dir))
            .output()
            .expect("failed to run formatted command");

        assert_eq!(
            String::from_utf8_lossy(&output.stdout),
            "EXTERNAL\n[/etc/hostname]\n"
        );

        let _ = fs::remove_dir_all(&dir);
    }

    /// A shell function defined in the evaluating shell must not take over from the real program.
    #[test]
    fn test_print_only_binary_shadowed_by_shell_function_runs_external_program() {
        let dir = temp_test_dir("function-collision");
        write_argv_printer(&dir, "raffifakeapp");

        let config = binary_config(Some("raffifakeapp"), Some(vec!["one"]));
        let formatted = format_print_only_command(&config, "").unwrap();

        let output = Command::new("/bin/sh")
            .arg("-c")
            .arg(format!(
                "raffifakeapp() {{ printf 'FUNCTION\\n'; }}\n{formatted}"
            ))
            .env("PATH", shadowed_path(&dir))
            .output()
            .expect("failed to run formatted command");

        assert_eq!(String::from_utf8_lossy(&output.stdout), "EXTERNAL\n[one]\n");

        let _ = fs::remove_dir_all(&dir);
    }

    /// The same protection applies to a script interpreter whose name collides with a builtin.
    #[test]
    fn test_print_only_script_interpreter_shadowing_builtin_runs_external_program() {
        let dir = temp_test_dir("interpreter-collision");
        write_argv_printer(&dir, "test");

        let config = script_config("echo hello", None);
        let formatted = format_print_only_command(&config, "test").unwrap();

        let output = Command::new("/bin/sh")
            .arg("-c")
            .arg(&formatted)
            .env("PATH", shadowed_path(&dir))
            .output()
            .expect("failed to run formatted command");

        assert_eq!(
            String::from_utf8_lossy(&output.stdout),
            "EXTERNAL\n[-c]\n[echo hello]\n"
        );

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_read_config_from_reader() {
        let yaml_config = r#"
        shell:
          binary: sh
          description: "Shell"
        hello_script:
          script: "echo hello"
          description: "Hello script"
        "#;
        let reader = Cursor::new(yaml_config);
        let args = Args {
            help: false,
            version: false,
            configfile: None,
            print_only: false,
            refresh_cache: false,
            no_icons: true,
            default_script_shell: None,
            ui_type: None,
            initial_query: None,
            theme: None,
            schema: false,
            debug_file: None,
        };
        let parsed_config = read_config_from_reader(reader, &args).unwrap();
        assert_eq!(parsed_config.entries.len(), 2);

        // Addons should default to enabled
        assert!(parsed_config.addons.currency.enabled);
        assert!(parsed_config.addons.calculator.enabled);

        let expected_configs = vec![
            RaffiConfig {
                binary: Some("sh".to_string()),
                description: Some("Shell".to_string()),
                ..Default::default()
            },
            RaffiConfig {
                description: Some("Hello script".to_string()),
                script: Some("echo hello".to_string()),
                ..Default::default()
            },
        ];

        for expected_config in &expected_configs {
            assert!(parsed_config.entries.contains(expected_config));
        }
    }

    #[test]
    fn test_addons_config_parsing() {
        let yaml_config = r#"
        addons:
          currency:
            enabled: true
            currencies: ["USD", "EUR", "GBP"]
          calculator:
            enabled: false
        shell:
          binary: sh
          description: "Shell"
        "#;
        let reader = Cursor::new(yaml_config);
        let args = Args {
            help: false,
            version: false,
            configfile: None,
            print_only: false,
            refresh_cache: false,
            no_icons: true,
            default_script_shell: None,
            ui_type: None,
            initial_query: None,
            theme: None,
            schema: false,
            debug_file: None,
        };
        let parsed_config = read_config_from_reader(reader, &args).unwrap();

        assert!(parsed_config.addons.currency.enabled);
        assert!(!parsed_config.addons.calculator.enabled);
        assert_eq!(
            parsed_config.addons.currency.currencies,
            Some(vec![
                "USD".to_string(),
                "EUR".to_string(),
                "GBP".to_string()
            ])
        );
        assert_eq!(parsed_config.entries.len(), 1);
    }

    struct MockEnvProvider {
        vars: HashMap<String, String>,
    }

    impl EnvProvider for MockEnvProvider {
        fn var(&self, key: &str) -> Result<String, std::env::VarError> {
            self.vars
                .get(key)
                .cloned()
                .ok_or(std::env::VarError::NotPresent)
        }
    }

    struct MockBinaryChecker {
        binaries: Vec<String>,
    }

    impl BinaryChecker for MockBinaryChecker {
        fn exists(&self, binary: &str) -> bool {
            self.binaries.contains(&binary.to_string())
        }
    }

    #[test]
    fn test_is_valid_config() {
        let mut config = RaffiConfig {
            binary: Some("test-binary".to_string()),
            description: Some("Test Description".to_string()),
            script: None,
            args: None,
            icon: None,
            ifenveq: Some(vec!["TEST_VAR".to_string(), "true".to_string()]),
            ifenvset: Some("ANOTHER_VAR".to_string()),
            ifenvnotset: Some("MISSING_VAR".to_string()),
            ifexist: Some("another-binary".to_string()),
            disabled: None,
        };
        let args = Args {
            help: false,
            version: false,
            configfile: None,
            print_only: false,
            refresh_cache: false,
            no_icons: true,
            default_script_shell: None,
            ui_type: None,
            initial_query: None,
            theme: None,
            schema: false,
            debug_file: None,
        };
        let env_provider = MockEnvProvider {
            vars: {
                let mut vars = HashMap::new();
                vars.insert("TEST_VAR".to_string(), "true".to_string());
                vars.insert("ANOTHER_VAR".to_string(), "some_value".to_string());
                vars
            },
        };
        let binary_checker = MockBinaryChecker {
            binaries: vec!["test-binary".to_string(), "another-binary".to_string()],
        };

        assert!(is_valid_config(
            &mut config,
            &args,
            &env_provider,
            &binary_checker
        ));
    }

    #[test]
    fn test_script_filter_action_parsing() {
        let yaml_config = r#"
        addons:
          script_filters:
            - name: "Bookmarks"
              keyword: "bm"
              command: "my-bookmark-script"
              args: ["-j"]
              action: "wl-copy {value}"
              secondary_action: "xdg-open {value}"
            - name: "Timezones"
              keyword: "tz"
              command: "batz"
              args: ["-j"]
        shell:
          binary: sh
          description: "Shell"
        "#;
        let reader = Cursor::new(yaml_config);
        let args = Args {
            help: false,
            version: false,
            configfile: None,
            print_only: false,
            refresh_cache: false,
            no_icons: true,
            default_script_shell: None,
            ui_type: None,
            initial_query: None,
            theme: None,
            schema: false,
            debug_file: None,
        };
        let parsed_config = read_config_from_reader(reader, &args).unwrap();

        assert_eq!(parsed_config.addons.script_filters.len(), 2);

        let bm = &parsed_config.addons.script_filters[0];
        assert_eq!(bm.name, "Bookmarks");
        assert_eq!(bm.action, Some("wl-copy {value}".to_string()));
        assert_eq!(bm.secondary_action, Some("xdg-open {value}".to_string()));

        let tz = &parsed_config.addons.script_filters[1];
        assert_eq!(tz.name, "Timezones");
        assert_eq!(tz.action, None);
        assert_eq!(tz.secondary_action, None);
    }

    #[test]
    fn test_text_snippet_action_parsing() {
        let yaml_config = r#"
        addons:
          text_snippets:
            - name: "Emails"
              keyword: "em"
              action: "wl-copy {value}"
              secondary_action: "wtype {value}"
              snippets:
                - name: "Personal"
                  value: "user@example.com"
            - name: "Plain"
              keyword: "pl"
              snippets:
                - name: "Hello"
                  value: "hello"
        shell:
          binary: sh
          description: "Shell"
        "#;
        let reader = Cursor::new(yaml_config);
        let args = Args {
            help: false,
            version: false,
            configfile: None,
            print_only: false,
            refresh_cache: false,
            no_icons: true,
            default_script_shell: None,
            ui_type: None,
            initial_query: None,
            theme: None,
            schema: false,
            debug_file: None,
        };
        let parsed_config = read_config_from_reader(reader, &args).unwrap();

        assert_eq!(parsed_config.addons.text_snippets.len(), 2);

        let em = &parsed_config.addons.text_snippets[0];
        assert_eq!(em.name, "Emails");
        assert_eq!(em.action, Some("wl-copy {value}".to_string()));
        assert_eq!(em.secondary_action, Some("wtype {value}".to_string()));

        let pl = &parsed_config.addons.text_snippets[1];
        assert_eq!(pl.name, "Plain");
        assert_eq!(pl.action, None);
        assert_eq!(pl.secondary_action, None);
    }

    #[test]
    fn test_expand_tilde() {
        let home = std::env::var("HOME").unwrap();
        assert_eq!(expand_tilde("~/foo/bar"), format!("{home}/foo/bar"));
    }

    #[test]
    fn test_expand_tilde_no_tilde() {
        assert_eq!(expand_tilde("/usr/bin/foo"), "/usr/bin/foo");
        assert_eq!(expand_tilde("relative/path"), "relative/path");
    }

    #[test]
    fn test_expand_env_vars() {
        let home = std::env::var("HOME").unwrap();
        assert_eq!(expand_env_vars("${HOME}/foo"), format!("{home}/foo"));
    }

    #[test]
    fn test_expand_env_vars_unknown() {
        assert_eq!(expand_env_vars("${NONEXISTENT_VAR_12345}/foo"), "/foo");
    }

    #[test]
    fn test_expand_env_vars_multiple() {
        let home = std::env::var("HOME").unwrap();
        let user = std::env::var("USER").unwrap_or_default();
        assert_eq!(
            expand_env_vars("${HOME}/stuff/${USER}/data"),
            format!("{home}/stuff/{user}/data")
        );
    }

    #[test]
    fn test_expand_env_vars_no_vars() {
        assert_eq!(expand_env_vars("/usr/bin/foo"), "/usr/bin/foo");
        assert_eq!(expand_env_vars("plain text"), "plain text");
    }

    #[test]
    fn test_expand_config_value_combined() {
        let home = std::env::var("HOME").unwrap();
        let user = std::env::var("USER").unwrap_or_default();
        assert_eq!(
            expand_config_value("~/foo/${USER}/bar"),
            format!("{home}/foo/{user}/bar")
        );
    }

    #[test]
    fn test_config_expands_env_vars_in_fields() {
        let home = std::env::var("HOME").unwrap();
        let yaml_config = r#"
        version: 1
        launchers:
          myapp:
            binary: "${HOME}/bin/myapp"
            description: "My App"
            args: ["${HOME}/Downloads/file.txt", "--verbose"]
            icon: "${HOME}/icons/myapp.png"
            ifexist: "${HOME}/bin/myapp"
        "#;
        let reader = Cursor::new(yaml_config);
        let config: super::Config = serde_yaml::from_reader(reader).expect("cannot parse config");
        let mut rafficonfigs = Vec::new();
        for value in config.launchers.values() {
            if value.is_mapping() {
                let mut mc: RaffiConfig = serde_yaml::from_value(value.clone()).unwrap();
                mc.binary = mc.binary.map(|s| expand_config_value(&s));
                mc.icon = mc.icon.map(|s| expand_config_value(&s));
                mc.ifexist = mc.ifexist.map(|s| expand_config_value(&s));
                mc.args = mc
                    .args
                    .map(|v| v.into_iter().map(|s| expand_config_value(&s)).collect());
                rafficonfigs.push(mc);
            }
        }

        assert_eq!(rafficonfigs.len(), 1);
        let mc = &rafficonfigs[0];
        assert_eq!(mc.binary, Some(format!("{home}/bin/myapp")));
        assert_eq!(mc.icon, Some(format!("{home}/icons/myapp.png")));
        assert_eq!(mc.ifexist, Some(format!("{home}/bin/myapp")));
        assert_eq!(
            mc.args,
            Some(vec![
                format!("{home}/Downloads/file.txt"),
                "--verbose".to_string()
            ])
        );
    }

    #[test]
    fn test_config_expands_tilde_in_fields() {
        let home = std::env::var("HOME").unwrap();
        let yaml_config = r#"
        version: 1
        launchers:
          myapp:
            binary: "~/bin/myapp"
            description: "My App"
            args: ["~/Downloads/file.txt", "--verbose"]
            icon: "~/icons/myapp.png"
            ifexist: "~/bin/myapp"
        "#;
        let reader = Cursor::new(yaml_config);
        // Parse and expand manually to avoid is_valid_config filtering out non-existent paths
        let config: super::Config = serde_yaml::from_reader(reader).expect("cannot parse config");
        let mut rafficonfigs = Vec::new();
        for value in config.launchers.values() {
            if value.is_mapping() {
                let mut mc: RaffiConfig = serde_yaml::from_value(value.clone()).unwrap();
                mc.binary = mc.binary.map(|s| expand_tilde(&s));
                mc.icon = mc.icon.map(|s| expand_tilde(&s));
                mc.ifexist = mc.ifexist.map(|s| expand_tilde(&s));
                mc.args = mc
                    .args
                    .map(|v| v.into_iter().map(|s| expand_tilde(&s)).collect());
                rafficonfigs.push(mc);
            }
        }

        assert_eq!(rafficonfigs.len(), 1);
        let mc = &rafficonfigs[0];
        assert_eq!(mc.binary, Some(format!("{home}/bin/myapp")));
        assert_eq!(mc.icon, Some(format!("{home}/icons/myapp.png")));
        assert_eq!(mc.ifexist, Some(format!("{home}/bin/myapp")));
        assert_eq!(
            mc.args,
            Some(vec![
                format!("{home}/Downloads/file.txt"),
                "--verbose".to_string()
            ])
        );
    }

    #[test]
    fn test_general_config_parsing() {
        let yaml_config = r#"
        general:
          ui_type: native
          default_script_shell: zsh
          no_icons: true
        shell:
          binary: sh
          description: "Shell"
        "#;
        let reader = Cursor::new(yaml_config);
        let args = Args {
            help: false,
            version: false,
            configfile: None,
            print_only: false,
            refresh_cache: false,
            no_icons: false,
            default_script_shell: None,
            ui_type: None,
            initial_query: None,
            theme: None,
            schema: false,
            debug_file: None,
        };
        let parsed_config = read_config_from_reader(reader, &args).unwrap();

        assert_eq!(parsed_config.general.ui_type, Some("native".to_string()));
        assert_eq!(
            parsed_config.general.default_script_shell,
            Some("zsh".to_string())
        );
        assert_eq!(parsed_config.general.no_icons, Some(true));
        assert_eq!(parsed_config.entries.len(), 1);
    }

    #[test]
    fn test_config_without_general_section() {
        let yaml_config = r#"
        shell:
          binary: sh
          description: "Shell"
        "#;
        let reader = Cursor::new(yaml_config);
        let args = Args {
            help: false,
            version: false,
            configfile: None,
            print_only: false,
            refresh_cache: false,
            no_icons: false,
            default_script_shell: None,
            ui_type: None,
            initial_query: None,
            theme: None,
            schema: false,
            debug_file: None,
        };
        let parsed_config = read_config_from_reader(reader, &args).unwrap();

        assert!(parsed_config.general.ui_type.is_none());
        assert!(parsed_config.general.default_script_shell.is_none());
        assert!(parsed_config.general.no_icons.is_none());
        assert_eq!(parsed_config.entries.len(), 1);
    }

    #[test]
    fn test_partial_general_config() {
        let yaml_config = r#"
        general:
          no_icons: true
        shell:
          binary: sh
          description: "Shell"
        "#;
        let reader = Cursor::new(yaml_config);
        let args = Args {
            help: false,
            version: false,
            configfile: None,
            print_only: false,
            refresh_cache: false,
            no_icons: false,
            default_script_shell: None,
            ui_type: None,
            initial_query: None,
            theme: None,
            schema: false,
            debug_file: None,
        };
        let parsed_config = read_config_from_reader(reader, &args).unwrap();

        assert!(parsed_config.general.ui_type.is_none());
        assert!(parsed_config.general.default_script_shell.is_none());
        assert_eq!(parsed_config.general.no_icons, Some(true));
        assert_eq!(parsed_config.entries.len(), 1);
    }

    #[test]
    fn test_general_config_ui_settings_parsing() {
        let yaml_config = r#"
        general:
          font_size: 16
          font_family: "Inter"
          window_width: 900
          window_height: 500
        shell:
          binary: sh
          description: "Shell"
        "#;
        let reader = Cursor::new(yaml_config);
        let args = Args {
            help: false,
            version: false,
            configfile: None,
            print_only: false,
            refresh_cache: false,
            no_icons: false,
            default_script_shell: None,
            ui_type: None,
            initial_query: None,
            theme: None,
            schema: false,
            debug_file: None,
        };
        let parsed_config = read_config_from_reader(reader, &args).unwrap();
        assert_eq!(parsed_config.general.font_size, Some(16.0));
        assert_eq!(parsed_config.general.font_family, Some("Inter".to_string()));
        assert_eq!(parsed_config.general.window_width, Some(900.0));
        assert_eq!(parsed_config.general.window_height, Some(500.0));
    }

    #[test]
    fn test_general_config_theme_parsing() {
        let yaml_config = r#"
        general:
          theme: light
        shell:
          binary: sh
          description: "Shell"
        "#;
        let reader = Cursor::new(yaml_config);
        let args = Args {
            help: false,
            version: false,
            configfile: None,
            print_only: false,
            refresh_cache: false,
            no_icons: false,
            default_script_shell: None,
            ui_type: None,
            initial_query: None,
            theme: None,
            schema: false,
            debug_file: None,
        };
        let parsed_config = read_config_from_reader(reader, &args).unwrap();
        assert_eq!(parsed_config.general.theme, Some("light".to_string()));
    }

    #[test]
    fn test_theme_mode_from_str() {
        assert_eq!("dark".parse::<ThemeMode>().unwrap(), ThemeMode::Dark);
        assert_eq!("Dark".parse::<ThemeMode>().unwrap(), ThemeMode::Dark);
        assert_eq!("DARK".parse::<ThemeMode>().unwrap(), ThemeMode::Dark);
        assert_eq!("light".parse::<ThemeMode>().unwrap(), ThemeMode::Light);
        assert_eq!("Light".parse::<ThemeMode>().unwrap(), ThemeMode::Light);
        assert_eq!("LIGHT".parse::<ThemeMode>().unwrap(), ThemeMode::Light);
        assert!("invalid".parse::<ThemeMode>().is_err());
    }

    #[test]
    fn test_url_encode_query() {
        assert_eq!(url_encode_query("hello"), "hello");
        assert_eq!(url_encode_query("hello world"), "hello%20world");
        assert_eq!(url_encode_query("rust traits"), "rust%20traits");
        assert_eq!(url_encode_query("a+b"), "a%2Bb");
        assert_eq!(url_encode_query("foo&bar=baz"), "foo%26bar%3Dbaz");
        assert_eq!(url_encode_query(""), "");
        assert_eq!(url_encode_query("A-Z_0.9~"), "A-Z_0.9~");
    }

    #[test]
    fn test_web_search_config_parsing() {
        let yaml_config = r#"
        addons:
          web_searches:
            - name: "Google"
              keyword: "g"
              url: "https://google.com/search?q={query}"
              icon: "google"
            - name: "DuckDuckGo"
              keyword: "ddg"
              url: "https://duckduckgo.com/?q={query}"
        shell:
          binary: sh
          description: "Shell"
        "#;
        let reader = Cursor::new(yaml_config);
        let args = Args {
            help: false,
            version: false,
            configfile: None,
            print_only: false,
            refresh_cache: false,
            no_icons: true,
            default_script_shell: None,
            ui_type: None,
            initial_query: None,
            theme: None,
            schema: false,
            debug_file: None,
        };
        let parsed_config = read_config_from_reader(reader, &args).unwrap();

        assert_eq!(parsed_config.addons.web_searches.len(), 2);

        let google = &parsed_config.addons.web_searches[0];
        assert_eq!(google.name, "Google");
        assert_eq!(google.keyword, "g");
        assert_eq!(google.url, "https://google.com/search?q={query}");
        assert_eq!(google.icon, Some("google".to_string()));

        let ddg = &parsed_config.addons.web_searches[1];
        assert_eq!(ddg.name, "DuckDuckGo");
        assert_eq!(ddg.keyword, "ddg");
        assert_eq!(ddg.url, "https://duckduckgo.com/?q={query}");
        assert!(ddg.icon.is_none());
    }

    #[test]
    fn test_text_snippet_config_parsing() {
        let yaml_config = r#"
        addons:
          text_snippets:
            - name: "Emails"
              keyword: "em"
              icon: "mail"
              snippets:
                - name: "Personal Email"
                  value: "user@example.com"
                - name: "Work Email"
                  value: "user@company.com"
            - name: "Templates"
              keyword: "tpl"
              file: "~/.config/raffi/snippets.yaml"
            - name: "Dynamic"
              keyword: "dyn"
              command: "my-snippet-gen"
              args: ["-j"]
        shell:
          binary: sh
          description: "Shell"
        "#;
        let reader = Cursor::new(yaml_config);
        let args = Args {
            help: false,
            version: false,
            configfile: None,
            print_only: false,
            refresh_cache: false,
            no_icons: true,
            default_script_shell: None,
            ui_type: None,
            initial_query: None,
            theme: None,
            schema: false,
            debug_file: None,
        };
        let parsed_config = read_config_from_reader(reader, &args).unwrap();

        assert_eq!(parsed_config.addons.text_snippets.len(), 3);

        // Inline snippets source
        let emails = &parsed_config.addons.text_snippets[0];
        assert_eq!(emails.name, "Emails");
        assert_eq!(emails.keyword, "em");
        assert_eq!(emails.icon, Some("mail".to_string()));
        let snippets = emails.snippets.as_ref().unwrap();
        assert_eq!(snippets.len(), 2);
        assert_eq!(snippets[0].name, "Personal Email");
        assert_eq!(snippets[0].value, "user@example.com");
        assert_eq!(snippets[1].name, "Work Email");
        assert_eq!(snippets[1].value, "user@company.com");

        // File source
        let templates = &parsed_config.addons.text_snippets[1];
        assert_eq!(templates.name, "Templates");
        assert_eq!(templates.keyword, "tpl");
        let home = std::env::var("HOME").unwrap();
        assert_eq!(
            templates.file,
            Some(format!("{home}/.config/raffi/snippets.yaml"))
        );
        assert!(templates.snippets.is_none());
        assert!(templates.command.is_none());

        // Command source
        let dynamic = &parsed_config.addons.text_snippets[2];
        assert_eq!(dynamic.name, "Dynamic");
        assert_eq!(dynamic.keyword, "dyn");
        assert_eq!(dynamic.command, Some("my-snippet-gen".to_string()));
        assert_eq!(dynamic.args, vec!["-j".to_string()]);
        assert!(dynamic.snippets.is_none());
        assert!(dynamic.file.is_none());
    }

    #[test]
    fn test_text_snippet_directory_config_parsing() {
        let yaml_config = r#"
        addons:
          text_snippets:
            - name: "Snippets"
              keyword: "sn"
              icon: "snippets"
              directory: "~/.local/share/snippets"
        shell:
          binary: sh
          description: "Shell"
        "#;
        let reader = Cursor::new(yaml_config);
        let args = Args {
            help: false,
            version: false,
            configfile: None,
            print_only: false,
            refresh_cache: false,
            no_icons: true,
            default_script_shell: None,
            ui_type: None,
            initial_query: None,
            theme: None,
            schema: false,
            debug_file: None,
        };
        let parsed_config = read_config_from_reader(reader, &args).unwrap();

        assert_eq!(parsed_config.addons.text_snippets.len(), 1);
        let snippets_dir = &parsed_config.addons.text_snippets[0];
        assert_eq!(snippets_dir.name, "Snippets");
        assert_eq!(snippets_dir.keyword, "sn");
        assert_eq!(snippets_dir.icon, Some("snippets".to_string()));
        let home = std::env::var("HOME").unwrap();
        assert_eq!(
            snippets_dir.directory,
            Some(format!("{home}/.local/share/snippets"))
        );
        assert!(snippets_dir.snippets.is_none());
        assert!(snippets_dir.file.is_none());
        assert!(snippets_dir.command.is_none());
    }

    #[test]
    fn test_text_snippet_defaults_to_empty() {
        let yaml_config = r#"
        shell:
          binary: sh
          description: "Shell"
        "#;
        let reader = Cursor::new(yaml_config);
        let args = Args {
            help: false,
            version: false,
            configfile: None,
            print_only: false,
            refresh_cache: false,
            no_icons: true,
            default_script_shell: None,
            ui_type: None,
            initial_query: None,
            theme: None,
            schema: false,
            debug_file: None,
        };
        let parsed_config = read_config_from_reader(reader, &args).unwrap();
        assert!(parsed_config.addons.text_snippets.is_empty());
    }

    #[test]
    fn test_emoji_addon_config_parsing() {
        let yaml_config = r#"
        addons:
          emoji:
            enabled: true
            trigger: "em"
            action: "insert"
            secondary_action: "copy"
            data_files:
              - emojis_smileys_emotion
              - nerd_font
        shell:
          binary: sh
          description: "Shell"
        "#;
        let reader = Cursor::new(yaml_config);
        let args = Args {
            help: false,
            version: false,
            configfile: None,
            print_only: false,
            refresh_cache: false,
            no_icons: true,
            default_script_shell: None,
            ui_type: None,
            initial_query: None,
            theme: None,
            schema: false,
            debug_file: None,
        };
        let parsed_config = read_config_from_reader(reader, &args).unwrap();

        assert!(parsed_config.addons.emoji.enabled);
        assert_eq!(parsed_config.addons.emoji.trigger, Some("em".to_string()));
        assert_eq!(
            parsed_config.addons.emoji.action,
            Some("insert".to_string())
        );
        assert_eq!(
            parsed_config.addons.emoji.secondary_action,
            Some("copy".to_string())
        );
        assert_eq!(
            parsed_config.addons.emoji.data_files,
            Some(vec![
                "emojis_smileys_emotion".to_string(),
                "nerd_font".to_string()
            ])
        );
    }

    #[test]
    fn test_emoji_addon_defaults_to_enabled() {
        let yaml_config = r#"
        shell:
          binary: sh
          description: "Shell"
        "#;
        let reader = Cursor::new(yaml_config);
        let args = Args {
            help: false,
            version: false,
            configfile: None,
            print_only: false,
            refresh_cache: false,
            no_icons: true,
            default_script_shell: None,
            ui_type: None,
            initial_query: None,
            theme: None,
            schema: false,
            debug_file: None,
        };
        let parsed_config = read_config_from_reader(reader, &args).unwrap();

        // Emoji addon is enabled by default
        assert!(parsed_config.addons.emoji.enabled);
        assert!(parsed_config.addons.emoji.trigger.is_none());
        assert!(parsed_config.addons.emoji.action.is_none());
        assert!(parsed_config.addons.emoji.secondary_action.is_none());
        assert!(parsed_config.addons.emoji.data_files.is_none());
    }

    #[test]
    fn test_v0_config_migrated_in_memory() {
        // v0 format: launcher entries at top level (no version field)
        let yaml_config = r#"
        general:
          no_icons: true
        addons:
          calculator:
            enabled: false
        shell:
          binary: sh
          description: "Shell"
        firefox:
          binary: firefox
          description: "Firefox"
        "#;
        let reader = Cursor::new(yaml_config);
        let args = Args {
            help: false,
            version: false,
            configfile: None,
            print_only: false,
            refresh_cache: false,
            no_icons: true,
            default_script_shell: None,
            ui_type: None,
            initial_query: None,
            theme: None,
            schema: false,
            debug_file: None,
        };
        let parsed_config = read_config_from_reader(reader, &args).unwrap();

        // general and addons should be preserved
        assert_eq!(parsed_config.general.no_icons, Some(true));
        assert!(!parsed_config.addons.calculator.enabled);

        // launcher entries should be found
        assert_eq!(parsed_config.entries.len(), 2);
    }

    #[test]
    fn test_v1_config_passes_through() {
        // v1 format: entries under launchers key
        let yaml_config = r#"
        version: 1
        general:
          no_icons: true
        launchers:
          shell:
            binary: sh
            description: "Shell"
          firefox:
            binary: firefox
            description: "Firefox"
        "#;
        let reader = Cursor::new(yaml_config);
        let args = Args {
            help: false,
            version: false,
            configfile: None,
            print_only: false,
            refresh_cache: false,
            no_icons: true,
            default_script_shell: None,
            ui_type: None,
            initial_query: None,
            theme: None,
            schema: false,
            debug_file: None,
        };
        let parsed_config = read_config_from_reader(reader, &args).unwrap();

        assert_eq!(parsed_config.general.no_icons, Some(true));
        assert_eq!(parsed_config.entries.len(), 2);
    }

    #[test]
    fn test_migrate_v0_to_v1_moves_keys() {
        let yaml_str = r#"
        general:
          no_icons: true
        addons:
          calculator:
            enabled: false
        shell:
          binary: sh
          description: "Shell"
        firefox:
          binary: firefox
          description: "Firefox"
        "#;
        let mut raw: Value = serde_yaml::from_str(yaml_str).unwrap();

        // Create a temp file for migration
        let dir = std::env::temp_dir();
        let config_path = dir.join("test_migrate_v0.yaml");
        fs::write(&config_path, yaml_str).unwrap();

        let migrated = migrate_config_v0_to_v1(config_path.to_str().unwrap(), &mut raw).unwrap();
        assert!(migrated);

        // Check structure after migration
        let mapping = raw.as_mapping().unwrap();
        assert!(mapping.contains_key(Value::String("version".to_string())));
        assert!(mapping.contains_key(Value::String("launchers".to_string())));
        assert!(mapping.contains_key(Value::String("general".to_string())));
        assert!(mapping.contains_key(Value::String("addons".to_string())));

        // shell and firefox should NOT be top-level anymore
        assert!(!mapping.contains_key(Value::String("shell".to_string())));
        assert!(!mapping.contains_key(Value::String("firefox".to_string())));

        // They should be inside launchers
        let launchers = mapping
            .get(Value::String("launchers".to_string()))
            .unwrap()
            .as_mapping()
            .unwrap();
        assert!(launchers.contains_key(Value::String("shell".to_string())));
        assert!(launchers.contains_key(Value::String("firefox".to_string())));

        // Backup should exist
        let backup_path = format!("{}.bak", config_path.to_str().unwrap());
        assert!(Path::new(&backup_path).exists());

        // Cleanup
        let _ = fs::remove_file(&config_path);
        let _ = fs::remove_file(&backup_path);
    }

    #[test]
    fn test_migrate_v1_is_noop() {
        let yaml_str = r#"
        version: 1
        launchers:
          shell:
            binary: sh
        "#;
        let mut raw: Value = serde_yaml::from_str(yaml_str).unwrap();

        let dir = std::env::temp_dir();
        let config_path = dir.join("test_migrate_v1_noop.yaml");
        fs::write(&config_path, yaml_str).unwrap();

        let migrated = migrate_config_v0_to_v1(config_path.to_str().unwrap(), &mut raw).unwrap();
        assert!(!migrated);

        // No backup should be created
        let backup_path = format!("{}.bak", config_path.to_str().unwrap());
        assert!(!Path::new(&backup_path).exists());

        // Cleanup
        let _ = fs::remove_file(&config_path);
    }

    #[test]
    fn test_schema_generation() {
        let schema = generate_schema();
        let parsed: serde_json::Value = serde_json::from_str(&schema).unwrap();

        // Should be a valid JSON Schema
        assert_eq!(parsed["type"], "object");

        // Should have our top-level properties
        let props = parsed["properties"].as_object().unwrap();
        assert!(props.contains_key("version"));
        assert!(props.contains_key("general"));
        assert!(props.contains_key("addons"));
        assert!(props.contains_key("launchers"));
    }

    #[test]
    fn test_find_binary_accepts_paths() {
        let dir = temp_test_dir("find-binary");
        let binary = dir.join("custom-tool");
        fs::write(&binary, "#!/bin/sh\n").unwrap();

        assert!(find_binary(binary.to_str().unwrap()));

        let _ = fs::remove_dir_all(dir);
    }

    #[test]
    fn test_parse_desktop_exec_strips_field_codes() {
        let (binary, args) = parse_desktop_exec(
            r#"/usr/bin/env BAMF_DESKTOP_FILE_HINT=%k /usr/bin/firefox --new-window %U"#,
        )
        .unwrap();

        assert_eq!(binary, "/usr/bin/env");
        assert_eq!(
            args,
            vec![
                "BAMF_DESKTOP_FILE_HINT=".to_string(),
                "/usr/bin/firefox".to_string(),
                "--new-window".to_string()
            ]
        );
    }

    #[test]
    fn test_detect_desktop_entries_from_dirs() {
        let dir = temp_test_dir("desktop-detect");
        let apps_dir = dir.join("applications");
        fs::create_dir_all(&apps_dir).unwrap();

        fs::write(
            apps_dir.join("firefox.desktop"),
            r#"[Desktop Entry]
Type=Application
Name=Firefox
Exec=firefox %U
Icon=firefox
"#,
        )
        .unwrap();
        fs::write(
            apps_dir.join("hidden.desktop"),
            r#"[Desktop Entry]
Type=Application
Name=Hidden App
Exec=hidden-app
Hidden=true
"#,
        )
        .unwrap();
        fs::write(
            apps_dir.join("missing-tryexec.desktop"),
            r#"[Desktop Entry]
Type=Application
Name=Missing TryExec
Exec=missing-app
TryExec=missing-app
"#,
        )
        .unwrap();
        fs::write(
            apps_dir.join("terminal.desktop"),
            r#"[Desktop Entry]
Type=Application
Name=Terminal App
Exec=terminal-app
Terminal=true
"#,
        )
        .unwrap();

        let checker = MockBinaryChecker {
            binaries: vec!["firefox".to_string()],
        };
        let detected = detect_desktop_entries_from_dirs(&[apps_dir], &checker);

        assert_eq!(detected.len(), 1);
        assert_eq!(detected[0].description.as_deref(), Some("Firefox"));
        assert_eq!(detected[0].binary.as_deref(), Some("firefox"));
        assert!(detected[0].args.as_deref().unwrap_or(&[]).is_empty());

        let _ = fs::remove_dir_all(dir);
    }

    #[test]
    fn test_desktop_entry_icon_map_from_dirs_uses_real_exec_binary() {
        let dir = temp_test_dir("desktop-icon-map");
        let apps_dir = dir.join("applications");
        fs::create_dir_all(&apps_dir).unwrap();

        fs::write(
            apps_dir.join("firefox.desktop"),
            r#"[Desktop Entry]
Type=Application
Name=Firefox
Exec=/usr/bin/env BAMF_DESKTOP_FILE_HINT=%k /usr/bin/firefox --new-window %U
Icon=firefox
"#,
        )
        .unwrap();

        let checker = MockBinaryChecker {
            binaries: vec![
                "/usr/bin/env".to_string(),
                "/usr/bin/firefox".to_string(),
                "firefox".to_string(),
            ],
        };
        let icon_map = desktop_entry_icon_map_from_dirs(&[apps_dir], &checker);

        assert_eq!(
            icon_map.get("/usr/bin/firefox"),
            Some(&"firefox".to_string())
        );
        assert_eq!(icon_map.get("firefox"), Some(&"firefox".to_string()));
        assert!(!icon_map.contains_key("/usr/bin/env"));
        assert!(!icon_map.contains_key("env"));

        let _ = fs::remove_dir_all(dir);
    }

    #[test]
    fn test_resolve_launcher_icon_path_uses_launcher_args_for_lookup() {
        let config = RaffiConfig {
            binary: Some("jumpapp".to_string()),
            args: Some(vec!["-X".to_string(), "firefox".to_string()]),
            description: Some("Firefox".to_string()),
            ..Default::default()
        };
        let icon_map = HashMap::from([("firefox".to_string(), "/icons/firefox.svg".to_string())]);

        let resolved = resolve_launcher_icon_path(&config, &icon_map, &HashMap::new());

        assert_eq!(resolved.as_deref(), Some("/icons/firefox.svg"));
    }

    #[test]
    fn test_resolve_launcher_icon_path_uses_desktop_icon_map() {
        let config = RaffiConfig {
            binary: Some("custom-launcher".to_string()),
            description: Some("Firefox".to_string()),
            ..Default::default()
        };
        let icon_map = HashMap::from([("firefox".to_string(), "/icons/firefox.svg".to_string())]);
        let desktop_icon_map =
            HashMap::from([("custom-launcher".to_string(), "firefox".to_string())]);

        let resolved = resolve_launcher_icon_path(&config, &icon_map, &desktop_icon_map);

        assert_eq!(resolved.as_deref(), Some("/icons/firefox.svg"));
    }

    #[test]
    fn test_resolve_icon_reference_ignores_non_icon_files() {
        let dir = temp_test_dir("resolve-icon-reference");
        let binary_path = dir.join("firefox");
        fs::write(&binary_path, "#!/bin/sh\n").unwrap();

        let icon_map = HashMap::from([("firefox".to_string(), "/icons/firefox.svg".to_string())]);
        let resolved = resolve_icon_reference(binary_path.to_str().unwrap(), &icon_map);

        assert_eq!(resolved.as_deref(), Some("/icons/firefox.svg"));

        let _ = fs::remove_dir_all(dir);
    }

    #[test]
    fn test_resolve_icon_reference_ignores_directories() {
        let dir = temp_test_dir("resolve-icon-directory");
        let resolved = resolve_icon_reference(dir.to_str().unwrap(), &HashMap::new());

        assert!(resolved.is_none());

        let _ = fs::remove_dir_all(dir);
    }

    #[test]
    fn test_default_icon_path_materializes_bundled_icon_without_repo_cwd() {
        let cache_root = temp_test_dir("default-icon-cache");
        let cwd = temp_test_dir("default-icon-cwd");
        let previous_cache_home = std::env::var_os("XDG_CACHE_HOME");
        let previous_cwd = std::env::current_dir().unwrap();

        std::env::set_var("XDG_CACHE_HOME", &cache_root);
        std::env::set_current_dir(&cwd).unwrap();

        let result = (|| {
            let resolved = default_icon_path(&HashMap::new()).unwrap();
            let resolved_path = PathBuf::from(&resolved);

            assert!(resolved_path.exists());
            assert_eq!(
                resolved_path.file_name().and_then(|name| name.to_str()),
                Some("default_icon.svg")
            );
            assert_eq!(fs::read(&resolved_path).unwrap(), DEFAULT_ICON_BYTES);
        })();

        std::env::set_current_dir(previous_cwd).unwrap();
        match previous_cache_home {
            Some(value) => std::env::set_var("XDG_CACHE_HOME", value),
            None => std::env::remove_var("XDG_CACHE_HOME"),
        }

        let _ = fs::remove_dir_all(cache_root);
        let _ = fs::remove_dir_all(cwd);

        result
    }
}