debian-watch 0.4.6

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

#[cfg(test)]
use crate::types::VersionPolicy;

/// Get the linebased option key name for a WatchOption variant
pub(crate) fn watch_option_to_key(option: &crate::types::WatchOption) -> &'static str {
    use crate::types::WatchOption;

    match option {
        WatchOption::Component(_) => "component",
        WatchOption::Compression(_) => "compression",
        WatchOption::UserAgent(_) => "user-agent",
        WatchOption::Pagemangle(_) => "pagemangle",
        WatchOption::Uversionmangle(_) => "uversionmangle",
        WatchOption::Dversionmangle(_) => "dversionmangle",
        WatchOption::Dirversionmangle(_) => "dirversionmangle",
        WatchOption::Oversionmangle(_) => "oversionmangle",
        WatchOption::Downloadurlmangle(_) => "downloadurlmangle",
        WatchOption::Pgpsigurlmangle(_) => "pgpsigurlmangle",
        WatchOption::Filenamemangle(_) => "filenamemangle",
        WatchOption::VersionPolicy(_) => "version-policy",
        WatchOption::Searchmode(_) => "searchmode",
        WatchOption::Mode(_) => "mode",
        WatchOption::Pgpmode(_) => "pgpmode",
        WatchOption::Gitexport(_) => "gitexport",
        WatchOption::Gitmode(_) => "gitmode",
        WatchOption::Pretty(_) => "pretty",
        WatchOption::Ctype(_) => "ctype",
        WatchOption::Repacksuffix(_) => "repacksuffix",
        WatchOption::Unzipopt(_) => "unzipopt",
        WatchOption::Script(_) => "script",
        WatchOption::Decompress => "decompress",
        WatchOption::Bare => "bare",
        WatchOption::Repack => "repack",
    }
}

/// Get the string value for a WatchOption variant
pub(crate) fn watch_option_to_value(option: &crate::types::WatchOption) -> String {
    use crate::types::WatchOption;

    match option {
        WatchOption::Component(v) => v.clone(),
        WatchOption::Compression(v) => v.to_string(),
        WatchOption::UserAgent(v) => v.clone(),
        WatchOption::Pagemangle(v) => v.clone(),
        WatchOption::Uversionmangle(v) => v.clone(),
        WatchOption::Dversionmangle(v) => v.clone(),
        WatchOption::Dirversionmangle(v) => v.clone(),
        WatchOption::Oversionmangle(v) => v.clone(),
        WatchOption::Downloadurlmangle(v) => v.clone(),
        WatchOption::Pgpsigurlmangle(v) => v.clone(),
        WatchOption::Filenamemangle(v) => v.clone(),
        WatchOption::VersionPolicy(v) => v.to_string(),
        WatchOption::Searchmode(v) => v.to_string(),
        WatchOption::Mode(v) => v.to_string(),
        WatchOption::Pgpmode(v) => v.to_string(),
        WatchOption::Gitexport(v) => v.to_string(),
        WatchOption::Gitmode(v) => v.to_string(),
        WatchOption::Pretty(v) => v.to_string(),
        WatchOption::Ctype(v) => v.to_string(),
        WatchOption::Repacksuffix(v) => v.clone(),
        WatchOption::Unzipopt(v) => v.clone(),
        WatchOption::Script(v) => v.clone(),
        WatchOption::Decompress => String::new(),
        WatchOption::Bare => String::new(),
        WatchOption::Repack => String::new(),
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
/// Error type for parsing line-based watch files
pub struct ParseError(pub Vec<String>);

impl std::fmt::Display for ParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        for err in &self.0 {
            writeln!(f, "{}", err)?;
        }
        Ok(())
    }
}

impl std::error::Error for ParseError {}

/// Second, implementing the `Language` trait teaches rowan to convert between
/// these two SyntaxKind types, allowing for a nicer SyntaxNode API where
/// "kinds" are values from our `enum SyntaxKind`, instead of plain u16 values.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Lang {}
impl rowan::Language for Lang {
    type Kind = SyntaxKind;
    fn kind_from_raw(raw: rowan::SyntaxKind) -> Self::Kind {
        unsafe { std::mem::transmute::<u16, SyntaxKind>(raw.0) }
    }
    fn kind_to_raw(kind: Self::Kind) -> rowan::SyntaxKind {
        kind.into()
    }
}

/// GreenNode is an immutable tree, which is cheap to change,
/// but doesn't contain offsets and parent pointers.
use rowan::GreenNode;

/// You can construct GreenNodes by hand, but a builder
/// is helpful for top-down parsers: it maintains a stack
/// of currently in-progress nodes
use rowan::GreenNodeBuilder;

/// Thread-safe parse result that can be stored in incremental computation systems like Salsa.
/// The type parameter T represents the root AST node type (e.g., WatchFile).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Parse<T> {
    /// The immutable green tree that can be shared across threads
    green: GreenNode,
    /// Parse errors encountered during parsing
    errors: Vec<String>,
    /// Phantom type to associate this parse result with a specific AST type
    _ty: PhantomData<T>,
}

impl<T> Parse<T> {
    /// Create a new parse result
    pub(crate) fn new(green: GreenNode, errors: Vec<String>) -> Self {
        Parse {
            green,
            errors,
            _ty: PhantomData,
        }
    }

    /// Get the green node
    pub fn green(&self) -> &GreenNode {
        &self.green
    }

    /// Get the parse errors
    pub fn errors(&self) -> &[String] {
        &self.errors
    }

    /// Check if there were any parse errors
    pub fn is_ok(&self) -> bool {
        self.errors.is_empty()
    }
}

impl Parse<WatchFile> {
    /// Get the root WatchFile node
    pub fn tree(&self) -> WatchFile {
        WatchFile::cast(SyntaxNode::new_root_mut(self.green.clone()))
            .expect("root node should be a WatchFile")
    }
}

// Implement Send + Sync since GreenNode is thread-safe
// This allows Parse to be stored in Salsa databases
unsafe impl<T> Send for Parse<T> {}
unsafe impl<T> Sync for Parse<T> {}

// The internal parse result used during parsing
struct InternalParse {
    green_node: GreenNode,
    errors: Vec<String>,
}

fn parse(text: &str) -> InternalParse {
    struct Parser {
        /// input tokens, including whitespace,
        /// in *reverse* order.
        tokens: Vec<(SyntaxKind, String)>,
        /// the in-progress tree.
        builder: GreenNodeBuilder<'static>,
        /// the list of syntax errors we've accumulated
        /// so far.
        errors: Vec<String>,
    }

    impl Parser {
        fn parse_version(&mut self) -> Option<u32> {
            let mut version = None;
            if self.tokens.last() == Some(&(KEY, "version".to_string())) {
                self.builder.start_node(VERSION.into());
                self.bump();
                self.skip_ws();
                if self.current() != Some(EQUALS) {
                    self.builder.start_node(ERROR.into());
                    self.errors.push("expected `=`".to_string());
                    self.bump();
                    self.builder.finish_node();
                } else {
                    self.bump();
                }
                if self.current() != Some(VALUE) {
                    self.builder.start_node(ERROR.into());
                    self.errors
                        .push(format!("expected value, got {:?}", self.current()));
                    self.bump();
                    self.builder.finish_node();
                } else if let Some((_, value)) = self.tokens.last() {
                    let version_str = value;
                    match version_str.parse() {
                        Ok(v) => {
                            version = Some(v);
                            self.bump();
                        }
                        Err(_) => {
                            self.builder.start_node(ERROR.into());
                            self.errors
                                .push(format!("invalid version: {}", version_str));
                            self.bump();
                            self.builder.finish_node();
                        }
                    }
                } else {
                    self.builder.start_node(ERROR.into());
                    self.errors.push("expected version value".to_string());
                    self.builder.finish_node();
                }
                if self.current() != Some(NEWLINE) {
                    self.builder.start_node(ERROR.into());
                    self.errors.push("expected newline".to_string());
                    self.bump();
                    self.builder.finish_node();
                } else {
                    self.bump();
                }
                self.builder.finish_node();
            }
            version
        }

        fn parse_watch_entry(&mut self) -> bool {
            // Skip whitespace, comments, and blank lines between entries
            loop {
                self.skip_ws();
                if self.current() == Some(NEWLINE) {
                    self.bump();
                } else {
                    break;
                }
            }
            if self.current().is_none() {
                return false;
            }
            self.builder.start_node(ENTRY.into());
            self.parse_options_list();
            for i in 0..4 {
                if self.current() == Some(NEWLINE) || self.current().is_none() {
                    break;
                }
                if self.current() == Some(CONTINUATION) {
                    self.bump();
                    self.skip_ws();
                    continue;
                }
                if self.current() != Some(VALUE) && self.current() != Some(KEY) {
                    self.builder.start_node(ERROR.into());
                    self.errors.push(format!(
                        "expected value, got {:?} (i={})",
                        self.current(),
                        i
                    ));
                    if self.current().is_some() {
                        self.bump();
                    }
                    self.builder.finish_node();
                } else {
                    // Wrap each field in its appropriate node
                    match i {
                        0 => {
                            // URL
                            self.builder.start_node(URL.into());
                            self.bump();
                            self.builder.finish_node();
                        }
                        1 => {
                            // Matching pattern
                            self.builder.start_node(MATCHING_PATTERN.into());
                            self.bump();
                            self.builder.finish_node();
                        }
                        2 => {
                            // Version policy
                            self.builder.start_node(VERSION_POLICY.into());
                            self.bump();
                            self.builder.finish_node();
                        }
                        3 => {
                            // Script
                            self.builder.start_node(SCRIPT.into());
                            self.bump();
                            self.builder.finish_node();
                        }
                        _ => {
                            self.bump();
                        }
                    }
                }
                self.skip_ws();
            }
            if self.current() != Some(NEWLINE) && self.current().is_some() {
                self.builder.start_node(ERROR.into());
                self.errors
                    .push(format!("expected newline, not {:?}", self.current()));
                if self.current().is_some() {
                    self.bump();
                }
                self.builder.finish_node();
            } else if self.current().is_some() {
                // Consume the newline if present (but EOF is also okay)
                self.bump();
            }
            self.builder.finish_node();
            true
        }

        fn parse_option(&mut self) -> bool {
            if self.current().is_none() {
                return false;
            }
            while self.current() == Some(CONTINUATION) {
                self.bump();
            }
            if self.current() == Some(WHITESPACE) {
                return false;
            }
            self.builder.start_node(OPTION.into());
            if self.current() != Some(KEY) {
                self.builder.start_node(ERROR.into());
                self.errors.push("expected key".to_string());
                self.bump();
                self.builder.finish_node();
            } else {
                self.bump();
            }
            if self.current() == Some(EQUALS) {
                self.bump();
                if self.current() != Some(VALUE) && self.current() != Some(KEY) {
                    self.builder.start_node(ERROR.into());
                    self.errors
                        .push(format!("expected value, got {:?}", self.current()));
                    self.bump();
                    self.builder.finish_node();
                } else {
                    self.bump();
                }
            } else if self.current() == Some(COMMA) {
            } else {
                self.builder.start_node(ERROR.into());
                self.errors.push("expected `=`".to_string());
                if self.current().is_some() {
                    self.bump();
                }
                self.builder.finish_node();
            }
            self.builder.finish_node();
            true
        }

        fn parse_options_list(&mut self) {
            self.skip_ws();
            if self.tokens.last() == Some(&(KEY, "opts".to_string()))
                || self.tokens.last() == Some(&(KEY, "options".to_string()))
            {
                self.builder.start_node(OPTS_LIST.into());
                self.bump();
                self.skip_ws();
                if self.current() != Some(EQUALS) {
                    self.builder.start_node(ERROR.into());
                    self.errors.push("expected `=`".to_string());
                    if self.current().is_some() {
                        self.bump();
                    }
                    self.builder.finish_node();
                } else {
                    self.bump();
                }
                let quoted = if self.current() == Some(QUOTE) {
                    self.bump();
                    true
                } else {
                    false
                };
                loop {
                    if quoted {
                        if self.current() == Some(QUOTE) {
                            self.bump();
                            break;
                        }
                        self.skip_ws();
                    }
                    if !self.parse_option() {
                        break;
                    }
                    if self.current() == Some(COMMA) {
                        self.builder.start_node(OPTION_SEPARATOR.into());
                        self.bump();
                        self.builder.finish_node();
                    } else if !quoted {
                        break;
                    }
                }
                self.builder.finish_node();
                self.skip_ws();
            }
        }

        fn parse(mut self) -> InternalParse {
            // Make sure that the root node covers all source
            self.builder.start_node(ROOT.into());
            // Skip any leading comments/whitespace/newlines before version
            while self.current() == Some(WHITESPACE)
                || self.current() == Some(CONTINUATION)
                || self.current() == Some(COMMENT)
                || self.current() == Some(NEWLINE)
            {
                self.bump();
            }
            if let Some(_v) = self.parse_version() {
                // Version is stored in the syntax tree, no need to track separately
            }
            // TODO: use version to influence parsing
            loop {
                if !self.parse_watch_entry() {
                    break;
                }
            }
            // Don't forget to eat *trailing* whitespace
            self.skip_ws();
            // Consume any remaining tokens that were not parsed, recording an error.
            // This ensures the CST always covers the full input.
            if self.current().is_some() {
                self.builder.start_node(ERROR.into());
                self.errors
                    .push("unexpected tokens after last entry".to_string());
                while self.current().is_some() {
                    self.bump();
                }
                self.builder.finish_node();
            }
            // Close the root node.
            self.builder.finish_node();

            // Turn the builder into a GreenNode
            InternalParse {
                green_node: self.builder.finish(),
                errors: self.errors,
            }
        }
        /// Advance one token, adding it to the current branch of the tree builder.
        fn bump(&mut self) {
            if let Some((kind, text)) = self.tokens.pop() {
                self.builder.token(kind.into(), text.as_str());
            }
        }
        /// Peek at the first unprocessed token
        fn current(&self) -> Option<SyntaxKind> {
            self.tokens.last().map(|(kind, _)| *kind)
        }
        fn skip_ws(&mut self) {
            while self.current() == Some(WHITESPACE)
                || self.current() == Some(CONTINUATION)
                || self.current() == Some(COMMENT)
            {
                self.bump()
            }
        }
    }

    let mut tokens = lex(text);
    tokens.reverse();
    Parser {
        tokens,
        builder: GreenNodeBuilder::new(),
        errors: Vec::new(),
    }
    .parse()
}

/// To work with the parse results we need a view into the
/// green tree - the Syntax tree.
/// It is also immutable, like a GreenNode,
/// but it contains parent pointers, offsets, and
/// has identity semantics.
type SyntaxNode = rowan::SyntaxNode<Lang>;
#[allow(unused)]
type SyntaxToken = rowan::SyntaxToken<Lang>;
#[allow(unused)]
type SyntaxElement = rowan::NodeOrToken<SyntaxNode, SyntaxToken>;

impl InternalParse {
    fn syntax(&self) -> SyntaxNode {
        SyntaxNode::new_root_mut(self.green_node.clone())
    }

    fn root(&self) -> WatchFile {
        WatchFile::cast(self.syntax()).expect("root node should be a WatchFile")
    }
}

/// Calculate line and column (both 0-indexed) for the given offset in the tree.
/// Column is measured in bytes from the start of the line.
fn line_col_at_offset(node: &SyntaxNode, offset: rowan::TextSize) -> (usize, usize) {
    let root = node.ancestors().last().unwrap_or_else(|| node.clone());
    let mut line = 0;
    let mut last_newline_offset = rowan::TextSize::from(0);

    for element in root.preorder_with_tokens() {
        if let rowan::WalkEvent::Enter(rowan::NodeOrToken::Token(token)) = element {
            if token.text_range().start() >= offset {
                break;
            }

            // Count newlines and track position of last one
            for (idx, _) in token.text().match_indices('\n') {
                line += 1;
                last_newline_offset =
                    token.text_range().start() + rowan::TextSize::from((idx + 1) as u32);
            }
        }
    }

    let column: usize = (offset - last_newline_offset).into();
    (line, column)
}

macro_rules! ast_node {
    ($ast:ident, $kind:ident) => {
        #[derive(Debug, Clone, PartialEq, Eq, Hash)]
        #[repr(transparent)]
        /// A node in the syntax tree for $ast
        pub struct $ast(SyntaxNode);
        impl $ast {
            #[allow(unused)]
            fn cast(node: SyntaxNode) -> Option<Self> {
                if node.kind() == $kind {
                    Some(Self(node))
                } else {
                    None
                }
            }

            /// Get the line number (0-indexed) where this node starts.
            pub fn line(&self) -> usize {
                line_col_at_offset(&self.0, self.0.text_range().start()).0
            }

            /// Get the column number (0-indexed, in bytes) where this node starts.
            pub fn column(&self) -> usize {
                line_col_at_offset(&self.0, self.0.text_range().start()).1
            }

            /// Get both line and column (0-indexed) where this node starts.
            /// Returns (line, column) where column is measured in bytes from the start of the line.
            pub fn line_col(&self) -> (usize, usize) {
                line_col_at_offset(&self.0, self.0.text_range().start())
            }
        }

        impl std::fmt::Display for $ast {
            fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                write!(f, "{}", self.0.text())
            }
        }
    };
}

ast_node!(WatchFile, ROOT);
ast_node!(Version, VERSION);
ast_node!(Entry, ENTRY);
ast_node!(_Option, OPTION);
ast_node!(Url, URL);
ast_node!(MatchingPattern, MATCHING_PATTERN);
ast_node!(VersionPolicyNode, VERSION_POLICY);
ast_node!(ScriptNode, SCRIPT);

// OptionList is manually defined to have a custom Debug impl
#[derive(Clone, PartialEq, Eq, Hash)]
#[repr(transparent)]
/// A node in the syntax tree for OptionList
pub struct OptionList(SyntaxNode);

impl OptionList {
    #[allow(unused)]
    fn cast(node: SyntaxNode) -> Option<Self> {
        if node.kind() == OPTS_LIST {
            Some(Self(node))
        } else {
            None
        }
    }

    /// Get the line number (0-indexed) where this node starts.
    pub fn line(&self) -> usize {
        line_col_at_offset(&self.0, self.0.text_range().start()).0
    }

    /// Get the column number (0-indexed, in bytes) where this node starts.
    pub fn column(&self) -> usize {
        line_col_at_offset(&self.0, self.0.text_range().start()).1
    }

    /// Get both line and column (0-indexed) where this node starts.
    /// Returns (line, column) where column is measured in bytes from the start of the line.
    pub fn line_col(&self) -> (usize, usize) {
        line_col_at_offset(&self.0, self.0.text_range().start())
    }
}

impl std::fmt::Display for OptionList {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}", self.0.text())
    }
}

impl WatchFile {
    /// Access the underlying syntax node
    pub fn syntax(&self) -> &SyntaxNode {
        &self.0
    }

    /// Create a new watch file with specified version
    pub fn new(version: Option<u32>) -> WatchFile {
        let mut builder = GreenNodeBuilder::new();

        builder.start_node(ROOT.into());
        if let Some(version) = version {
            builder.start_node(VERSION.into());
            builder.token(KEY.into(), "version");
            builder.token(EQUALS.into(), "=");
            builder.token(VALUE.into(), version.to_string().as_str());
            builder.token(NEWLINE.into(), "\n");
            builder.finish_node();
        }
        builder.finish_node();
        WatchFile(SyntaxNode::new_root_mut(builder.finish()))
    }

    /// Returns the version AST node of the watch file.
    pub fn version_node(&self) -> Option<Version> {
        self.0.children().find_map(Version::cast)
    }

    /// Returns the version of the watch file.
    pub fn version(&self) -> u32 {
        self.version_node()
            .map(|it| it.version())
            .unwrap_or(DEFAULT_VERSION)
    }

    /// Returns an iterator over all entries in the watch file.
    pub fn entries(&self) -> impl Iterator<Item = Entry> + '_ {
        self.0.children().filter_map(Entry::cast)
    }

    /// Set the version of the watch file.
    pub fn set_version(&mut self, new_version: u32) {
        // Build the new version node
        let mut builder = GreenNodeBuilder::new();
        builder.start_node(VERSION.into());
        builder.token(KEY.into(), "version");
        builder.token(EQUALS.into(), "=");
        builder.token(VALUE.into(), new_version.to_string().as_str());
        builder.token(NEWLINE.into(), "\n");
        builder.finish_node();
        let new_version_green = builder.finish();

        // Create a syntax node (splice_children will detach and reattach it)
        let new_version_node = SyntaxNode::new_root_mut(new_version_green);

        // Find existing version node if any
        let version_pos = self.0.children().position(|child| child.kind() == VERSION);

        if let Some(pos) = version_pos {
            // Replace existing version node
            self.0
                .splice_children(pos..pos + 1, vec![new_version_node.into()]);
        } else {
            // Insert version node at the beginning
            self.0.splice_children(0..0, vec![new_version_node.into()]);
        }
    }

    /// Discover releases for all entries in the watch file (async version)
    ///
    /// Fetches URLs and searches for version matches for all entries.
    /// Requires the 'discover' feature.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// # use debian_watch::WatchFile;
    /// # async fn example() {
    /// let wf: WatchFile = r#"version=4
    /// https://example.com/releases/ .*/v?(\d+\.\d+)\.tar\.gz
    /// "#.parse().unwrap();
    /// let all_releases = wf.uscan(|| "mypackage".to_string()).await.unwrap();
    /// for (entry_idx, releases) in all_releases.iter().enumerate() {
    ///     println!("Entry {}: {} releases found", entry_idx, releases.len());
    /// }
    /// # }
    /// ```
    #[cfg(feature = "discover")]
    pub async fn uscan(
        &self,
        package: impl Fn() -> String + Send + Sync,
    ) -> Result<Vec<Vec<crate::Release>>, Box<dyn std::error::Error>> {
        let mut all_releases = Vec::new();

        for entry in self.entries() {
            let parsed_entry = crate::parse::ParsedEntry::LineBased(entry);
            let releases = parsed_entry.discover(|| package()).await?;
            all_releases.push(releases);
        }

        Ok(all_releases)
    }

    /// Discover releases for all entries in the watch file (blocking version)
    ///
    /// Fetches URLs and searches for version matches for all entries.
    /// Requires both 'discover' and 'blocking' features.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// # use debian_watch::WatchFile;
    /// let wf: WatchFile = r#"version=4
    /// https://example.com/releases/ .*/v?(\d+\.\d+)\.tar\.gz
    /// "#.parse().unwrap();
    /// let all_releases = wf.uscan_blocking(|| "mypackage".to_string()).unwrap();
    /// for (entry_idx, releases) in all_releases.iter().enumerate() {
    ///     println!("Entry {}: {} releases found", entry_idx, releases.len());
    /// }
    /// ```
    #[cfg(all(feature = "discover", feature = "blocking"))]
    pub fn uscan_blocking(
        &self,
        package: impl Fn() -> String,
    ) -> Result<Vec<Vec<crate::Release>>, Box<dyn std::error::Error>> {
        let mut all_releases = Vec::new();

        for entry in self.entries() {
            let parsed_entry = crate::parse::ParsedEntry::LineBased(entry);
            let releases = parsed_entry.discover_blocking(|| package())?;
            all_releases.push(releases);
        }

        Ok(all_releases)
    }

    /// Add an entry to the watch file.
    ///
    /// Appends a new entry to the end of the watch file.
    ///
    /// # Examples
    ///
    /// ```
    /// use debian_watch::linebased::{WatchFile, EntryBuilder};
    ///
    /// let mut wf = WatchFile::new(Some(4));
    ///
    /// // Add an entry using EntryBuilder
    /// let entry = EntryBuilder::new("https://github.com/example/tags")
    ///     .matching_pattern(".*/v?(\\d\\S+)\\.tar\\.gz")
    ///     .build();
    /// wf.add_entry(entry);
    ///
    /// // Or use the builder pattern directly
    /// wf.add_entry(
    ///     EntryBuilder::new("https://example.com/releases")
    ///         .matching_pattern(".*/(\\d+\\.\\d+)\\.tar\\.gz")
    ///         .opt("compression", "xz")
    ///         .version_policy("debian")
    ///         .build()
    /// );
    /// ```
    pub fn add_entry(&mut self, entry: Entry) -> Entry {
        // Find the position to insert (after the last entry or after version)
        let insert_pos = self.0.children_with_tokens().count();

        // Detach the entry node from its current parent and get its green node
        let entry_green = entry.0.green().into_owned();
        let new_entry_node = SyntaxNode::new_root_mut(entry_green);

        // Insert the entry at the end
        self.0
            .splice_children(insert_pos..insert_pos, vec![new_entry_node.into()]);

        // Get the entry we just inserted by indexing directly to the position
        Entry::cast(
            self.0
                .children()
                .nth(insert_pos)
                .expect("Entry was just inserted"),
        )
        .expect("Inserted node should be an Entry")
    }

    /// Read a watch file from a Read object.
    pub fn from_reader<R: std::io::Read>(reader: R) -> Result<WatchFile, ParseError> {
        let mut buf_reader = std::io::BufReader::new(reader);
        let mut content = String::new();
        buf_reader
            .read_to_string(&mut content)
            .map_err(|e| ParseError(vec![e.to_string()]))?;
        content.parse()
    }

    /// Read a watch file from a Read object, allowing syntax errors.
    pub fn from_reader_relaxed<R: std::io::Read>(mut r: R) -> Result<Self, std::io::Error> {
        let mut content = String::new();
        r.read_to_string(&mut content)?;
        let parsed = parse(&content);
        Ok(parsed.root())
    }

    /// Parse a debian watch file from a string, allowing syntax errors.
    pub fn from_str_relaxed(s: &str) -> Self {
        let parsed = parse(s);
        parsed.root()
    }
}

impl FromStr for WatchFile {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let parsed = parse(s);
        if parsed.errors.is_empty() {
            Ok(parsed.root())
        } else {
            Err(ParseError(parsed.errors))
        }
    }
}

/// Parse a watch file and return a thread-safe parse result.
/// This can be stored in incremental computation systems like Salsa.
pub fn parse_watch_file(text: &str) -> Parse<WatchFile> {
    let parsed = parse(text);
    Parse::new(parsed.green_node, parsed.errors)
}

impl Version {
    /// Returns the version of the watch file.
    pub fn version(&self) -> u32 {
        self.0
            .children_with_tokens()
            .find_map(|it| match it {
                SyntaxElement::Token(token) => {
                    if token.kind() == VALUE {
                        token.text().parse().ok()
                    } else {
                        None
                    }
                }
                _ => None,
            })
            .unwrap_or(DEFAULT_VERSION)
    }
}

/// Builder for creating new watchfile entries.
///
/// Provides a fluent API for constructing entries with various components.
///
/// # Examples
///
/// ```
/// use debian_watch::linebased::EntryBuilder;
///
/// // Minimal entry with just URL and pattern
/// let entry = EntryBuilder::new("https://github.com/example/tags")
///     .matching_pattern(".*/v?(\\d\\S+)\\.tar\\.gz")
///     .build();
///
/// // Entry with options
/// let entry = EntryBuilder::new("https://github.com/example/tags")
///     .matching_pattern(".*/v?(\\d\\S+)\\.tar\\.gz")
///     .opt("compression", "xz")
///     .flag("repack")
///     .version_policy("debian")
///     .script("uupdate")
///     .build();
/// ```
#[derive(Debug, Clone, Default)]
pub struct EntryBuilder {
    url: Option<String>,
    matching_pattern: Option<String>,
    version_policy: Option<String>,
    script: Option<String>,
    opts: std::collections::HashMap<String, String>,
}

impl EntryBuilder {
    /// Create a new entry builder with the specified URL.
    pub fn new(url: impl Into<String>) -> Self {
        EntryBuilder {
            url: Some(url.into()),
            matching_pattern: None,
            version_policy: None,
            script: None,
            opts: std::collections::HashMap::new(),
        }
    }

    /// Set the matching pattern for the entry.
    pub fn matching_pattern(mut self, pattern: impl Into<String>) -> Self {
        self.matching_pattern = Some(pattern.into());
        self
    }

    /// Set the version policy for the entry.
    pub fn version_policy(mut self, policy: impl Into<String>) -> Self {
        self.version_policy = Some(policy.into());
        self
    }

    /// Set the script for the entry.
    pub fn script(mut self, script: impl Into<String>) -> Self {
        self.script = Some(script.into());
        self
    }

    /// Add an option to the entry.
    pub fn opt(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.opts.insert(key.into(), value.into());
        self
    }

    /// Add a boolean flag option to the entry.
    ///
    /// Boolean options like "repack", "bare", "decompress" don't have values.
    pub fn flag(mut self, key: impl Into<String>) -> Self {
        self.opts.insert(key.into(), String::new());
        self
    }

    /// Build the entry.
    ///
    /// # Panics
    ///
    /// Panics if no URL was provided.
    pub fn build(self) -> Entry {
        let url = self.url.expect("URL is required for entry");

        let mut builder = GreenNodeBuilder::new();

        builder.start_node(ENTRY.into());

        // Add options list if provided
        if !self.opts.is_empty() {
            builder.start_node(OPTS_LIST.into());
            builder.token(KEY.into(), "opts");
            builder.token(EQUALS.into(), "=");

            let mut first = true;
            for (key, value) in self.opts.iter() {
                if !first {
                    builder.token(COMMA.into(), ",");
                }
                first = false;

                builder.start_node(OPTION.into());
                builder.token(KEY.into(), key);
                if !value.is_empty() {
                    builder.token(EQUALS.into(), "=");
                    builder.token(VALUE.into(), value);
                }
                builder.finish_node();
            }

            builder.finish_node();
            builder.token(WHITESPACE.into(), " ");
        }

        // Add URL (required)
        builder.start_node(URL.into());
        builder.token(VALUE.into(), &url);
        builder.finish_node();

        // Add matching pattern if provided
        if let Some(pattern) = self.matching_pattern {
            builder.token(WHITESPACE.into(), " ");
            builder.start_node(MATCHING_PATTERN.into());
            builder.token(VALUE.into(), &pattern);
            builder.finish_node();
        }

        // Add version policy if provided
        if let Some(policy) = self.version_policy {
            builder.token(WHITESPACE.into(), " ");
            builder.start_node(VERSION_POLICY.into());
            builder.token(VALUE.into(), &policy);
            builder.finish_node();
        }

        // Add script if provided
        if let Some(script_val) = self.script {
            builder.token(WHITESPACE.into(), " ");
            builder.start_node(SCRIPT.into());
            builder.token(VALUE.into(), &script_val);
            builder.finish_node();
        }

        builder.token(NEWLINE.into(), "\n");
        builder.finish_node();

        Entry(SyntaxNode::new_root_mut(builder.finish()))
    }
}

impl Entry {
    /// Access the underlying syntax node.
    pub fn syntax(&self) -> &SyntaxNode {
        &self.0
    }

    /// Create a new entry builder.
    ///
    /// This is a convenience method that returns an `EntryBuilder`.
    ///
    /// # Examples
    ///
    /// ```
    /// use debian_watch::linebased::Entry;
    ///
    /// let entry = Entry::builder("https://github.com/example/tags")
    ///     .matching_pattern(".*/v?(\\d\\S+)\\.tar\\.gz")
    ///     .build();
    /// ```
    pub fn builder(url: impl Into<String>) -> EntryBuilder {
        EntryBuilder::new(url)
    }

    /// List of options
    pub fn option_list(&self) -> Option<OptionList> {
        self.0.children().find_map(OptionList::cast)
    }

    /// Get the value of an option
    pub fn get_option(&self, key: &str) -> Option<String> {
        self.option_list().and_then(|ol| ol.get_option(key))
    }

    /// Check if an option is set
    pub fn has_option(&self, key: &str) -> bool {
        self.option_list().is_some_and(|ol| ol.has_option(key))
    }

    /// The name of the secondary source tarball
    pub fn component(&self) -> Option<String> {
        self.get_option("component")
    }

    /// Component type
    pub fn ctype(&self) -> Result<Option<ComponentType>, ()> {
        self.try_ctype().map_err(|_| ())
    }

    /// Component type with detailed error information
    pub fn try_ctype(&self) -> Result<Option<ComponentType>, crate::types::ParseError> {
        self.get_option("ctype").map(|s| s.parse()).transpose()
    }

    /// Compression method
    pub fn compression(&self) -> Result<Option<Compression>, ()> {
        self.try_compression().map_err(|_| ())
    }

    /// Compression method with detailed error information
    pub fn try_compression(&self) -> Result<Option<Compression>, crate::types::ParseError> {
        self.get_option("compression")
            .map(|s| s.parse())
            .transpose()
    }

    /// Repack the tarball
    pub fn repack(&self) -> bool {
        self.has_option("repack")
    }

    /// Repack suffix
    pub fn repacksuffix(&self) -> Option<String> {
        self.get_option("repacksuffix")
    }

    /// Retrieve the mode of the watch file entry.
    pub fn mode(&self) -> Result<Mode, ()> {
        self.try_mode().map_err(|_| ())
    }

    /// Retrieve the mode of the watch file entry with detailed error information.
    pub fn try_mode(&self) -> Result<Mode, crate::types::ParseError> {
        Ok(self
            .get_option("mode")
            .map(|s| s.parse())
            .transpose()?
            .unwrap_or_default())
    }

    /// Return the git pretty mode
    pub fn pretty(&self) -> Result<Pretty, ()> {
        self.try_pretty().map_err(|_| ())
    }

    /// Return the git pretty mode with detailed error information
    pub fn try_pretty(&self) -> Result<Pretty, crate::types::ParseError> {
        Ok(self
            .get_option("pretty")
            .map(|s| s.parse())
            .transpose()?
            .unwrap_or_default())
    }

    /// Set the date string used by the pretty option to an arbitrary format as an optional
    /// opts argument when the matching-pattern is HEAD or heads/branch for git mode.
    pub fn date(&self) -> String {
        self.get_option("date").unwrap_or_else(|| "%Y%m%d".into())
    }

    /// Return the git export mode
    pub fn gitexport(&self) -> Result<GitExport, ()> {
        self.try_gitexport().map_err(|_| ())
    }

    /// Return the git export mode with detailed error information
    pub fn try_gitexport(&self) -> Result<GitExport, crate::types::ParseError> {
        Ok(self
            .get_option("gitexport")
            .map(|s| s.parse())
            .transpose()?
            .unwrap_or_default())
    }

    /// Return the git mode
    pub fn gitmode(&self) -> Result<GitMode, ()> {
        self.try_gitmode().map_err(|_| ())
    }

    /// Return the git mode with detailed error information
    pub fn try_gitmode(&self) -> Result<GitMode, crate::types::ParseError> {
        Ok(self
            .get_option("gitmode")
            .map(|s| s.parse())
            .transpose()?
            .unwrap_or_default())
    }

    /// Return the pgp mode
    pub fn pgpmode(&self) -> Result<PgpMode, ()> {
        self.try_pgpmode().map_err(|_| ())
    }

    /// Return the pgp mode with detailed error information
    pub fn try_pgpmode(&self) -> Result<PgpMode, crate::types::ParseError> {
        Ok(self
            .get_option("pgpmode")
            .map(|s| s.parse())
            .transpose()?
            .unwrap_or_default())
    }

    /// Return the search mode
    pub fn searchmode(&self) -> Result<SearchMode, ()> {
        self.try_searchmode().map_err(|_| ())
    }

    /// Return the search mode with detailed error information
    pub fn try_searchmode(&self) -> Result<SearchMode, crate::types::ParseError> {
        Ok(self
            .get_option("searchmode")
            .map(|s| s.parse())
            .transpose()?
            .unwrap_or_default())
    }

    /// Return the decompression mode
    pub fn decompress(&self) -> bool {
        self.has_option("decompress")
    }

    /// Whether to disable all site specific special case code such as URL director uses and page
    /// content alterations.
    pub fn bare(&self) -> bool {
        self.has_option("bare")
    }

    /// Set the user-agent string used to contact the HTTP(S) server as user-agent-string. (persistent)
    pub fn user_agent(&self) -> Option<String> {
        self.get_option("user-agent")
    }

    /// Use PASV mode for the FTP connection.
    pub fn passive(&self) -> Option<bool> {
        if self.has_option("passive") || self.has_option("pasv") {
            Some(true)
        } else if self.has_option("active") || self.has_option("nopasv") {
            Some(false)
        } else {
            None
        }
    }

    /// Add the extra options to use with the unzip command, such as -a, -aa, and -b, when executed
    /// by mk-origtargz.
    pub fn unzipoptions(&self) -> Option<String> {
        self.get_option("unzipopt")
    }

    /// Normalize the downloaded web page string.
    pub fn dversionmangle(&self) -> Option<String> {
        self.get_option("dversionmangle")
            .or_else(|| self.get_option("versionmangle"))
    }

    /// Normalize the directory path string matching the regex in a set of parentheses of
    /// http://URL as the sortable version index string.  This is used
    /// as the directory path sorting index only.
    pub fn dirversionmangle(&self) -> Option<String> {
        self.get_option("dirversionmangle")
    }

    /// Normalize the downloaded web page string.
    pub fn pagemangle(&self) -> Option<String> {
        self.get_option("pagemangle")
    }

    /// Normalize the candidate upstream version strings extracted from hrefs in the
    /// source of the web page.  This is used as the version sorting index when selecting the
    /// latest upstream version.
    pub fn uversionmangle(&self) -> Option<String> {
        self.get_option("uversionmangle")
            .or_else(|| self.get_option("versionmangle"))
    }

    /// Syntactic shorthand for uversionmangle=rules, dversionmangle=rules
    pub fn versionmangle(&self) -> Option<String> {
        self.get_option("versionmangle")
    }

    /// Convert the selected upstream tarball href string from the percent-encoded hexadecimal
    /// string to the decoded normal URL  string  for  obfuscated
    /// web sites.  Only percent-encoding is available and it is decoded with
    /// s/%([A-Fa-f\d]{2})/chr hex $1/eg.
    pub fn hrefdecode(&self) -> bool {
        self.get_option("hrefdecode").is_some()
    }

    /// Convert the selected upstream tarball href string into the accessible URL for obfuscated
    /// web sites.  This is run after hrefdecode.
    pub fn downloadurlmangle(&self) -> Option<String> {
        self.get_option("downloadurlmangle")
    }

    /// Generate the upstream tarball filename from the selected href string if matching-pattern
    /// can extract the latest upstream version <uversion> from the  selected  href  string.
    /// Otherwise, generate the upstream tarball filename from its full URL string and set the
    /// missing <uversion> from the generated upstream tarball filename.
    ///
    /// Without this option, the default upstream tarball filename is generated by taking the last
    /// component of the URL and  removing everything  after any '?' or '#'.
    pub fn filenamemangle(&self) -> Option<String> {
        self.get_option("filenamemangle")
    }

    /// Generate the candidate upstream signature file URL string from the upstream tarball URL.
    pub fn pgpsigurlmangle(&self) -> Option<String> {
        self.get_option("pgpsigurlmangle")
    }

    /// Generate the version string <oversion> of the source tarball <spkg>_<oversion>.orig.tar.gz
    /// from <uversion>.  This should be used to add a suffix such as +dfsg to a MUT package.
    pub fn oversionmangle(&self) -> Option<String> {
        self.get_option("oversionmangle")
    }

    /// Apply uversionmangle to a version string
    ///
    /// # Examples
    ///
    /// ```
    /// # use debian_watch::linebased::WatchFile;
    /// let wf: WatchFile = r#"version=4
    /// opts=uversionmangle=s/\+ds// https://example.com/ .*
    /// "#.parse().unwrap();
    /// let entry = wf.entries().next().unwrap();
    /// assert_eq!(entry.apply_uversionmangle("1.0+ds").unwrap(), "1.0");
    /// ```
    pub fn apply_uversionmangle(
        &self,
        version: &str,
    ) -> Result<String, crate::mangle::MangleError> {
        if let Some(vm) = self.uversionmangle() {
            crate::mangle::apply_mangle(&vm, version)
        } else {
            Ok(version.to_string())
        }
    }

    /// Apply dversionmangle to a version string
    ///
    /// # Examples
    ///
    /// ```
    /// # use debian_watch::linebased::WatchFile;
    /// let wf: WatchFile = r#"version=4
    /// opts=dversionmangle=s/\+dfsg$// https://example.com/ .*
    /// "#.parse().unwrap();
    /// let entry = wf.entries().next().unwrap();
    /// assert_eq!(entry.apply_dversionmangle("1.0+dfsg").unwrap(), "1.0");
    /// ```
    pub fn apply_dversionmangle(
        &self,
        version: &str,
    ) -> Result<String, crate::mangle::MangleError> {
        if let Some(vm) = self.dversionmangle() {
            crate::mangle::apply_mangle(&vm, version)
        } else {
            Ok(version.to_string())
        }
    }

    /// Apply oversionmangle to a version string
    ///
    /// # Examples
    ///
    /// ```
    /// # use debian_watch::linebased::WatchFile;
    /// let wf: WatchFile = r#"version=4
    /// opts=oversionmangle=s/$/-1/ https://example.com/ .*
    /// "#.parse().unwrap();
    /// let entry = wf.entries().next().unwrap();
    /// assert_eq!(entry.apply_oversionmangle("1.0").unwrap(), "1.0-1");
    /// ```
    pub fn apply_oversionmangle(
        &self,
        version: &str,
    ) -> Result<String, crate::mangle::MangleError> {
        if let Some(vm) = self.oversionmangle() {
            crate::mangle::apply_mangle(&vm, version)
        } else {
            Ok(version.to_string())
        }
    }

    /// Apply dirversionmangle to a directory path string
    ///
    /// # Examples
    ///
    /// ```
    /// # use debian_watch::linebased::WatchFile;
    /// let wf: WatchFile = r#"version=4
    /// opts=dirversionmangle=s/v(\d)/$1/ https://example.com/ .*
    /// "#.parse().unwrap();
    /// let entry = wf.entries().next().unwrap();
    /// assert_eq!(entry.apply_dirversionmangle("v1.0").unwrap(), "1.0");
    /// ```
    pub fn apply_dirversionmangle(
        &self,
        version: &str,
    ) -> Result<String, crate::mangle::MangleError> {
        if let Some(vm) = self.dirversionmangle() {
            crate::mangle::apply_mangle(&vm, version)
        } else {
            Ok(version.to_string())
        }
    }

    /// Apply filenamemangle to a URL or filename string
    ///
    /// # Examples
    ///
    /// ```
    /// # use debian_watch::linebased::WatchFile;
    /// let wf: WatchFile = r#"version=4
    /// opts=filenamemangle=s/.+\/v?(\d\S+)\.tar\.gz/mypackage-$1.tar.gz/ https://example.com/ .*
    /// "#.parse().unwrap();
    /// let entry = wf.entries().next().unwrap();
    /// assert_eq!(
    ///     entry.apply_filenamemangle("https://example.com/v1.0.tar.gz").unwrap(),
    ///     "mypackage-1.0.tar.gz"
    /// );
    /// ```
    pub fn apply_filenamemangle(&self, url: &str) -> Result<String, crate::mangle::MangleError> {
        if let Some(vm) = self.filenamemangle() {
            crate::mangle::apply_mangle(&vm, url)
        } else {
            Ok(url.to_string())
        }
    }

    /// Apply pagemangle to page content bytes
    ///
    /// # Examples
    ///
    /// ```
    /// # use debian_watch::linebased::WatchFile;
    /// let wf: WatchFile = r#"version=4
    /// opts=pagemangle=s/&amp;/&/g https://example.com/ .*
    /// "#.parse().unwrap();
    /// let entry = wf.entries().next().unwrap();
    /// assert_eq!(
    ///     entry.apply_pagemangle(b"foo &amp; bar").unwrap(),
    ///     b"foo & bar"
    /// );
    /// ```
    pub fn apply_pagemangle(&self, page: &[u8]) -> Result<Vec<u8>, crate::mangle::MangleError> {
        if let Some(vm) = self.pagemangle() {
            let page_str = String::from_utf8_lossy(page);
            let mangled = crate::mangle::apply_mangle(&vm, &page_str)?;
            Ok(mangled.into_bytes())
        } else {
            Ok(page.to_vec())
        }
    }

    /// Apply downloadurlmangle to a URL string
    ///
    /// # Examples
    ///
    /// ```
    /// # use debian_watch::linebased::WatchFile;
    /// let wf: WatchFile = r#"version=4
    /// opts=downloadurlmangle=s|/archive/|/download/| https://example.com/ .*
    /// "#.parse().unwrap();
    /// let entry = wf.entries().next().unwrap();
    /// assert_eq!(
    ///     entry.apply_downloadurlmangle("https://example.com/archive/file.tar.gz").unwrap(),
    ///     "https://example.com/download/file.tar.gz"
    /// );
    /// ```
    pub fn apply_downloadurlmangle(&self, url: &str) -> Result<String, crate::mangle::MangleError> {
        if let Some(vm) = self.downloadurlmangle() {
            crate::mangle::apply_mangle(&vm, url)
        } else {
            Ok(url.to_string())
        }
    }

    /// Returns options set
    pub fn opts(&self) -> std::collections::HashMap<String, String> {
        let mut options = std::collections::HashMap::new();

        if let Some(ol) = self.option_list() {
            for opt in ol.options() {
                let key = opt.key();
                let value = opt.value();
                if let (Some(key), Some(value)) = (key, value) {
                    options.insert(key.to_string(), value.to_string());
                }
            }
        }

        options
    }

    fn items(&self) -> impl Iterator<Item = String> + '_ {
        self.0.children_with_tokens().filter_map(|it| match it {
            SyntaxElement::Token(token) => {
                if token.kind() == VALUE || token.kind() == KEY {
                    Some(token.text().to_string())
                } else {
                    None
                }
            }
            SyntaxElement::Node(node) => {
                // Extract values from entry field nodes
                match node.kind() {
                    URL => Url::cast(node).map(|n| n.url()),
                    MATCHING_PATTERN => MatchingPattern::cast(node).map(|n| n.pattern()),
                    VERSION_POLICY => VersionPolicyNode::cast(node).map(|n| n.policy()),
                    SCRIPT => ScriptNode::cast(node).map(|n| n.script()),
                    _ => None,
                }
            }
        })
    }

    /// Returns the URL AST node of the entry.
    pub fn url_node(&self) -> Option<Url> {
        self.0.children().find_map(Url::cast)
    }

    /// Returns the URL of the entry.
    pub fn url(&self) -> String {
        self.url_node().map(|it| it.url()).unwrap_or_else(|| {
            // Fallback for entries without URL node (shouldn't happen with new parser)
            self.items().next().unwrap()
        })
    }

    /// Returns the matching pattern AST node of the entry.
    pub fn matching_pattern_node(&self) -> Option<MatchingPattern> {
        self.0.children().find_map(MatchingPattern::cast)
    }

    /// Returns the matching pattern of the entry.
    pub fn matching_pattern(&self) -> Option<String> {
        self.matching_pattern_node()
            .map(|it| it.pattern())
            .or_else(|| {
                // Fallback for entries without MATCHING_PATTERN node
                self.items().nth(1)
            })
    }

    /// Returns the version policy AST node of the entry.
    pub fn version_node(&self) -> Option<VersionPolicyNode> {
        self.0.children().find_map(VersionPolicyNode::cast)
    }

    /// Returns the version policy
    pub fn version(&self) -> Result<Option<crate::VersionPolicy>, String> {
        self.version_node()
            .map(|it| it.policy().parse())
            .transpose()
            .map_err(|e: crate::types::ParseError| e.to_string())
            .or_else(|_e| {
                // Fallback for entries without VERSION_POLICY node
                self.items()
                    .nth(2)
                    .map(|it| it.parse())
                    .transpose()
                    .map_err(|e: crate::types::ParseError| e.to_string())
            })
    }

    /// Returns the script AST node of the entry.
    pub fn script_node(&self) -> Option<ScriptNode> {
        self.0.children().find_map(ScriptNode::cast)
    }

    /// Returns the script of the entry.
    pub fn script(&self) -> Option<String> {
        self.script_node().map(|it| it.script()).or_else(|| {
            // Fallback for entries without SCRIPT node
            self.items().nth(3)
        })
    }

    /// Replace all substitutions and return the resulting URL.
    pub fn format_url(
        &self,
        package: impl FnOnce() -> String,
        component: impl FnOnce() -> String,
    ) -> url::Url {
        crate::subst::subst(self.url().as_str(), package, component)
            .parse()
            .unwrap()
    }

    /// Set the URL of the entry.
    pub fn set_url(&mut self, new_url: &str) {
        // Build the new URL node
        let mut builder = GreenNodeBuilder::new();
        builder.start_node(URL.into());
        builder.token(VALUE.into(), new_url);
        builder.finish_node();
        let new_url_green = builder.finish();

        // Create a syntax node (splice_children will detach and reattach it)
        let new_url_node = SyntaxNode::new_root_mut(new_url_green);

        // Find existing URL node position (need to use children_with_tokens for correct indexing)
        let url_pos = self
            .0
            .children_with_tokens()
            .position(|child| matches!(child, SyntaxElement::Node(node) if node.kind() == URL));

        if let Some(pos) = url_pos {
            // Replace existing URL node
            self.0
                .splice_children(pos..pos + 1, vec![new_url_node.into()]);
        }
    }

    /// Set the matching pattern of the entry.
    ///
    /// TODO: This currently only replaces an existing matching pattern.
    /// If the entry doesn't have a matching pattern, this method does nothing.
    /// Future implementation should insert the node at the correct position.
    pub fn set_matching_pattern(&mut self, new_pattern: &str) {
        // Build the new MATCHING_PATTERN node
        let mut builder = GreenNodeBuilder::new();
        builder.start_node(MATCHING_PATTERN.into());
        builder.token(VALUE.into(), new_pattern);
        builder.finish_node();
        let new_pattern_green = builder.finish();

        // Create a syntax node (splice_children will detach and reattach it)
        let new_pattern_node = SyntaxNode::new_root_mut(new_pattern_green);

        // Find existing MATCHING_PATTERN node position
        let pattern_pos = self.0.children_with_tokens().position(
            |child| matches!(child, SyntaxElement::Node(node) if node.kind() == MATCHING_PATTERN),
        );

        if let Some(pos) = pattern_pos {
            // Replace existing MATCHING_PATTERN node
            self.0
                .splice_children(pos..pos + 1, vec![new_pattern_node.into()]);
        }
        // TODO: else insert new node after URL
    }

    /// Set the version policy of the entry.
    ///
    /// TODO: This currently only replaces an existing version policy.
    /// If the entry doesn't have a version policy, this method does nothing.
    /// Future implementation should insert the node at the correct position.
    pub fn set_version_policy(&mut self, new_policy: &str) {
        // Build the new VERSION_POLICY node
        let mut builder = GreenNodeBuilder::new();
        builder.start_node(VERSION_POLICY.into());
        // Version policy can be KEY (e.g., "debian") or VALUE
        builder.token(VALUE.into(), new_policy);
        builder.finish_node();
        let new_policy_green = builder.finish();

        // Create a syntax node (splice_children will detach and reattach it)
        let new_policy_node = SyntaxNode::new_root_mut(new_policy_green);

        // Find existing VERSION_POLICY node position
        let policy_pos = self.0.children_with_tokens().position(
            |child| matches!(child, SyntaxElement::Node(node) if node.kind() == VERSION_POLICY),
        );

        if let Some(pos) = policy_pos {
            // Replace existing VERSION_POLICY node
            self.0
                .splice_children(pos..pos + 1, vec![new_policy_node.into()]);
        }
        // TODO: else insert new node after MATCHING_PATTERN (or URL if no pattern)
    }

    /// Set the script of the entry.
    ///
    /// TODO: This currently only replaces an existing script.
    /// If the entry doesn't have a script, this method does nothing.
    /// Future implementation should insert the node at the correct position.
    pub fn set_script(&mut self, new_script: &str) {
        // Build the new SCRIPT node
        let mut builder = GreenNodeBuilder::new();
        builder.start_node(SCRIPT.into());
        // Script can be KEY (e.g., "uupdate") or VALUE
        builder.token(VALUE.into(), new_script);
        builder.finish_node();
        let new_script_green = builder.finish();

        // Create a syntax node (splice_children will detach and reattach it)
        let new_script_node = SyntaxNode::new_root_mut(new_script_green);

        // Find existing SCRIPT node position
        let script_pos = self
            .0
            .children_with_tokens()
            .position(|child| matches!(child, SyntaxElement::Node(node) if node.kind() == SCRIPT));

        if let Some(pos) = script_pos {
            // Replace existing SCRIPT node
            self.0
                .splice_children(pos..pos + 1, vec![new_script_node.into()]);
        }
        // TODO: else insert new node after VERSION_POLICY (or MATCHING_PATTERN/URL if no policy)
    }

    /// Set or update an option value using a WatchOption enum.
    ///
    /// If the option already exists, it will be updated with the new value.
    /// If the option doesn't exist, it will be added to the options list.
    /// If there's no options list, one will be created.
    pub fn set_option(&mut self, option: crate::types::WatchOption) {
        let key = watch_option_to_key(&option);
        let value = watch_option_to_value(&option);
        self.set_opt(key, &value);
    }

    /// Set or update an option value using string key and value (for backward compatibility).
    ///
    /// If the option already exists, it will be updated with the new value.
    /// If the option doesn't exist, it will be added to the options list.
    /// If there's no options list, one will be created.
    pub fn set_opt(&mut self, key: &str, value: &str) {
        // Find the OPTS_LIST position in Entry
        let opts_pos = self.0.children_with_tokens().position(
            |child| matches!(child, SyntaxElement::Node(node) if node.kind() == OPTS_LIST),
        );

        if let Some(_opts_idx) = opts_pos {
            if let Some(mut ol) = self.option_list() {
                // Find if the option already exists
                if let Some(mut opt) = ol.find_option(key) {
                    // Update the existing option's value
                    opt.set_value(value);
                    // Mutations should propagate automatically - no need to replace
                } else {
                    // Add new option
                    ol.add_option(key, value);
                    // Mutations should propagate automatically - no need to replace
                }
            }
        } else {
            // Create a new options list
            let mut builder = GreenNodeBuilder::new();
            builder.start_node(OPTS_LIST.into());
            builder.token(KEY.into(), "opts");
            builder.token(EQUALS.into(), "=");
            builder.start_node(OPTION.into());
            builder.token(KEY.into(), key);
            builder.token(EQUALS.into(), "=");
            builder.token(VALUE.into(), value);
            builder.finish_node();
            builder.finish_node();
            let new_opts_green = builder.finish();
            let new_opts_node = SyntaxNode::new_root_mut(new_opts_green);

            // Find position to insert (before URL if it exists, otherwise at start)
            let url_pos = self
                .0
                .children_with_tokens()
                .position(|child| matches!(child, SyntaxElement::Node(node) if node.kind() == URL));

            if let Some(url_idx) = url_pos {
                // Insert options list and a space before the URL
                // Build a parent node containing both space and whitespace to extract from
                let mut combined_builder = GreenNodeBuilder::new();
                combined_builder.start_node(ROOT.into()); // Temporary parent
                combined_builder.token(WHITESPACE.into(), " ");
                combined_builder.finish_node();
                let temp_green = combined_builder.finish();
                let temp_root = SyntaxNode::new_root_mut(temp_green);
                let space_element = temp_root.children_with_tokens().next().unwrap();

                self.0
                    .splice_children(url_idx..url_idx, vec![new_opts_node.into(), space_element]);
            } else {
                self.0.splice_children(0..0, vec![new_opts_node.into()]);
            }
        }
    }

    /// Delete an option using a WatchOption enum.
    ///
    /// Removes the option from the options list.
    /// If the option doesn't exist, this method does nothing.
    /// If deleting the option results in an empty options list, the entire
    /// opts= declaration is removed.
    pub fn del_opt(&mut self, option: crate::types::WatchOption) {
        let key = watch_option_to_key(&option);
        if let Some(mut ol) = self.option_list() {
            let option_count = ol.0.children().filter(|n| n.kind() == OPTION).count();

            if option_count == 1 && ol.has_option(key) {
                // This is the last option, remove the entire OPTS_LIST from Entry
                let opts_pos = self.0.children().position(|node| node.kind() == OPTS_LIST);

                if let Some(opts_idx) = opts_pos {
                    // Remove the OPTS_LIST
                    self.0.splice_children(opts_idx..opts_idx + 1, vec![]);

                    // Remove any leading whitespace/continuation that was after the OPTS_LIST
                    while self.0.children_with_tokens().next().is_some_and(|e| {
                        matches!(
                            e,
                            SyntaxElement::Token(t) if t.kind() == WHITESPACE || t.kind() == CONTINUATION
                        )
                    }) {
                        self.0.splice_children(0..1, vec![]);
                    }
                }
            } else {
                // Defer to OptionList to remove the option
                ol.remove_option(key);
            }
        }
    }

    /// Delete an option using a string key (for backward compatibility).
    ///
    /// Removes the option with the specified key from the options list.
    /// If the option doesn't exist, this method does nothing.
    /// If deleting the option results in an empty options list, the entire
    /// opts= declaration is removed.
    pub fn del_opt_str(&mut self, key: &str) {
        if let Some(mut ol) = self.option_list() {
            let option_count = ol.0.children().filter(|n| n.kind() == OPTION).count();

            if option_count == 1 && ol.has_option(key) {
                // This is the last option, remove the entire OPTS_LIST from Entry
                let opts_pos = self.0.children().position(|node| node.kind() == OPTS_LIST);

                if let Some(opts_idx) = opts_pos {
                    // Remove the OPTS_LIST
                    self.0.splice_children(opts_idx..opts_idx + 1, vec![]);

                    // Remove any leading whitespace/continuation that was after the OPTS_LIST
                    while self.0.children_with_tokens().next().is_some_and(|e| {
                        matches!(
                            e,
                            SyntaxElement::Token(t) if t.kind() == WHITESPACE || t.kind() == CONTINUATION
                        )
                    }) {
                        self.0.splice_children(0..1, vec![]);
                    }
                }
            } else {
                // Defer to OptionList to remove the option
                ol.remove_option(key);
            }
        }
    }
}

impl std::fmt::Debug for OptionList {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("OptionList")
            .field("text", &self.0.text().to_string())
            .finish()
    }
}

impl OptionList {
    /// Returns an iterator over all option nodes in the options list.
    pub fn options(&self) -> impl Iterator<Item = _Option> + '_ {
        self.0.children().filter_map(_Option::cast)
    }

    /// Find an option node by key.
    pub fn find_option(&self, key: &str) -> Option<_Option> {
        self.options().find(|opt| opt.key().as_deref() == Some(key))
    }

    /// Check if an option with the given key exists
    pub fn has_option(&self, key: &str) -> bool {
        self.options().any(|it| it.key().as_deref() == Some(key))
    }

    /// Returns an iterator over all options as (key, value) pairs.
    /// This is a convenience method for code that needs key-value tuples (used for conversion to deb822 format).
    #[cfg(feature = "deb822")]
    pub(crate) fn iter_key_values(&self) -> impl Iterator<Item = (String, String)> + '_ {
        self.options().filter_map(|opt| {
            if let (Some(key), Some(value)) = (opt.key(), opt.value()) {
                Some((key, value))
            } else {
                None
            }
        })
    }

    /// Get the value of an option by key
    pub fn get_option(&self, key: &str) -> Option<String> {
        for child in self.options() {
            if child.key().as_deref() == Some(key) {
                return child.value();
            }
        }
        None
    }

    /// Add a new option to the end of the options list.
    fn add_option(&mut self, key: &str, value: &str) {
        let option_count = self.0.children().filter(|n| n.kind() == OPTION).count();

        // Build a structure containing separator (if needed) + option wrapped in a temporary parent
        let mut builder = GreenNodeBuilder::new();
        builder.start_node(ROOT.into()); // Temporary parent

        if option_count > 0 {
            builder.start_node(OPTION_SEPARATOR.into());
            builder.token(COMMA.into(), ",");
            builder.finish_node();
        }

        builder.start_node(OPTION.into());
        builder.token(KEY.into(), key);
        builder.token(EQUALS.into(), "=");
        builder.token(VALUE.into(), value);
        builder.finish_node();

        builder.finish_node(); // Close temporary parent
        let combined_green = builder.finish();

        // Create a temporary root to extract children from
        let temp_root = SyntaxNode::new_root_mut(combined_green);
        let new_children: Vec<_> = temp_root.children_with_tokens().collect();

        let insert_pos = self.0.children_with_tokens().count();
        self.0.splice_children(insert_pos..insert_pos, new_children);
    }

    /// Remove an option by key. Returns true if an option was removed.
    fn remove_option(&mut self, key: &str) -> bool {
        if let Some(mut opt) = self.find_option(key) {
            opt.remove();
            true
        } else {
            false
        }
    }
}

impl _Option {
    /// Returns the key of the option.
    pub fn key(&self) -> Option<String> {
        self.0.children_with_tokens().find_map(|it| match it {
            SyntaxElement::Token(token) => {
                if token.kind() == KEY {
                    Some(token.text().to_string())
                } else {
                    None
                }
            }
            _ => None,
        })
    }

    /// Returns the value of the option.
    pub fn value(&self) -> Option<String> {
        self.0
            .children_with_tokens()
            .filter_map(|it| match it {
                SyntaxElement::Token(token) => {
                    if token.kind() == VALUE || token.kind() == KEY {
                        Some(token.text().to_string())
                    } else {
                        None
                    }
                }
                _ => None,
            })
            .nth(1)
    }

    /// Set the value of the option.
    pub fn set_value(&mut self, new_value: &str) {
        let key = self.key().expect("Option must have a key");

        // Build a new OPTION node with the updated value
        let mut builder = GreenNodeBuilder::new();
        builder.start_node(OPTION.into());
        builder.token(KEY.into(), &key);
        builder.token(EQUALS.into(), "=");
        builder.token(VALUE.into(), new_value);
        builder.finish_node();
        let new_option_green = builder.finish();
        let new_option_node = SyntaxNode::new_root_mut(new_option_green);

        // Replace this option in the parent OptionList
        if let Some(parent) = self.0.parent() {
            let idx = self.0.index();
            parent.splice_children(idx..idx + 1, vec![new_option_node.into()]);
        }
    }

    /// Remove this option and its associated separator from the parent OptionList.
    pub fn remove(&mut self) {
        // Find adjacent separator to remove before detaching this node
        let next_sep = self
            .0
            .next_sibling()
            .filter(|n| n.kind() == OPTION_SEPARATOR);
        let prev_sep = self
            .0
            .prev_sibling()
            .filter(|n| n.kind() == OPTION_SEPARATOR);

        // Detach separator first if it exists
        if let Some(sep) = next_sep {
            sep.detach();
        } else if let Some(sep) = prev_sep {
            sep.detach();
        }

        // Now detach the option itself
        self.0.detach();
    }
}

impl Url {
    /// Returns the URL string.
    pub fn url(&self) -> String {
        self.0
            .children_with_tokens()
            .find_map(|it| match it {
                SyntaxElement::Token(token) => {
                    if token.kind() == VALUE {
                        Some(token.text().to_string())
                    } else {
                        None
                    }
                }
                _ => None,
            })
            .unwrap()
    }
}

impl MatchingPattern {
    /// Returns the matching pattern string.
    pub fn pattern(&self) -> String {
        self.0
            .children_with_tokens()
            .find_map(|it| match it {
                SyntaxElement::Token(token) => {
                    if token.kind() == VALUE {
                        Some(token.text().to_string())
                    } else {
                        None
                    }
                }
                _ => None,
            })
            .unwrap()
    }
}

impl VersionPolicyNode {
    /// Returns the version policy string.
    pub fn policy(&self) -> String {
        self.0
            .children_with_tokens()
            .find_map(|it| match it {
                SyntaxElement::Token(token) => {
                    // Can be KEY (e.g., "debian") or VALUE
                    if token.kind() == VALUE || token.kind() == KEY {
                        Some(token.text().to_string())
                    } else {
                        None
                    }
                }
                _ => None,
            })
            .unwrap()
    }
}

impl ScriptNode {
    /// Returns the script string.
    pub fn script(&self) -> String {
        self.0
            .children_with_tokens()
            .find_map(|it| match it {
                SyntaxElement::Token(token) => {
                    // Can be KEY (e.g., "uupdate") or VALUE
                    if token.kind() == VALUE || token.kind() == KEY {
                        Some(token.text().to_string())
                    } else {
                        None
                    }
                }
                _ => None,
            })
            .unwrap()
    }
}

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

    #[test]
    fn test_entry_node_structure() {
        // Test that entries properly use the new node types
        let wf: super::WatchFile = r#"version=4
opts=compression=xz https://example.com/releases (?:.*?/)?v?(\d[\d.]*)\.tar\.gz debian uupdate
"#
        .parse()
        .unwrap();

        let entry = wf.entries().next().unwrap();

        // Verify URL node exists and works
        assert_eq!(entry.0.children().find(|n| n.kind() == URL).is_some(), true);
        assert_eq!(entry.url(), "https://example.com/releases");

        // Verify MATCHING_PATTERN node exists and works
        assert_eq!(
            entry
                .0
                .children()
                .find(|n| n.kind() == MATCHING_PATTERN)
                .is_some(),
            true
        );
        assert_eq!(
            entry.matching_pattern(),
            Some("(?:.*?/)?v?(\\d[\\d.]*)\\.tar\\.gz".into())
        );

        // Verify VERSION_POLICY node exists and works
        assert_eq!(
            entry
                .0
                .children()
                .find(|n| n.kind() == VERSION_POLICY)
                .is_some(),
            true
        );
        assert_eq!(entry.version(), Ok(Some(super::VersionPolicy::Debian)));

        // Verify SCRIPT node exists and works
        assert_eq!(
            entry.0.children().find(|n| n.kind() == SCRIPT).is_some(),
            true
        );
        assert_eq!(entry.script(), Some("uupdate".into()));
    }

    #[test]
    fn test_entry_node_structure_partial() {
        // Test entry with only URL and pattern (no version or script)
        let wf: super::WatchFile = r#"version=4
https://github.com/example/tags .*/v?(\d\S+)\.tar\.gz
"#
        .parse()
        .unwrap();

        let entry = wf.entries().next().unwrap();

        // Should have URL and MATCHING_PATTERN nodes
        assert_eq!(entry.0.children().find(|n| n.kind() == URL).is_some(), true);
        assert_eq!(
            entry
                .0
                .children()
                .find(|n| n.kind() == MATCHING_PATTERN)
                .is_some(),
            true
        );

        // Should NOT have VERSION_POLICY or SCRIPT nodes
        assert_eq!(
            entry
                .0
                .children()
                .find(|n| n.kind() == VERSION_POLICY)
                .is_some(),
            false
        );
        assert_eq!(
            entry.0.children().find(|n| n.kind() == SCRIPT).is_some(),
            false
        );

        // Verify accessors work correctly
        assert_eq!(entry.url(), "https://github.com/example/tags");
        assert_eq!(
            entry.matching_pattern(),
            Some(".*/v?(\\d\\S+)\\.tar\\.gz".into())
        );
        assert_eq!(entry.version(), Ok(None));
        assert_eq!(entry.script(), None);
    }

    #[test]
    fn test_parse_v1() {
        const WATCHV1: &str = r#"version=4
opts=bare,filenamemangle=s/.+\/v?(\d\S+)\.tar\.gz/syncthing-gtk-$1\.tar\.gz/ \
  https://github.com/syncthing/syncthing-gtk/tags .*/v?(\d\S+)\.tar\.gz
"#;
        let parsed = parse(WATCHV1);
        //assert_eq!(parsed.errors, Vec::<String>::new());
        let node = parsed.syntax();
        assert_eq!(
            format!("{:#?}", node),
            r#"ROOT@0..161
  VERSION@0..10
    KEY@0..7 "version"
    EQUALS@7..8 "="
    VALUE@8..9 "4"
    NEWLINE@9..10 "\n"
  ENTRY@10..161
    OPTS_LIST@10..86
      KEY@10..14 "opts"
      EQUALS@14..15 "="
      OPTION@15..19
        KEY@15..19 "bare"
      OPTION_SEPARATOR@19..20
        COMMA@19..20 ","
      OPTION@20..86
        KEY@20..34 "filenamemangle"
        EQUALS@34..35 "="
        VALUE@35..86 "s/.+\\/v?(\\d\\S+)\\.tar\\ ..."
    WHITESPACE@86..87 " "
    CONTINUATION@87..89 "\\\n"
    WHITESPACE@89..91 "  "
    URL@91..138
      VALUE@91..138 "https://github.com/sy ..."
    WHITESPACE@138..139 " "
    MATCHING_PATTERN@139..160
      VALUE@139..160 ".*/v?(\\d\\S+)\\.tar\\.gz"
    NEWLINE@160..161 "\n"
"#
        );

        let root = parsed.root();
        assert_eq!(root.version(), 4);
        let entries = root.entries().collect::<Vec<_>>();
        assert_eq!(entries.len(), 1);
        let entry = &entries[0];
        assert_eq!(
            entry.url(),
            "https://github.com/syncthing/syncthing-gtk/tags"
        );
        assert_eq!(
            entry.matching_pattern(),
            Some(".*/v?(\\d\\S+)\\.tar\\.gz".into())
        );
        assert_eq!(entry.version(), Ok(None));
        assert_eq!(entry.script(), None);

        assert_eq!(node.text(), WATCHV1);
    }

    #[test]
    fn test_parse_v2() {
        let parsed = parse(
            r#"version=4
https://github.com/syncthing/syncthing-gtk/tags .*/v?(\d\S+)\.tar\.gz
# comment
"#,
        );
        assert_eq!(parsed.errors, Vec::<String>::new());
        let node = parsed.syntax();
        assert_eq!(
            format!("{:#?}", node),
            r###"ROOT@0..90
  VERSION@0..10
    KEY@0..7 "version"
    EQUALS@7..8 "="
    VALUE@8..9 "4"
    NEWLINE@9..10 "\n"
  ENTRY@10..80
    URL@10..57
      VALUE@10..57 "https://github.com/sy ..."
    WHITESPACE@57..58 " "
    MATCHING_PATTERN@58..79
      VALUE@58..79 ".*/v?(\\d\\S+)\\.tar\\.gz"
    NEWLINE@79..80 "\n"
  COMMENT@80..89 "# comment"
  NEWLINE@89..90 "\n"
"###
        );

        let root = parsed.root();
        assert_eq!(root.version(), 4);
        let entries = root.entries().collect::<Vec<_>>();
        assert_eq!(entries.len(), 1);
        let entry = &entries[0];
        assert_eq!(
            entry.url(),
            "https://github.com/syncthing/syncthing-gtk/tags"
        );
        assert_eq!(
            entry.format_url(|| "syncthing-gtk".to_string(), || String::new()),
            "https://github.com/syncthing/syncthing-gtk/tags"
                .parse()
                .unwrap()
        );
    }

    #[test]
    fn test_parse_v3() {
        let parsed = parse(
            r#"version=4
https://github.com/syncthing/@PACKAGE@/tags .*/v?(\d\S+)\.tar\.gz
# comment
"#,
        );
        assert_eq!(parsed.errors, Vec::<String>::new());
        let root = parsed.root();
        assert_eq!(root.version(), 4);
        let entries = root.entries().collect::<Vec<_>>();
        assert_eq!(entries.len(), 1);
        let entry = &entries[0];
        assert_eq!(entry.url(), "https://github.com/syncthing/@PACKAGE@/tags");
        assert_eq!(
            entry.format_url(|| "syncthing-gtk".to_string(), || String::new()),
            "https://github.com/syncthing/syncthing-gtk/tags"
                .parse()
                .unwrap()
        );
    }

    #[test]
    fn test_thread_safe_parsing() {
        let text = r#"version=4
https://github.com/example/example/tags example-(.*)\.tar\.gz
"#;

        let parsed = parse_watch_file(text);
        assert!(parsed.is_ok());
        assert_eq!(parsed.errors().len(), 0);

        // Test that we can get the AST from the parse result
        let watchfile = parsed.tree();
        assert_eq!(watchfile.version(), 4);
        let entries: Vec<_> = watchfile.entries().collect();
        assert_eq!(entries.len(), 1);
    }

    #[test]
    fn test_parse_clone_and_eq() {
        let text = r#"version=4
https://github.com/example/example/tags example-(.*)\.tar\.gz
"#;

        let parsed1 = parse_watch_file(text);
        let parsed2 = parsed1.clone();

        // Test that cloned parse results are equal
        assert_eq!(parsed1, parsed2);

        // Test that the AST nodes are also cloneable
        let watchfile1 = parsed1.tree();
        let watchfile2 = watchfile1.clone();
        assert_eq!(watchfile1, watchfile2);
    }

    #[test]
    fn test_parse_v4() {
        let cl: super::WatchFile = r#"version=4
opts=repack,compression=xz,dversionmangle=s/\+ds//,repacksuffix=+ds \
    https://github.com/example/example-cat/tags \
        (?:.*?/)?v?(\d[\d.]*)\.tar\.gz debian uupdate
"#
        .parse()
        .unwrap();
        assert_eq!(cl.version(), 4);
        let entries = cl.entries().collect::<Vec<_>>();
        assert_eq!(entries.len(), 1);
        let entry = &entries[0];
        assert_eq!(entry.url(), "https://github.com/example/example-cat/tags");
        assert_eq!(
            entry.matching_pattern(),
            Some("(?:.*?/)?v?(\\d[\\d.]*)\\.tar\\.gz".into())
        );
        assert!(entry.repack());
        assert_eq!(entry.compression(), Ok(Some(Compression::Xz)));
        assert_eq!(entry.dversionmangle(), Some("s/\\+ds//".into()));
        assert_eq!(entry.repacksuffix(), Some("+ds".into()));
        assert_eq!(entry.script(), Some("uupdate".into()));
        assert_eq!(
            entry.format_url(|| "example-cat".to_string(), || String::new()),
            "https://github.com/example/example-cat/tags"
                .parse()
                .unwrap()
        );
        assert_eq!(entry.version(), Ok(Some(VersionPolicy::Debian)));
    }

    #[test]
    fn test_git_mode() {
        let text = r#"version=3
opts="mode=git, gitmode=shallow, pgpmode=gittag" \
https://git.kernel.org/pub/scm/linux/kernel/git/firmware/linux-firmware.git \
refs/tags/(.*) debian
"#;
        let parsed = parse(text);
        assert_eq!(parsed.errors, Vec::<String>::new());
        let cl = parsed.root();
        assert_eq!(cl.version(), 3);
        let entries = cl.entries().collect::<Vec<_>>();
        assert_eq!(entries.len(), 1);
        let entry = &entries[0];
        assert_eq!(
            entry.url(),
            "https://git.kernel.org/pub/scm/linux/kernel/git/firmware/linux-firmware.git"
        );
        assert_eq!(entry.matching_pattern(), Some("refs/tags/(.*)".into()));
        assert_eq!(entry.version(), Ok(Some(VersionPolicy::Debian)));
        assert_eq!(entry.script(), None);
        assert_eq!(entry.gitmode(), Ok(GitMode::Shallow));
        assert_eq!(entry.pgpmode(), Ok(PgpMode::GitTag));
        assert_eq!(entry.mode(), Ok(Mode::Git));
    }

    #[test]
    fn test_parse_quoted() {
        const WATCHV1: &str = r#"version=4
opts="bare, filenamemangle=blah" \
  https://github.com/syncthing/syncthing-gtk/tags .*/v?(\d\S+)\.tar\.gz
"#;
        let parsed = parse(WATCHV1);
        //assert_eq!(parsed.errors, Vec::<String>::new());
        let node = parsed.syntax();

        let root = parsed.root();
        assert_eq!(root.version(), 4);
        let entries = root.entries().collect::<Vec<_>>();
        assert_eq!(entries.len(), 1);
        let entry = &entries[0];

        assert_eq!(
            entry.url(),
            "https://github.com/syncthing/syncthing-gtk/tags"
        );
        assert_eq!(
            entry.matching_pattern(),
            Some(".*/v?(\\d\\S+)\\.tar\\.gz".into())
        );
        assert_eq!(entry.version(), Ok(None));
        assert_eq!(entry.script(), None);

        assert_eq!(node.text(), WATCHV1);
    }

    #[test]
    fn test_set_url() {
        // Test setting URL on a simple entry without options
        let wf: super::WatchFile = r#"version=4
https://github.com/syncthing/syncthing-gtk/tags .*/v?(\d\S+)\.tar\.gz
"#
        .parse()
        .unwrap();

        let mut entry = wf.entries().next().unwrap();
        assert_eq!(
            entry.url(),
            "https://github.com/syncthing/syncthing-gtk/tags"
        );

        entry.set_url("https://newurl.example.org/path");
        assert_eq!(entry.url(), "https://newurl.example.org/path");
        assert_eq!(
            entry.matching_pattern(),
            Some(".*/v?(\\d\\S+)\\.tar\\.gz".into())
        );

        // Verify the exact serialized output
        assert_eq!(
            entry.to_string(),
            "https://newurl.example.org/path .*/v?(\\d\\S+)\\.tar\\.gz\n"
        );
    }

    #[test]
    fn test_set_url_with_options() {
        // Test setting URL on an entry with options
        let wf: super::WatchFile = r#"version=4
opts=foo=blah https://foo.com/bar .*/v?(\d\S+)\.tar\.gz
"#
        .parse()
        .unwrap();

        let mut entry = wf.entries().next().unwrap();
        assert_eq!(entry.url(), "https://foo.com/bar");
        assert_eq!(entry.get_option("foo"), Some("blah".to_string()));

        entry.set_url("https://example.com/baz");
        assert_eq!(entry.url(), "https://example.com/baz");

        // Verify options are preserved
        assert_eq!(entry.get_option("foo"), Some("blah".to_string()));
        assert_eq!(
            entry.matching_pattern(),
            Some(".*/v?(\\d\\S+)\\.tar\\.gz".into())
        );

        // Verify the exact serialized output
        assert_eq!(
            entry.to_string(),
            "opts=foo=blah https://example.com/baz .*/v?(\\d\\S+)\\.tar\\.gz\n"
        );
    }

    #[test]
    fn test_set_url_complex() {
        // Test with a complex watch file with multiple options and continuation
        let wf: super::WatchFile = r#"version=4
opts=bare,filenamemangle=s/.+\/v?(\d\S+)\.tar\.gz/syncthing-gtk-$1\.tar\.gz/ \
  https://github.com/syncthing/syncthing-gtk/tags .*/v?(\d\S+)\.tar\.gz
"#
        .parse()
        .unwrap();

        let mut entry = wf.entries().next().unwrap();
        assert_eq!(
            entry.url(),
            "https://github.com/syncthing/syncthing-gtk/tags"
        );

        entry.set_url("https://gitlab.com/newproject/tags");
        assert_eq!(entry.url(), "https://gitlab.com/newproject/tags");

        // Verify all options are preserved
        assert!(entry.bare());
        assert_eq!(
            entry.filenamemangle(),
            Some("s/.+\\/v?(\\d\\S+)\\.tar\\.gz/syncthing-gtk-$1\\.tar\\.gz/".into())
        );
        assert_eq!(
            entry.matching_pattern(),
            Some(".*/v?(\\d\\S+)\\.tar\\.gz".into())
        );

        // Verify the exact serialized output preserves structure
        assert_eq!(
            entry.to_string(),
            r#"opts=bare,filenamemangle=s/.+\/v?(\d\S+)\.tar\.gz/syncthing-gtk-$1\.tar\.gz/ \
  https://gitlab.com/newproject/tags .*/v?(\d\S+)\.tar\.gz
"#
        );
    }

    #[test]
    fn test_set_url_with_all_fields() {
        // Test with all fields: options, URL, matching pattern, version, and script
        let wf: super::WatchFile = r#"version=4
opts=repack,compression=xz,dversionmangle=s/\+ds//,repacksuffix=+ds \
    https://github.com/example/example-cat/tags \
        (?:.*?/)?v?(\d[\d.]*)\.tar\.gz debian uupdate
"#
        .parse()
        .unwrap();

        let mut entry = wf.entries().next().unwrap();
        assert_eq!(entry.url(), "https://github.com/example/example-cat/tags");
        assert_eq!(
            entry.matching_pattern(),
            Some("(?:.*?/)?v?(\\d[\\d.]*)\\.tar\\.gz".into())
        );
        assert_eq!(entry.version(), Ok(Some(super::VersionPolicy::Debian)));
        assert_eq!(entry.script(), Some("uupdate".into()));

        entry.set_url("https://gitlab.example.org/project/releases");
        assert_eq!(entry.url(), "https://gitlab.example.org/project/releases");

        // Verify all other fields are preserved
        assert!(entry.repack());
        assert_eq!(entry.compression(), Ok(Some(super::Compression::Xz)));
        assert_eq!(entry.dversionmangle(), Some("s/\\+ds//".into()));
        assert_eq!(entry.repacksuffix(), Some("+ds".into()));
        assert_eq!(
            entry.matching_pattern(),
            Some("(?:.*?/)?v?(\\d[\\d.]*)\\.tar\\.gz".into())
        );
        assert_eq!(entry.version(), Ok(Some(super::VersionPolicy::Debian)));
        assert_eq!(entry.script(), Some("uupdate".into()));

        // Verify the exact serialized output
        assert_eq!(
            entry.to_string(),
            r#"opts=repack,compression=xz,dversionmangle=s/\+ds//,repacksuffix=+ds \
    https://gitlab.example.org/project/releases \
        (?:.*?/)?v?(\d[\d.]*)\.tar\.gz debian uupdate
"#
        );
    }

    #[test]
    fn test_set_url_quoted_options() {
        // Test with quoted options
        let wf: super::WatchFile = r#"version=4
opts="bare, filenamemangle=blah" \
  https://github.com/syncthing/syncthing-gtk/tags .*/v?(\d\S+)\.tar\.gz
"#
        .parse()
        .unwrap();

        let mut entry = wf.entries().next().unwrap();
        assert_eq!(
            entry.url(),
            "https://github.com/syncthing/syncthing-gtk/tags"
        );

        entry.set_url("https://example.org/new/path");
        assert_eq!(entry.url(), "https://example.org/new/path");

        // Verify the exact serialized output
        assert_eq!(
            entry.to_string(),
            r#"opts="bare, filenamemangle=blah" \
  https://example.org/new/path .*/v?(\d\S+)\.tar\.gz
"#
        );
    }

    #[test]
    fn test_set_opt_update_existing() {
        // Test updating an existing option
        let wf: super::WatchFile = r#"version=4
opts=foo=blah,bar=baz https://example.com/releases .*/v?(\d\S+)\.tar\.gz
"#
        .parse()
        .unwrap();

        let mut entry = wf.entries().next().unwrap();
        assert_eq!(entry.get_option("foo"), Some("blah".to_string()));
        assert_eq!(entry.get_option("bar"), Some("baz".to_string()));

        entry.set_opt("foo", "updated");
        assert_eq!(entry.get_option("foo"), Some("updated".to_string()));
        assert_eq!(entry.get_option("bar"), Some("baz".to_string()));

        // Verify the exact serialized output
        assert_eq!(
            entry.to_string(),
            "opts=foo=updated,bar=baz https://example.com/releases .*/v?(\\d\\S+)\\.tar\\.gz\n"
        );
    }

    #[test]
    fn test_set_opt_add_new() {
        // Test adding a new option to existing options
        let wf: super::WatchFile = r#"version=4
opts=foo=blah https://example.com/releases .*/v?(\d\S+)\.tar\.gz
"#
        .parse()
        .unwrap();

        let mut entry = wf.entries().next().unwrap();
        assert_eq!(entry.get_option("foo"), Some("blah".to_string()));
        assert_eq!(entry.get_option("bar"), None);

        entry.set_opt("bar", "baz");
        assert_eq!(entry.get_option("foo"), Some("blah".to_string()));
        assert_eq!(entry.get_option("bar"), Some("baz".to_string()));

        // Verify the exact serialized output
        assert_eq!(
            entry.to_string(),
            "opts=foo=blah,bar=baz https://example.com/releases .*/v?(\\d\\S+)\\.tar\\.gz\n"
        );
    }

    #[test]
    fn test_set_opt_create_options_list() {
        // Test creating a new options list when none exists
        let wf: super::WatchFile = r#"version=4
https://example.com/releases .*/v?(\d\S+)\.tar\.gz
"#
        .parse()
        .unwrap();

        let mut entry = wf.entries().next().unwrap();
        assert_eq!(entry.option_list(), None);

        entry.set_opt("compression", "xz");
        assert_eq!(entry.get_option("compression"), Some("xz".to_string()));

        // Verify the exact serialized output
        assert_eq!(
            entry.to_string(),
            "opts=compression=xz https://example.com/releases .*/v?(\\d\\S+)\\.tar\\.gz\n"
        );
    }

    #[test]
    fn test_del_opt_remove_single() {
        // Test removing a single option from multiple options
        let wf: super::WatchFile = r#"version=4
opts=foo=blah,bar=baz,qux=quux https://example.com/releases .*/v?(\d\S+)\.tar\.gz
"#
        .parse()
        .unwrap();

        let mut entry = wf.entries().next().unwrap();
        assert_eq!(entry.get_option("foo"), Some("blah".to_string()));
        assert_eq!(entry.get_option("bar"), Some("baz".to_string()));
        assert_eq!(entry.get_option("qux"), Some("quux".to_string()));

        entry.del_opt_str("bar");
        assert_eq!(entry.get_option("foo"), Some("blah".to_string()));
        assert_eq!(entry.get_option("bar"), None);
        assert_eq!(entry.get_option("qux"), Some("quux".to_string()));

        // Verify the exact serialized output
        assert_eq!(
            entry.to_string(),
            "opts=foo=blah,qux=quux https://example.com/releases .*/v?(\\d\\S+)\\.tar\\.gz\n"
        );
    }

    #[test]
    fn test_del_opt_remove_first() {
        // Test removing the first option
        let wf: super::WatchFile = r#"version=4
opts=foo=blah,bar=baz https://example.com/releases .*/v?(\d\S+)\.tar\.gz
"#
        .parse()
        .unwrap();

        let mut entry = wf.entries().next().unwrap();
        entry.del_opt_str("foo");
        assert_eq!(entry.get_option("foo"), None);
        assert_eq!(entry.get_option("bar"), Some("baz".to_string()));

        // Verify the exact serialized output
        assert_eq!(
            entry.to_string(),
            "opts=bar=baz https://example.com/releases .*/v?(\\d\\S+)\\.tar\\.gz\n"
        );
    }

    #[test]
    fn test_del_opt_remove_last() {
        // Test removing the last option
        let wf: super::WatchFile = r#"version=4
opts=foo=blah,bar=baz https://example.com/releases .*/v?(\d\S+)\.tar\.gz
"#
        .parse()
        .unwrap();

        let mut entry = wf.entries().next().unwrap();
        entry.del_opt_str("bar");
        assert_eq!(entry.get_option("foo"), Some("blah".to_string()));
        assert_eq!(entry.get_option("bar"), None);

        // Verify the exact serialized output
        assert_eq!(
            entry.to_string(),
            "opts=foo=blah https://example.com/releases .*/v?(\\d\\S+)\\.tar\\.gz\n"
        );
    }

    #[test]
    fn test_del_opt_remove_only_option() {
        // Test removing the only option (should remove entire opts list)
        let wf: super::WatchFile = r#"version=4
opts=foo=blah https://example.com/releases .*/v?(\d\S+)\.tar\.gz
"#
        .parse()
        .unwrap();

        let mut entry = wf.entries().next().unwrap();
        assert_eq!(entry.get_option("foo"), Some("blah".to_string()));

        entry.del_opt_str("foo");
        assert_eq!(entry.get_option("foo"), None);
        assert_eq!(entry.option_list(), None);

        // Verify the exact serialized output (opts should be gone)
        assert_eq!(
            entry.to_string(),
            "https://example.com/releases .*/v?(\\d\\S+)\\.tar\\.gz\n"
        );
    }

    #[test]
    fn test_del_opt_nonexistent() {
        // Test deleting a non-existent option (should do nothing)
        let wf: super::WatchFile = r#"version=4
opts=foo=blah https://example.com/releases .*/v?(\d\S+)\.tar\.gz
"#
        .parse()
        .unwrap();

        let mut entry = wf.entries().next().unwrap();
        let original = entry.to_string();

        entry.del_opt_str("nonexistent");
        assert_eq!(entry.to_string(), original);
    }

    #[test]
    fn test_set_opt_multiple_operations() {
        // Test multiple set_opt operations
        let wf: super::WatchFile = r#"version=4
https://example.com/releases .*/v?(\d\S+)\.tar\.gz
"#
        .parse()
        .unwrap();

        let mut entry = wf.entries().next().unwrap();

        entry.set_opt("compression", "xz");
        entry.set_opt("repack", "");
        entry.set_opt("dversionmangle", "s/\\+ds//");

        assert_eq!(entry.get_option("compression"), Some("xz".to_string()));
        assert_eq!(
            entry.get_option("dversionmangle"),
            Some("s/\\+ds//".to_string())
        );
    }

    #[test]
    fn test_set_matching_pattern() {
        // Test setting matching pattern on a simple entry
        let wf: super::WatchFile = r#"version=4
https://github.com/example/tags .*/v?(\d\S+)\.tar\.gz
"#
        .parse()
        .unwrap();

        let mut entry = wf.entries().next().unwrap();
        assert_eq!(
            entry.matching_pattern(),
            Some(".*/v?(\\d\\S+)\\.tar\\.gz".into())
        );

        entry.set_matching_pattern("(?:.*?/)?v?([\\d.]+)\\.tar\\.gz");
        assert_eq!(
            entry.matching_pattern(),
            Some("(?:.*?/)?v?([\\d.]+)\\.tar\\.gz".into())
        );

        // Verify URL is preserved
        assert_eq!(entry.url(), "https://github.com/example/tags");

        // Verify the exact serialized output
        assert_eq!(
            entry.to_string(),
            "https://github.com/example/tags (?:.*?/)?v?([\\d.]+)\\.tar\\.gz\n"
        );
    }

    #[test]
    fn test_set_matching_pattern_with_all_fields() {
        // Test with all fields present
        let wf: super::WatchFile = r#"version=4
opts=compression=xz https://example.com/releases (?:.*?/)?v?(\d[\d.]*)\.tar\.gz debian uupdate
"#
        .parse()
        .unwrap();

        let mut entry = wf.entries().next().unwrap();
        assert_eq!(
            entry.matching_pattern(),
            Some("(?:.*?/)?v?(\\d[\\d.]*)\\.tar\\.gz".into())
        );

        entry.set_matching_pattern(".*/version-([\\d.]+)\\.tar\\.xz");
        assert_eq!(
            entry.matching_pattern(),
            Some(".*/version-([\\d.]+)\\.tar\\.xz".into())
        );

        // Verify all other fields are preserved
        assert_eq!(entry.url(), "https://example.com/releases");
        assert_eq!(entry.version(), Ok(Some(super::VersionPolicy::Debian)));
        assert_eq!(entry.script(), Some("uupdate".into()));
        assert_eq!(entry.compression(), Ok(Some(super::Compression::Xz)));

        // Verify the exact serialized output
        assert_eq!(
        entry.to_string(),
        "opts=compression=xz https://example.com/releases .*/version-([\\d.]+)\\.tar\\.xz debian uupdate\n"
    );
    }

    #[test]
    fn test_set_version_policy() {
        // Test setting version policy
        let wf: super::WatchFile = r#"version=4
https://example.com/releases (?:.*?/)?v?(\d[\d.]*)\.tar\.gz debian uupdate
"#
        .parse()
        .unwrap();

        let mut entry = wf.entries().next().unwrap();
        assert_eq!(entry.version(), Ok(Some(super::VersionPolicy::Debian)));

        entry.set_version_policy("previous");
        assert_eq!(entry.version(), Ok(Some(super::VersionPolicy::Previous)));

        // Verify all other fields are preserved
        assert_eq!(entry.url(), "https://example.com/releases");
        assert_eq!(
            entry.matching_pattern(),
            Some("(?:.*?/)?v?(\\d[\\d.]*)\\.tar\\.gz".into())
        );
        assert_eq!(entry.script(), Some("uupdate".into()));

        // Verify the exact serialized output
        assert_eq!(
            entry.to_string(),
            "https://example.com/releases (?:.*?/)?v?(\\d[\\d.]*)\\.tar\\.gz previous uupdate\n"
        );
    }

    #[test]
    fn test_set_version_policy_with_options() {
        // Test with options and continuation
        let wf: super::WatchFile = r#"version=4
opts=repack,compression=xz \
    https://github.com/example/example-cat/tags \
        (?:.*?/)?v?(\d[\d.]*)\.tar\.gz debian uupdate
"#
        .parse()
        .unwrap();

        let mut entry = wf.entries().next().unwrap();
        assert_eq!(entry.version(), Ok(Some(super::VersionPolicy::Debian)));

        entry.set_version_policy("ignore");
        assert_eq!(entry.version(), Ok(Some(super::VersionPolicy::Ignore)));

        // Verify all other fields are preserved
        assert_eq!(entry.url(), "https://github.com/example/example-cat/tags");
        assert_eq!(
            entry.matching_pattern(),
            Some("(?:.*?/)?v?(\\d[\\d.]*)\\.tar\\.gz".into())
        );
        assert_eq!(entry.script(), Some("uupdate".into()));
        assert!(entry.repack());

        // Verify the exact serialized output
        assert_eq!(
            entry.to_string(),
            r#"opts=repack,compression=xz \
    https://github.com/example/example-cat/tags \
        (?:.*?/)?v?(\d[\d.]*)\.tar\.gz ignore uupdate
"#
        );
    }

    #[test]
    fn test_set_script() {
        // Test setting script
        let wf: super::WatchFile = r#"version=4
https://example.com/releases (?:.*?/)?v?(\d[\d.]*)\.tar\.gz debian uupdate
"#
        .parse()
        .unwrap();

        let mut entry = wf.entries().next().unwrap();
        assert_eq!(entry.script(), Some("uupdate".into()));

        entry.set_script("uscan");
        assert_eq!(entry.script(), Some("uscan".into()));

        // Verify all other fields are preserved
        assert_eq!(entry.url(), "https://example.com/releases");
        assert_eq!(
            entry.matching_pattern(),
            Some("(?:.*?/)?v?(\\d[\\d.]*)\\.tar\\.gz".into())
        );
        assert_eq!(entry.version(), Ok(Some(super::VersionPolicy::Debian)));

        // Verify the exact serialized output
        assert_eq!(
            entry.to_string(),
            "https://example.com/releases (?:.*?/)?v?(\\d[\\d.]*)\\.tar\\.gz debian uscan\n"
        );
    }

    #[test]
    fn test_set_script_with_options() {
        // Test with options
        let wf: super::WatchFile = r#"version=4
opts=compression=xz https://example.com/releases (?:.*?/)?v?(\d[\d.]*)\.tar\.gz debian uupdate
"#
        .parse()
        .unwrap();

        let mut entry = wf.entries().next().unwrap();
        assert_eq!(entry.script(), Some("uupdate".into()));

        entry.set_script("custom-script.sh");
        assert_eq!(entry.script(), Some("custom-script.sh".into()));

        // Verify all other fields are preserved
        assert_eq!(entry.url(), "https://example.com/releases");
        assert_eq!(
            entry.matching_pattern(),
            Some("(?:.*?/)?v?(\\d[\\d.]*)\\.tar\\.gz".into())
        );
        assert_eq!(entry.version(), Ok(Some(super::VersionPolicy::Debian)));
        assert_eq!(entry.compression(), Ok(Some(super::Compression::Xz)));

        // Verify the exact serialized output
        assert_eq!(
        entry.to_string(),
        "opts=compression=xz https://example.com/releases (?:.*?/)?v?(\\d[\\d.]*)\\.tar\\.gz debian custom-script.sh\n"
    );
    }

    #[test]
    fn test_apply_dversionmangle() {
        // Test basic dversionmangle
        let wf: super::WatchFile = r#"version=4
opts=dversionmangle=s/\+dfsg$// https://example.com/ .*
"#
        .parse()
        .unwrap();
        let entry = wf.entries().next().unwrap();
        assert_eq!(entry.apply_dversionmangle("1.0+dfsg").unwrap(), "1.0");
        assert_eq!(entry.apply_dversionmangle("1.0").unwrap(), "1.0");

        // Test with versionmangle (fallback)
        let wf: super::WatchFile = r#"version=4
opts=versionmangle=s/^v// https://example.com/ .*
"#
        .parse()
        .unwrap();
        let entry = wf.entries().next().unwrap();
        assert_eq!(entry.apply_dversionmangle("v1.0").unwrap(), "1.0");

        // Test with both dversionmangle and versionmangle (dversionmangle takes precedence)
        let wf: super::WatchFile = r#"version=4
opts=dversionmangle=s/\+ds//,versionmangle=s/^v// https://example.com/ .*
"#
        .parse()
        .unwrap();
        let entry = wf.entries().next().unwrap();
        assert_eq!(entry.apply_dversionmangle("1.0+ds").unwrap(), "1.0");

        // Test without any mangle options
        let wf: super::WatchFile = r#"version=4
https://example.com/ .*
"#
        .parse()
        .unwrap();
        let entry = wf.entries().next().unwrap();
        assert_eq!(entry.apply_dversionmangle("1.0+dfsg").unwrap(), "1.0+dfsg");
    }

    #[test]
    fn test_apply_oversionmangle() {
        // Test basic oversionmangle - adding suffix
        let wf: super::WatchFile = r#"version=4
opts=oversionmangle=s/$/-1/ https://example.com/ .*
"#
        .parse()
        .unwrap();
        let entry = wf.entries().next().unwrap();
        assert_eq!(entry.apply_oversionmangle("1.0").unwrap(), "1.0-1");
        assert_eq!(entry.apply_oversionmangle("2.5.3").unwrap(), "2.5.3-1");

        // Test oversionmangle for adding +dfsg suffix
        let wf: super::WatchFile = r#"version=4
opts=oversionmangle=s/$/.dfsg/ https://example.com/ .*
"#
        .parse()
        .unwrap();
        let entry = wf.entries().next().unwrap();
        assert_eq!(entry.apply_oversionmangle("1.0").unwrap(), "1.0.dfsg");

        // Test without any mangle options
        let wf: super::WatchFile = r#"version=4
https://example.com/ .*
"#
        .parse()
        .unwrap();
        let entry = wf.entries().next().unwrap();
        assert_eq!(entry.apply_oversionmangle("1.0").unwrap(), "1.0");
    }

    #[test]
    fn test_apply_dirversionmangle() {
        // Test basic dirversionmangle - removing 'v' prefix
        let wf: super::WatchFile = r#"version=4
opts=dirversionmangle=s/^v// https://example.com/ .*
"#
        .parse()
        .unwrap();
        let entry = wf.entries().next().unwrap();
        assert_eq!(entry.apply_dirversionmangle("v1.0").unwrap(), "1.0");
        assert_eq!(entry.apply_dirversionmangle("v2.5.3").unwrap(), "2.5.3");

        // Test dirversionmangle with capture groups
        let wf: super::WatchFile = r#"version=4
opts=dirversionmangle=s/v(\d)/$1/ https://example.com/ .*
"#
        .parse()
        .unwrap();
        let entry = wf.entries().next().unwrap();
        assert_eq!(entry.apply_dirversionmangle("v1.0").unwrap(), "1.0");

        // Test without any mangle options
        let wf: super::WatchFile = r#"version=4
https://example.com/ .*
"#
        .parse()
        .unwrap();
        let entry = wf.entries().next().unwrap();
        assert_eq!(entry.apply_dirversionmangle("v1.0").unwrap(), "v1.0");
    }

    #[test]
    fn test_apply_filenamemangle() {
        // Test filenamemangle to generate tarball filename
        let wf: super::WatchFile = r#"version=4
opts=filenamemangle=s/.+\/v?(\d\S+)\.tar\.gz/mypackage-$1.tar.gz/ https://example.com/ .*
"#
        .parse()
        .unwrap();
        let entry = wf.entries().next().unwrap();
        assert_eq!(
            entry
                .apply_filenamemangle("https://example.com/v1.0.tar.gz")
                .unwrap(),
            "mypackage-1.0.tar.gz"
        );
        assert_eq!(
            entry
                .apply_filenamemangle("https://example.com/2.5.3.tar.gz")
                .unwrap(),
            "mypackage-2.5.3.tar.gz"
        );

        // Test filenamemangle with different pattern
        let wf: super::WatchFile = r#"version=4
opts=filenamemangle=s/.*\/(.*)/$1/ https://example.com/ .*
"#
        .parse()
        .unwrap();
        let entry = wf.entries().next().unwrap();
        assert_eq!(
            entry
                .apply_filenamemangle("https://example.com/path/to/file.tar.gz")
                .unwrap(),
            "file.tar.gz"
        );

        // Test without any mangle options
        let wf: super::WatchFile = r#"version=4
https://example.com/ .*
"#
        .parse()
        .unwrap();
        let entry = wf.entries().next().unwrap();
        assert_eq!(
            entry
                .apply_filenamemangle("https://example.com/file.tar.gz")
                .unwrap(),
            "https://example.com/file.tar.gz"
        );
    }

    #[test]
    fn test_apply_pagemangle() {
        // Test pagemangle to decode HTML entities
        let wf: super::WatchFile = r#"version=4
opts=pagemangle=s/&amp;/&/g https://example.com/ .*
"#
        .parse()
        .unwrap();
        let entry = wf.entries().next().unwrap();
        assert_eq!(
            entry.apply_pagemangle(b"foo &amp; bar").unwrap(),
            b"foo & bar"
        );
        assert_eq!(
            entry
                .apply_pagemangle(b"&amp; foo &amp; bar &amp;")
                .unwrap(),
            b"& foo & bar &"
        );

        // Test pagemangle with different pattern
        let wf: super::WatchFile = r#"version=4
opts=pagemangle=s/<[^>]+>//g https://example.com/ .*
"#
        .parse()
        .unwrap();
        let entry = wf.entries().next().unwrap();
        assert_eq!(entry.apply_pagemangle(b"<div>text</div>").unwrap(), b"text");

        // Test without any mangle options
        let wf: super::WatchFile = r#"version=4
https://example.com/ .*
"#
        .parse()
        .unwrap();
        let entry = wf.entries().next().unwrap();
        assert_eq!(
            entry.apply_pagemangle(b"foo &amp; bar").unwrap(),
            b"foo &amp; bar"
        );
    }

    #[test]
    fn test_apply_downloadurlmangle() {
        // Test downloadurlmangle to change URL path
        let wf: super::WatchFile = r#"version=4
opts=downloadurlmangle=s|/archive/|/download/| https://example.com/ .*
"#
        .parse()
        .unwrap();
        let entry = wf.entries().next().unwrap();
        assert_eq!(
            entry
                .apply_downloadurlmangle("https://example.com/archive/file.tar.gz")
                .unwrap(),
            "https://example.com/download/file.tar.gz"
        );

        // Test downloadurlmangle with different pattern
        let wf: super::WatchFile = r#"version=4
opts=downloadurlmangle=s/github\.com/raw.githubusercontent.com/ https://example.com/ .*
"#
        .parse()
        .unwrap();
        let entry = wf.entries().next().unwrap();
        assert_eq!(
            entry
                .apply_downloadurlmangle("https://github.com/user/repo/file.tar.gz")
                .unwrap(),
            "https://raw.githubusercontent.com/user/repo/file.tar.gz"
        );

        // Test without any mangle options
        let wf: super::WatchFile = r#"version=4
https://example.com/ .*
"#
        .parse()
        .unwrap();
        let entry = wf.entries().next().unwrap();
        assert_eq!(
            entry
                .apply_downloadurlmangle("https://example.com/archive/file.tar.gz")
                .unwrap(),
            "https://example.com/archive/file.tar.gz"
        );
    }

    #[test]
    fn test_entry_builder_minimal() {
        // Test creating a minimal entry with just URL and pattern
        let entry = super::EntryBuilder::new("https://github.com/example/tags")
            .matching_pattern(".*/v?(\\d\\S+)\\.tar\\.gz")
            .build();

        assert_eq!(entry.url(), "https://github.com/example/tags");
        assert_eq!(
            entry.matching_pattern().as_deref(),
            Some(".*/v?(\\d\\S+)\\.tar\\.gz")
        );
        assert_eq!(entry.version(), Ok(None));
        assert_eq!(entry.script(), None);
        assert!(entry.opts().is_empty());
    }

    #[test]
    fn test_entry_builder_url_only() {
        // Test creating an entry with just URL
        let entry = super::EntryBuilder::new("https://example.com/releases").build();

        assert_eq!(entry.url(), "https://example.com/releases");
        assert_eq!(entry.matching_pattern(), None);
        assert_eq!(entry.version(), Ok(None));
        assert_eq!(entry.script(), None);
        assert!(entry.opts().is_empty());
    }

    #[test]
    fn test_entry_builder_with_all_fields() {
        // Test creating an entry with all fields
        let entry = super::EntryBuilder::new("https://github.com/example/tags")
            .matching_pattern(".*/v?(\\d[\\d.]*)\\.tar\\.gz")
            .version_policy("debian")
            .script("uupdate")
            .opt("compression", "xz")
            .flag("repack")
            .build();

        assert_eq!(entry.url(), "https://github.com/example/tags");
        assert_eq!(
            entry.matching_pattern().as_deref(),
            Some(".*/v?(\\d[\\d.]*)\\.tar\\.gz")
        );
        assert_eq!(entry.version(), Ok(Some(VersionPolicy::Debian)));
        assert_eq!(entry.script(), Some("uupdate".into()));
        assert_eq!(entry.get_option("compression"), Some("xz".to_string()));
        assert!(entry.has_option("repack"));
        assert!(entry.repack());
    }

    #[test]
    fn test_entry_builder_multiple_options() {
        // Test creating an entry with multiple options
        let entry = super::EntryBuilder::new("https://example.com/tags")
            .matching_pattern(".*/v?(\\d+\\.\\d+)\\.tar\\.gz")
            .opt("compression", "xz")
            .opt("dversionmangle", "s/\\+ds//")
            .opt("repacksuffix", "+ds")
            .build();

        assert_eq!(entry.get_option("compression"), Some("xz".to_string()));
        assert_eq!(
            entry.get_option("dversionmangle"),
            Some("s/\\+ds//".to_string())
        );
        assert_eq!(entry.get_option("repacksuffix"), Some("+ds".to_string()));
    }

    #[test]
    fn test_entry_builder_via_entry() {
        // Test using Entry::builder() convenience method
        let entry = super::Entry::builder("https://github.com/example/tags")
            .matching_pattern(".*/v?(\\d\\S+)\\.tar\\.gz")
            .version_policy("debian")
            .build();

        assert_eq!(entry.url(), "https://github.com/example/tags");
        assert_eq!(
            entry.matching_pattern().as_deref(),
            Some(".*/v?(\\d\\S+)\\.tar\\.gz")
        );
        assert_eq!(entry.version(), Ok(Some(VersionPolicy::Debian)));
    }

    #[test]
    fn test_watchfile_add_entry_to_empty() {
        // Test adding an entry to an empty watchfile
        let mut wf = super::WatchFile::new(Some(4));

        let entry = super::EntryBuilder::new("https://github.com/example/tags")
            .matching_pattern(".*/v?(\\d\\S+)\\.tar\\.gz")
            .build();

        wf.add_entry(entry);

        assert_eq!(wf.version(), 4);
        assert_eq!(wf.entries().count(), 1);

        let added_entry = wf.entries().next().unwrap();
        assert_eq!(added_entry.url(), "https://github.com/example/tags");
        assert_eq!(
            added_entry.matching_pattern().as_deref(),
            Some(".*/v?(\\d\\S+)\\.tar\\.gz")
        );
    }

    #[test]
    fn test_watchfile_add_multiple_entries() {
        // Test adding multiple entries to a watchfile
        let mut wf = super::WatchFile::new(Some(4));

        wf.add_entry(
            super::EntryBuilder::new("https://github.com/example1/tags")
                .matching_pattern(".*/v?(\\d\\S+)\\.tar\\.gz")
                .build(),
        );

        wf.add_entry(
            super::EntryBuilder::new("https://github.com/example2/releases")
                .matching_pattern(".*/(\\d+\\.\\d+)\\.tar\\.gz")
                .opt("compression", "xz")
                .build(),
        );

        assert_eq!(wf.entries().count(), 2);

        let entries: Vec<_> = wf.entries().collect();
        assert_eq!(entries[0].url(), "https://github.com/example1/tags");
        assert_eq!(entries[1].url(), "https://github.com/example2/releases");
        assert_eq!(entries[1].get_option("compression"), Some("xz".to_string()));
    }

    #[test]
    fn test_watchfile_add_entry_to_existing() {
        // Test adding an entry to a watchfile that already has entries
        let mut wf: super::WatchFile = r#"version=4
https://example.com/old .*/v?(\\d\\S+)\\.tar\\.gz
"#
        .parse()
        .unwrap();

        assert_eq!(wf.entries().count(), 1);

        wf.add_entry(
            super::EntryBuilder::new("https://github.com/example/new")
                .matching_pattern(".*/v?(\\d+\\.\\d+)\\.tar\\.gz")
                .opt("compression", "xz")
                .version_policy("debian")
                .build(),
        );

        assert_eq!(wf.entries().count(), 2);

        let entries: Vec<_> = wf.entries().collect();
        assert_eq!(entries[0].url(), "https://example.com/old");
        assert_eq!(entries[1].url(), "https://github.com/example/new");
        assert_eq!(entries[1].version(), Ok(Some(VersionPolicy::Debian)));
    }

    #[test]
    fn test_entry_builder_formatting() {
        // Test that the builder produces correctly formatted entries
        let entry = super::EntryBuilder::new("https://github.com/example/tags")
            .matching_pattern(".*/v?(\\d\\S+)\\.tar\\.gz")
            .opt("compression", "xz")
            .flag("repack")
            .version_policy("debian")
            .script("uupdate")
            .build();

        let entry_str = entry.to_string();

        // Should start with opts=
        assert!(entry_str.starts_with("opts="));
        // Should contain the URL
        assert!(entry_str.contains("https://github.com/example/tags"));
        // Should contain the pattern
        assert!(entry_str.contains(".*/v?(\\d\\S+)\\.tar\\.gz"));
        // Should contain version policy
        assert!(entry_str.contains("debian"));
        // Should contain script
        assert!(entry_str.contains("uupdate"));
        // Should end with newline
        assert!(entry_str.ends_with('\n'));
    }

    #[test]
    fn test_watchfile_add_entry_preserves_format() {
        // Test that adding entries preserves the watchfile format
        let mut wf = super::WatchFile::new(Some(4));

        wf.add_entry(
            super::EntryBuilder::new("https://github.com/example/tags")
                .matching_pattern(".*/v?(\\d\\S+)\\.tar\\.gz")
                .build(),
        );

        let wf_str = wf.to_string();

        // Should have version line
        assert!(wf_str.starts_with("version=4\n"));
        // Should have the entry
        assert!(wf_str.contains("https://github.com/example/tags"));

        // Parse it back and ensure it's still valid
        let reparsed: super::WatchFile = wf_str.parse().unwrap();
        assert_eq!(reparsed.version(), 4);
        assert_eq!(reparsed.entries().count(), 1);
    }

    #[test]
    fn test_line_col() {
        let text = r#"version=4
opts=compression=xz https://example.com/releases (?:.*?/)?v?(\d[\d.]*)\.tar\.gz debian uupdate
"#;
        let wf = text.parse::<super::WatchFile>().unwrap();

        // Test version line position
        let version_node = wf.version_node().unwrap();
        assert_eq!(version_node.line(), 0);
        assert_eq!(version_node.column(), 0);
        assert_eq!(version_node.line_col(), (0, 0));

        // Test entry line numbers
        let entries: Vec<_> = wf.entries().collect();
        assert_eq!(entries.len(), 1);

        // Entry starts at line 1
        assert_eq!(entries[0].line(), 1);
        assert_eq!(entries[0].column(), 0);
        assert_eq!(entries[0].line_col(), (1, 0));

        // Test node accessors
        let option_list = entries[0].option_list().unwrap();
        assert_eq!(option_list.line(), 1); // Option list is on line 1

        let url_node = entries[0].url_node().unwrap();
        assert_eq!(url_node.line(), 1); // URL is on line 1

        let pattern_node = entries[0].matching_pattern_node().unwrap();
        assert_eq!(pattern_node.line(), 1); // Pattern is on line 1

        let version_policy_node = entries[0].version_node().unwrap();
        assert_eq!(version_policy_node.line(), 1); // Version policy is on line 1

        let script_node = entries[0].script_node().unwrap();
        assert_eq!(script_node.line(), 1); // Script is on line 1

        // Test individual option nodes
        let options: Vec<_> = option_list.options().collect();
        assert_eq!(options.len(), 1);
        assert_eq!(options[0].key(), Some("compression".to_string()));
        assert_eq!(options[0].value(), Some("xz".to_string()));
        assert_eq!(options[0].line(), 1); // Option is on line 1

        // Test find_option
        let compression_opt = option_list.find_option("compression").unwrap();
        assert_eq!(compression_opt.line(), 1);
        assert_eq!(compression_opt.column(), 5); // After "opts="
        assert_eq!(compression_opt.line_col(), (1, 5));
    }

    #[test]
    fn test_parse_str_relaxed() {
        let wf: super::WatchFile = super::WatchFile::from_str_relaxed(
            r#"version=4
ERRORS IN THIS LINE
opts=compression=xz https://example.com/releases (?:.*?/)?v?(\d
"#,
        );
        assert_eq!(wf.version(), 4);
        assert_eq!(wf.entries().count(), 2);

        let entries = wf.entries().collect::<Vec<_>>();

        let entry = &entries[0];
        assert_eq!(entry.url(), "ERRORS");

        let entry = &entries[1];
        assert_eq!(entry.url(), "https://example.com/releases");
        assert_eq!(entry.matching_pattern().as_deref(), Some("(?:.*?/)?v?(\\d"));
        assert_eq!(entry.get_option("compression"), Some("xz".to_string()));
    }

    #[test]
    fn test_parse_entry_with_comment_before() {
        // Regression test for https://bugs.debian.org/1128319:
        // A comment line before an entry with a continuation line was not parsed correctly
        // - the entry was silently dropped.
        let input = concat!(
            "version=4\n",
            "# try also https://pypi.debian.net/tomoscan/watch\n",
            "opts=uversionmangle=s/(rc|a|b|c)/~$1/;s/\\.dev/~dev/ \\\n",
            "https://pypi.debian.net/tomoscan/tomoscan-(.+)\\.(?:zip|tgz|tbz|txz|(?:tar\\.(?:gz|bz2|xz)))\n"
        );
        let wf: super::WatchFile = input.parse().unwrap();
        // The CST must cover the full input (round-trip invariant)
        assert_eq!(wf.to_string(), input);
        assert_eq!(wf.entries().count(), 1);
        let entry = wf.entries().next().unwrap();
        assert_eq!(
            entry.url(),
            "https://pypi.debian.net/tomoscan/tomoscan-(.+)\\.(?:zip|tgz|tbz|txz|(?:tar\\.(?:gz|bz2|xz)))"
        );
        assert_eq!(
            entry.get_option("uversionmangle"),
            Some("s/(rc|a|b|c)/~$1/;s/\\.dev/~dev/".to_string())
        );
    }

    #[test]
    fn test_parse_multiple_comments_before_entry() {
        // Multiple consecutive comment lines before an entry should all be preserved
        // and the entry should still be parsed correctly.
        let input = concat!(
            "version=4\n",
            "# first comment\n",
            "# second comment\n",
            "# third comment\n",
            "https://example.com/foo foo-(.*).tar.gz\n",
        );
        let wf: super::WatchFile = input.parse().unwrap();
        assert_eq!(wf.to_string(), input);
        assert_eq!(wf.entries().count(), 1);
        assert_eq!(
            wf.entries().next().unwrap().url(),
            "https://example.com/foo"
        );
    }

    #[test]
    fn test_parse_blank_lines_between_entries() {
        // Blank lines between entries should be preserved and all entries parsed.
        let input = concat!(
            "version=4\n",
            "https://example.com/foo .*/foo-(\\d+)\\.tar\\.gz\n",
            "\n",
            "https://example.com/bar .*/bar-(\\d+)\\.tar\\.gz\n",
        );
        let wf: super::WatchFile = input.parse().unwrap();
        assert_eq!(wf.to_string(), input);
        assert_eq!(wf.entries().count(), 2);
    }

    #[test]
    fn test_parse_trailing_unparseable_tokens_produce_error() {
        // Any tokens that remain after all entries are parsed should be captured
        // in an ERROR node so the CST covers the full input, and an error is reported.
        let input = "version=4\nhttps://example.com/foo foo-(.*).tar.gz\n=garbage\n";
        let result = input.parse::<super::WatchFile>();
        assert!(result.is_err(), "expected parse error for trailing garbage");
        // Verify the round-trip via from_str_relaxed: the CST must cover all input.
        let wf = super::WatchFile::from_str_relaxed(input);
        assert_eq!(wf.to_string(), input);
    }

    #[test]
    fn test_parse_roundtrip_full_file() {
        // The CST must always cover the full input, so to_string() == original input.
        let inputs = [
            "version=4\nhttps://example.com/foo foo-(.*).tar.gz\n",
            "version=4\n# a comment\nhttps://example.com/foo foo-(.*).tar.gz\n",
            concat!(
                "version=4\n",
                "opts=uversionmangle=s/rc/~rc/ \\\n",
                "  https://example.com/foo foo-(.*).tar.gz\n",
            ),
            concat!(
                "version=4\n",
                "# comment before entry\n",
                "opts=uversionmangle=s/rc/~rc/ \\\n",
                "https://example.com/foo foo-(.*).tar.gz\n",
                "# comment between entries\n",
                "https://example.com/bar bar-(.*).tar.gz\n",
            ),
        ];
        for input in &inputs {
            let wf: super::WatchFile = input.parse().unwrap();
            assert_eq!(
                wf.to_string(),
                *input,
                "round-trip failed for input: {:?}",
                input
            );
        }
    }
}