Loading...
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
# SPDX-License-Identifier: GPL-2.0+
#
# Copyright 2025 Canonical Ltd.
# Written by Simon Glass <simon.glass@canonical.com>
#
# pylint: disable=too-many-lines
"""Tests for pickman."""

import asyncio
import argparse
import os
import shutil
import sqlite3
import subprocess
import sys
import tempfile
import unittest
from unittest import mock

# Allow 'from pickman import xxx' to work via symlink
our_path = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, os.path.join(our_path, '..'))

# pylint: disable=wrong-import-position,import-error,cyclic-import
from u_boot_pylib import command
from u_boot_pylib import terminal
from u_boot_pylib import tools
from u_boot_pylib import tout

from pickman import __main__ as pickman
from pickman import agent
from pickman import control
from pickman import database
from pickman import gitlab_api as gitlab

# Test URL constants
TEST_OAUTH_URL = 'https://oauth2:test-token@gitlab.com/group/project.git'
TEST_HTTPS_URL = 'https://gitlab.com/group/project.git'
TEST_SSH_URL = 'git@gitlab.com:group/project.git'
TEST_MR_URL = 'https://gitlab.com/group/project/-/merge_requests/42'
TEST_MR_42_URL = 'https://gitlab.com/mr/42'
TEST_MR_1_URL = 'https://gitlab.com/mr/1'
TEST_SHORT_OAUTH_URL = 'https://oauth2:token@gitlab.com/g/p.git'


class TestCommit(unittest.TestCase):
    """Tests for the Commit namedtuple."""

    def test_commit_fields(self):
        """Test Commit namedtuple has correct fields."""
        commit = control.Commit(
            'abc123def456',
            'abc123d',
            'Test commit subject',
            '2024-01-15 10:30:00 -0600'
        )
        self.assertEqual(commit.hash, 'abc123def456')
        self.assertEqual(commit.chash, 'abc123d')
        self.assertEqual(commit.subject, 'Test commit subject')
        self.assertEqual(commit.date, '2024-01-15 10:30:00 -0600')


class TestRunGit(unittest.TestCase):
    """Tests for run_git function."""

    def test_run_git(self):
        """Test run_git returns stripped output."""
        result = command.CommandResult(stdout='  output with spaces  \n')
        command.TEST_RESULT = result
        try:
            with terminal.capture():
                out = control.run_git(['status'])
            self.assertEqual(out, 'output with spaces')
        finally:
            command.TEST_RESULT = None


class TestCompareBranches(unittest.TestCase):
    """Tests for compare_branches function."""

    def test_compare_branches(self):
        """Test compare_branches returns correct count and commit."""
        results = iter([
            '42',  # rev-list --count
            'abc123def456789',  # merge-base
            'abc123def456789\nabc123d\nTest subject\n2024-01-15 10:30:00 -0600',
        ])

        def handle_command(**_):
            return command.CommandResult(stdout=next(results))

        command.TEST_RESULT = handle_command
        try:
            with terminal.capture():
                count, commit = control.compare_branches('master', 'source')

            self.assertEqual(count, 42)
            self.assertEqual(commit.hash, 'abc123def456789')
            self.assertEqual(commit.chash, 'abc123d')
            self.assertEqual(commit.subject, 'Test subject')
            self.assertEqual(commit.date, '2024-01-15 10:30:00 -0600')
        finally:
            command.TEST_RESULT = None

    def test_compare_branches_zero_commits(self):
        """Test compare_branches with zero commit difference."""
        results = iter([
            '0',
            'def456abc789',
            'def456abc789\ndef456a\nMerge commit\n2024-02-20 14:00:00 -0500',
        ])

        def handle_command(**_):
            return command.CommandResult(stdout=next(results))

        command.TEST_RESULT = handle_command
        try:
            with terminal.capture():
                count, commit = control.compare_branches('branch1', 'branch2')

            self.assertEqual(count, 0)
            self.assertEqual(commit.chash, 'def456a')
        finally:
            command.TEST_RESULT = None


class TestParseArgs(unittest.TestCase):
    """Tests for parse_args function."""

    def test_parse_add_source(self):
        """Test parsing add-source command."""
        args = pickman.parse_args(['add-source', 'us/next'])
        self.assertEqual(args.cmd, 'add-source')
        self.assertEqual(args.source, 'us/next')

    def test_parse_apply(self):
        """Test parsing apply command."""
        args = pickman.parse_args(['apply', 'us/next'])
        self.assertEqual(args.cmd, 'apply')
        self.assertEqual(args.source, 'us/next')
        self.assertIsNone(args.branch)

    def test_parse_apply_with_branch(self):
        """Test parsing apply command with branch."""
        args = pickman.parse_args(['apply', 'us/next', '-b', 'my-branch'])
        self.assertEqual(args.cmd, 'apply')
        self.assertEqual(args.source, 'us/next')
        self.assertEqual(args.branch, 'my-branch')

    def test_parse_commit_source(self):
        """Test parsing commit-source command."""
        args = pickman.parse_args(['commit-source', 'us/next', 'abc123'])
        self.assertEqual(args.cmd, 'commit-source')
        self.assertEqual(args.source, 'us/next')
        self.assertEqual(args.commit, 'abc123')

    def test_parse_compare(self):
        """Test parsing compare command."""
        args = pickman.parse_args(['compare'])
        self.assertEqual(args.cmd, 'compare')

    def test_parse_test(self):
        """Test parsing test command."""
        args = pickman.parse_args(['test'])
        self.assertEqual(args.cmd, 'test')

    def test_parse_no_command(self):
        """Test parsing with no command raises error."""
        with terminal.capture():
            with self.assertRaises(SystemExit):
                pickman.parse_args([])


class TestMain(unittest.TestCase):
    """Tests for main function."""

    def test_add_source(self):
        """Test add-source command"""
        results = iter([
            'abc123def456',  # merge-base
            'abc123d\nTest subject',  # log
        ])

        def handle_command(**_):
            return command.CommandResult(stdout=next(results))

        # Use a temp database file
        fd, db_path = tempfile.mkstemp(suffix='.db')
        os.close(fd)
        os.unlink(db_path)
        old_db_fname = control.DB_FNAME
        control.DB_FNAME = db_path
        database.Database.instances.clear()

        command.TEST_RESULT = handle_command
        try:
            args = argparse.Namespace(cmd='add-source', source='us/next')
            with terminal.capture() as (stdout, _):
                ret = control.do_pickman(args)
            self.assertEqual(ret, 0)
            output = stdout.getvalue()
            self.assertIn("Added source 'us/next' with base commit:", output)
            self.assertIn('Hash:    abc123d', output)
            self.assertIn('Subject: Test subject', output)

            # Verify database was updated
            database.Database.instances.clear()
            dbs = database.Database(db_path)
            dbs.start()
            self.assertEqual(dbs.source_get('us/next'), 'abc123def456')
            dbs.close()
        finally:
            command.TEST_RESULT = None
            control.DB_FNAME = old_db_fname
            if os.path.exists(db_path):
                os.unlink(db_path)
            database.Database.instances.clear()

    def test_main_compare(self):
        """Test main with compare command."""
        results = iter([
            '10',
            'abc123',
            'abc123\nabc\nSubject\n2024-01-01 00:00:00 -0000',
        ])

        def handle_command(**_):
            return command.CommandResult(stdout=next(results))

        # Use a temp database file
        fd, db_path = tempfile.mkstemp(suffix='.db')
        os.close(fd)
        os.unlink(db_path)
        old_db_fname = control.DB_FNAME
        control.DB_FNAME = db_path
        database.Database.instances.clear()

        command.TEST_RESULT = handle_command
        try:
            with terminal.capture() as (stdout, _):
                ret = pickman.main(['compare'])
            self.assertEqual(ret, 0)
            # Filter out database migration messages
            output_lines = [l for l in stdout.getvalue().splitlines()
                            if not l.startswith(('Update database',
                                                'Creating'))]
            lines = iter(output_lines)
            self.assertEqual('Commits in us/next not in ci/master: 10',
                             next(lines))
            self.assertEqual('', next(lines))
            self.assertEqual('Last common commit:', next(lines))
            self.assertEqual('  Hash:    abc', next(lines))
            self.assertEqual('  Subject: Subject', next(lines))
            self.assertEqual('  Date:    2024-01-01 00:00:00 -0000',
                             next(lines))
            self.assertRaises(StopIteration, next, lines)
        finally:
            command.TEST_RESULT = None
            control.DB_FNAME = old_db_fname
            if os.path.exists(db_path):
                os.unlink(db_path)
            database.Database.instances.clear()


class TestDatabase(unittest.TestCase):
    """Tests for Database class."""

    def setUp(self):
        """Set up test fixtures."""
        fd, self.db_path = tempfile.mkstemp(suffix='.db')
        os.close(fd)
        os.unlink(self.db_path)  # Remove so database creates it fresh
        database.Database.instances.clear()

    def tearDown(self):
        """Clean up test fixtures."""
        if os.path.exists(self.db_path):
            os.unlink(self.db_path)
        database.Database.instances.clear()

    def test_create_database(self):
        """Test creating a new database."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            self.assertTrue(dbs.is_open)
            self.assertEqual(dbs.get_schema_version(), database.LATEST)
            dbs.close()

    def test_source_get_empty(self):
        """Test getting source from empty database."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            result = dbs.source_get('us/next')
            self.assertIsNone(result)
            dbs.close()

    def test_source_set_and_get(self):
        """Test setting and getting source commit."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'abc123def456')
            dbs.commit()
            result = dbs.source_get('us/next')
            self.assertEqual(result, 'abc123def456')
            dbs.close()

    def test_source_update(self):
        """Test updating source commit."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'abc123')
            dbs.commit()
            dbs.source_set('us/next', 'def456')
            dbs.commit()
            result = dbs.source_get('us/next')
            self.assertEqual(result, 'def456')
            dbs.close()

    def test_get_instance(self):
        """Test get_instance returns same database."""
        with terminal.capture():
            dbs1, created1 = database.Database.get_instance(self.db_path)
            dbs1.start()
            dbs2, created2 = database.Database.get_instance(self.db_path)
            self.assertTrue(created1)
            self.assertFalse(created2)
            self.assertIs(dbs1, dbs2)
            dbs1.close()

    def test_duplicate_database_error(self):
        """Test creating duplicate database raises error."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            with self.assertRaises(ValueError) as ctx:
                database.Database(self.db_path)
            self.assertIn('already a database', str(ctx.exception))
            dbs.close()

    def test_open_already_open_error(self):
        """Test opening already open database raises error."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            with self.assertRaises(ValueError) as ctx:
                dbs.open_it()
            self.assertIn('Already open', str(ctx.exception))
            dbs.close()

    def test_close_already_closed_error(self):
        """Test closing already closed database raises error."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.close()
            with self.assertRaises(ValueError) as ctx:
                dbs.close()
            self.assertIn('Already closed', str(ctx.exception))

    def test_rollback(self):
        """Test rollback discards uncommitted changes."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'abc123')
            dbs.commit()

            # Make a change but don't commit
            dbs.source_set('us/next', 'def456')
            # Rollback should discard the change
            dbs.rollback()

            result = dbs.source_get('us/next')
            self.assertEqual(result, 'abc123')
            dbs.close()

    def test_source_get_all(self):
        """Test getting all sources."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()

            # Empty initially
            self.assertEqual(dbs.source_get_all(), [])

            # Add some sources
            dbs.source_set('branch-a', 'abc123')
            dbs.source_set('branch-b', 'def456')
            dbs.commit()

            # Should be sorted by name
            sources = dbs.source_get_all()
            self.assertEqual(len(sources), 2)
            self.assertEqual(sources[0], ('branch-a', 'abc123'))
            self.assertEqual(sources[1], ('branch-b', 'def456'))
            dbs.close()

    def test_schema_version_readonly_raises(self):
        """Test that a read-only database raises instead of returning 0.

        Previously get_schema_version() caught all OperationalError and
        returned 0, which caused migrate_to() to re-create all tables on
        top of an existing (read-only) database, wiping the data.
        """
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'abc123')
            dbs.commit()

            # Simulate a read-only error by replacing the cursor
            real_cur = dbs.cur
            mock_cur = mock.MagicMock()
            mock_cur.execute.side_effect = sqlite3.OperationalError(
                'attempt to write a readonly database')
            dbs.cur = mock_cur
            with self.assertRaises(sqlite3.OperationalError):
                dbs.get_schema_version()
            dbs.cur = real_cur
            dbs.close()

    def test_schema_version_missing_table_returns_zero(self):
        """Test that a missing schema_version table returns 0."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.open_it()
            # Fresh database has no tables, should return 0
            self.assertEqual(dbs.get_schema_version(), 0)
            dbs.close()


class TestDatabaseCommit(unittest.TestCase):
    """Tests for Database commit functions."""

    def setUp(self):
        """Set up test fixtures."""
        fd, self.db_path = tempfile.mkstemp(suffix='.db')
        os.close(fd)
        os.unlink(self.db_path)
        database.Database.instances.clear()

    def tearDown(self):
        """Clean up test fixtures."""
        if os.path.exists(self.db_path):
            os.unlink(self.db_path)
        database.Database.instances.clear()

    def test_commit_add_and_get(self):
        """Test adding and getting a commit."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()

            # First add a source
            dbs.source_set('us/next', 'base123')
            dbs.commit()
            source_id = dbs.source_get_id('us/next')

            # Add a commit
            dbs.commit_add('abc123def456', source_id, 'Test subject',
                           'Author Name')
            dbs.commit()

            # Get the commit
            result = dbs.commit_get('abc123def456')
            self.assertIsNotNone(result)
            self.assertEqual(result[1], 'abc123def456')  # chash
            self.assertEqual(result[2], source_id)  # source_id
            self.assertIsNone(result[3])  # mergereq_id
            self.assertEqual(result[4], 'Test subject')  # subject
            self.assertEqual(result[5], 'Author Name')  # author
            self.assertEqual(result[6], 'pending')  # status
            dbs.close()

    def test_commit_get_not_found(self):
        """Test getting a non-existent commit."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            result = dbs.commit_get('nonexistent')
            self.assertIsNone(result)
            dbs.close()

    def test_commit_get_by_source(self):
        """Test getting commits by source."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()

            # Add a source
            dbs.source_set('us/next', 'base123')
            dbs.commit()
            source_id = dbs.source_get_id('us/next')

            # Add commits
            dbs.commit_add('commit1', source_id, 'Subject 1', 'Author 1')
            dbs.commit_add('commit2', source_id, 'Subject 2', 'Author 2',
                           status='applied')
            dbs.commit_add('commit3', source_id, 'Subject 3', 'Author 3')
            dbs.commit()

            # Get all commits for source
            commits = dbs.commit_get_by_source(source_id)
            self.assertEqual(len(commits), 3)

            # Get only pending commits
            pending = dbs.commit_get_by_source(source_id, status='pending')
            self.assertEqual(len(pending), 2)

            # Get only applied commits
            applied = dbs.commit_get_by_source(source_id, status='applied')
            self.assertEqual(len(applied), 1)
            self.assertEqual(applied[0][1], 'commit2')
            dbs.close()

    def test_commit_set_status(self):
        """Test updating commit status."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()

            dbs.source_set('us/next', 'base123')
            dbs.commit()
            source_id = dbs.source_get_id('us/next')

            dbs.commit_add('abc123', source_id, 'Subject', 'Author')
            dbs.commit()

            # Update status
            dbs.commit_set_status('abc123', 'applied')
            dbs.commit()

            result = dbs.commit_get('abc123')
            self.assertEqual(result[6], 'applied')
            dbs.close()

    def test_commit_set_status_with_cherry_hash(self):
        """Test updating commit status with cherry hash."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()

            dbs.source_set('us/next', 'base123')
            dbs.commit()
            source_id = dbs.source_get_id('us/next')

            dbs.commit_add('abc123', source_id, 'Subject', 'Author')
            dbs.commit()

            # Update status with cherry hash
            dbs.commit_set_status('abc123', 'applied', cherry_hash='xyz789')
            dbs.commit()

            result = dbs.commit_get('abc123')
            self.assertEqual(result[6], 'applied')
            self.assertEqual(result[7], 'xyz789')  # cherry_hash
            dbs.close()

    def test_source_get_id(self):
        """Test getting source id by name."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()

            # Not found initially
            self.assertIsNone(dbs.source_get_id('us/next'))

            # Add source and get id
            dbs.source_set('us/next', 'abc123')
            dbs.commit()

            source_id = dbs.source_get_id('us/next')
            self.assertIsNotNone(source_id)
            self.assertIsInstance(source_id, int)
            dbs.close()


class TestDatabaseMergereq(unittest.TestCase):
    """Tests for Database mergereq functions."""

    def setUp(self):
        """Set up test fixtures."""
        fd, self.db_path = tempfile.mkstemp(suffix='.db')
        os.close(fd)
        os.unlink(self.db_path)
        database.Database.instances.clear()

    def tearDown(self):
        """Clean up test fixtures."""
        if os.path.exists(self.db_path):
            os.unlink(self.db_path)
        database.Database.instances.clear()

    def test_mergereq_add_and_get(self):
        """Test adding and getting a merge request."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()

            # Add a source
            dbs.source_set('us/next', 'base123')
            dbs.commit()
            source_id = dbs.source_get_id('us/next')

            # Add a merge request
            dbs.mergereq_add(source_id, 'cherry-abc123', 42, 'open',
                             TEST_MR_42_URL, '2025-01-15')
            dbs.commit()

            # Get the merge request
            result = dbs.mergereq_get(42)
            self.assertIsNotNone(result)
            self.assertEqual(result[1], source_id)  # source_id
            self.assertEqual(result[2], 'cherry-abc123')  # branch_name
            self.assertEqual(result[3], 42)  # mr_id
            self.assertEqual(result[4], 'open')  # status
            self.assertEqual(result[5], TEST_MR_42_URL)  # url
            self.assertEqual(result[6], '2025-01-15')  # created_at
            dbs.close()

    def test_mergereq_get_not_found(self):
        """Test getting a non-existent merge request."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            result = dbs.mergereq_get(999)
            self.assertIsNone(result)
            dbs.close()

    def test_mergereq_get_by_source(self):
        """Test getting merge requests by source."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()

            # Add a source
            dbs.source_set('us/next', 'base123')
            dbs.commit()
            source_id = dbs.source_get_id('us/next')

            # Add merge requests
            dbs.mergereq_add(source_id, 'branch-1', 1, 'open',
                             TEST_MR_1_URL, '2025-01-01')
            dbs.mergereq_add(source_id, 'branch-2', 2, 'merged',
                             'https://gitlab.com/mr/2', '2025-01-02')
            dbs.mergereq_add(source_id, 'branch-3', 3, 'open',
                             'https://gitlab.com/mr/3', '2025-01-03')
            dbs.commit()

            # Get all merge requests for source
            mrs = dbs.mergereq_get_by_source(source_id)
            self.assertEqual(len(mrs), 3)

            # Get only open merge requests
            open_mrs = dbs.mergereq_get_by_source(source_id, status='open')
            self.assertEqual(len(open_mrs), 2)

            # Get only merged
            merged = dbs.mergereq_get_by_source(source_id, status='merged')
            self.assertEqual(len(merged), 1)
            self.assertEqual(merged[0][3], 2)  # mr_id
            dbs.close()

    def test_mergereq_set_status(self):
        """Test updating merge request status."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()

            dbs.source_set('us/next', 'base123')
            dbs.commit()
            source_id = dbs.source_get_id('us/next')

            dbs.mergereq_add(source_id, 'branch-1', 42, 'open',
                             TEST_MR_42_URL, '2025-01-15')
            dbs.commit()

            # Update status
            dbs.mergereq_set_status(42, 'merged')
            dbs.commit()

            result = dbs.mergereq_get(42)
            self.assertEqual(result[4], 'merged')
            dbs.close()


class TestDatabaseCommitMergereq(unittest.TestCase):
    """Tests for commit-mergereq relationship."""

    def setUp(self):
        """Set up test fixtures."""
        fd, self.db_path = tempfile.mkstemp(suffix='.db')
        os.close(fd)
        os.unlink(self.db_path)
        database.Database.instances.clear()

    def tearDown(self):
        """Clean up test fixtures."""
        if os.path.exists(self.db_path):
            os.unlink(self.db_path)
        database.Database.instances.clear()

    def test_commit_set_mergereq(self):
        """Test setting merge request for a commit."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()

            # Add source
            dbs.source_set('us/next', 'base123')
            dbs.commit()
            source_id = dbs.source_get_id('us/next')

            # Add merge request
            dbs.mergereq_add(source_id, 'branch-1', 42, 'open',
                             TEST_MR_42_URL, '2025-01-15')
            dbs.commit()
            mr = dbs.mergereq_get(42)
            mr_id = mr[0]  # id field

            # Add commit without mergereq
            dbs.commit_add('abc123', source_id, 'Subject', 'Author')
            dbs.commit()

            # Set mergereq
            dbs.commit_set_mergereq('abc123', mr_id)
            dbs.commit()

            result = dbs.commit_get('abc123')
            self.assertEqual(result[3], mr_id)  # mergereq_id
            dbs.close()

    def test_commit_get_by_mergereq(self):
        """Test getting commits by merge request."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()

            # Add source
            dbs.source_set('us/next', 'base123')
            dbs.commit()
            source_id = dbs.source_get_id('us/next')

            # Add merge request
            dbs.mergereq_add(source_id, 'branch-1', 42, 'open',
                             TEST_MR_42_URL, '2025-01-15')
            dbs.commit()
            mr = dbs.mergereq_get(42)
            mr_id = mr[0]

            # Add commits with mergereq_id
            dbs.commit_add('commit1', source_id, 'Subject 1', 'Author 1',
                           mergereq_id=mr_id)
            dbs.commit_add('commit2', source_id, 'Subject 2', 'Author 2',
                           mergereq_id=mr_id)
            dbs.commit_add('commit3', source_id, 'Subject 3', 'Author 3')
            dbs.commit()

            # Get commits for merge request
            commits = dbs.commit_get_by_mergereq(mr_id)
            self.assertEqual(len(commits), 2)
            hashes = [c[1] for c in commits]
            self.assertIn('commit1', hashes)
            self.assertIn('commit2', hashes)
            self.assertNotIn('commit3', hashes)
            dbs.close()


class TestDatabaseComment(unittest.TestCase):
    """Tests for Database comment functions."""

    def setUp(self):
        """Set up test fixtures."""
        fd, self.db_path = tempfile.mkstemp(suffix='.db')
        os.close(fd)
        os.unlink(self.db_path)

    def tearDown(self):
        """Clean up test fixtures."""
        if os.path.exists(self.db_path):
            os.unlink(self.db_path)
        database.Database.instances.clear()

    def test_comment_mark_and_check_processed(self):
        """Test marking and checking processed comments"""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()

            # Comment should not be processed initially
            self.assertFalse(dbs.comment_is_processed(123, 456))

            # Mark as processed
            dbs.comment_mark_processed(123, 456)
            dbs.commit()

            # Now should be processed
            self.assertTrue(dbs.comment_is_processed(123, 456))

            # Different comment should not be processed
            self.assertFalse(dbs.comment_is_processed(123, 789))
            self.assertFalse(dbs.comment_is_processed(999, 456))

            dbs.close()

    def test_comment_get_processed(self):
        """Test getting all processed comments for an MR"""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()

            # Mark several comments as processed
            dbs.comment_mark_processed(100, 1)
            dbs.comment_mark_processed(100, 2)
            dbs.comment_mark_processed(100, 3)
            dbs.comment_mark_processed(200, 10)  # Different MR
            dbs.commit()

            # Get processed for MR 100
            processed = dbs.comment_get_processed(100)
            self.assertEqual(len(processed), 3)
            self.assertIn(1, processed)
            self.assertIn(2, processed)
            self.assertIn(3, processed)
            self.assertNotIn(10, processed)

            # Get processed for MR 200
            processed = dbs.comment_get_processed(200)
            self.assertEqual(len(processed), 1)
            self.assertIn(10, processed)

            dbs.close()

    def test_comment_mark_processed_idempotent(self):
        """Test that marking same comment twice doesn't fail"""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()

            # Mark same comment twice (should not raise)
            dbs.comment_mark_processed(123, 456)
            dbs.comment_mark_processed(123, 456)
            dbs.commit()

            # Should still be processed
            self.assertTrue(dbs.comment_is_processed(123, 456))

            dbs.close()


class TestDatabasePipelineFix(unittest.TestCase):
    """Tests for Database pipeline_fix functions."""

    def setUp(self):
        """Set up test fixtures."""
        fd, self.db_path = tempfile.mkstemp(suffix='.db')
        os.close(fd)
        os.unlink(self.db_path)

    def tearDown(self):
        """Clean up test fixtures."""
        if os.path.exists(self.db_path):
            os.unlink(self.db_path)
        database.Database.instances.clear()

    def test_pfix_add(self):
        """Test adding a pipeline fix record"""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()

            dbs.pfix_add(123, 456, 1, 'success')
            dbs.commit()

            self.assertTrue(dbs.pfix_has(123, 456))

            dbs.close()

    def test_pfix_count(self):
        """Test counting pipeline fix attempts"""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()

            self.assertEqual(dbs.pfix_count(123), 0)

            dbs.pfix_add(123, 100, 1, 'failure')
            dbs.pfix_add(123, 200, 2, 'success')
            dbs.commit()

            self.assertEqual(dbs.pfix_count(123), 2)
            # Different MR should have 0
            self.assertEqual(dbs.pfix_count(999), 0)

            dbs.close()

    def test_pfix_has(self):
        """Test checking if a pipeline was already handled"""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()

            self.assertFalse(dbs.pfix_has(123, 456))

            dbs.pfix_add(123, 456, 1, 'success')
            dbs.commit()

            self.assertTrue(dbs.pfix_has(123, 456))
            # Different pipeline should not be handled
            self.assertFalse(dbs.pfix_has(123, 789))
            # Different MR should not be handled
            self.assertFalse(dbs.pfix_has(999, 456))

            dbs.close()

    def test_pfix_unique(self):
        """Test that duplicate mr_iid/pipeline_id pairs are ignored"""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()

            dbs.pfix_add(123, 456, 1, 'failure')
            dbs.commit()

            # Adding same pair again should not raise (OR IGNORE)
            dbs.pfix_add(123, 456, 2, 'success')
            dbs.commit()

            # Count should still be 1 (second insert ignored)
            self.assertEqual(dbs.pfix_count(123), 1)

            dbs.close()


class TestListSources(unittest.TestCase):
    """Tests for list-sources command."""

    def setUp(self):
        """Set up test fixtures."""
        fd, self.db_path = tempfile.mkstemp(suffix='.db')
        os.close(fd)
        os.unlink(self.db_path)
        self.old_db_fname = control.DB_FNAME
        control.DB_FNAME = self.db_path
        database.Database.instances.clear()

    def tearDown(self):
        """Clean up test fixtures."""
        control.DB_FNAME = self.old_db_fname
        if os.path.exists(self.db_path):
            os.unlink(self.db_path)
        database.Database.instances.clear()

    def test_list_sources_empty(self):
        """Test list-sources with no sources"""
        args = argparse.Namespace(cmd='list-sources')
        with terminal.capture() as (stdout, _):
            ret = control.do_pickman(args)
        self.assertEqual(ret, 0)
        self.assertIn('No source branches tracked', stdout.getvalue())

    def test_list_sources(self):
        """Test list-sources with sources"""
        # Add some sources first
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'abc123def456')
            dbs.source_set('other/branch', 'def456abc789')
            dbs.commit()
            dbs.close()

        database.Database.instances.clear()
        args = argparse.Namespace(cmd='list-sources')
        with terminal.capture() as (stdout, _):
            ret = control.do_pickman(args)
        self.assertEqual(ret, 0)
        output = stdout.getvalue()
        self.assertIn('Tracked source branches:', output)
        self.assertIn('other/branch: def456abc789', output)
        self.assertIn('us/next: abc123def456', output)


class TestNextSet(unittest.TestCase):
    """Tests for next-set command."""

    def setUp(self):
        """Set up test fixtures."""
        fd, self.db_path = tempfile.mkstemp(suffix='.db')
        os.close(fd)
        os.unlink(self.db_path)
        self.old_db_fname = control.DB_FNAME
        control.DB_FNAME = self.db_path
        database.Database.instances.clear()

    def tearDown(self):
        """Clean up test fixtures."""
        control.DB_FNAME = self.old_db_fname
        if os.path.exists(self.db_path):
            os.unlink(self.db_path)
        database.Database.instances.clear()
        command.TEST_RESULT = None

    def test_next_set_source_not_found(self):
        """Test next-set with unknown source"""
        # Create empty database first
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.close()

        database.Database.instances.clear()

        args = argparse.Namespace(cmd='next-set', source='unknown')
        with terminal.capture() as (_, stderr):
            ret = control.do_pickman(args)
        self.assertEqual(ret, 1)
        # Error goes to stderr
        self.assertIn("Source 'unknown' not found", stderr.getvalue())

    def test_next_set_no_commits(self):
        """Test next-set with no new commits"""
        # Add source to database
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'abc123')
            dbs.commit()
            dbs.close()

        database.Database.instances.clear()

        # Mock git log returning empty
        command.TEST_RESULT = command.CommandResult(stdout='')

        args = argparse.Namespace(cmd='next-set', source='us/next')
        with terminal.capture() as (stdout, _):
            ret = control.do_pickman(args)
        self.assertEqual(ret, 0)
        self.assertIn('No new commits to cherry-pick', stdout.getvalue())

    def test_next_set_with_merge(self):
        """Test next-set finding commits up to merge"""
        # Add source to database
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'abc123')
            dbs.commit()
            dbs.close()

        database.Database.instances.clear()

        # First-parent log (to find next merge on mainline)
        fp_log_output = (
            'aaa111|aaa111a|Author 1|First commit|abc123\n'
            'bbb222|bbb222b|Author 2|Second commit|aaa111\n'
            'ccc333|ccc333c|Author 3|Merge branch feature|bbb222 ddd444\n'
            'eee555|eee555e|Author 4|After merge|ccc333\n'
        )
        # Full log (to get all commits up to the merge)
        full_log_output = (
            'aaa111|aaa111a|Author 1|First commit|abc123\n'
            'bbb222|bbb222b|Author 2|Second commit|aaa111\n'
            'ccc333|ccc333c|Author 3|Merge branch feature|bbb222 ddd444\n'
        )

        def mock_git(pipe_list):
            cmd = pipe_list[0] if pipe_list else []
            if '--first-parent' in cmd and '--merges' in cmd:
                # detect_sub_merges: no sub-merges
                return command.CommandResult(stdout='')
            if '--first-parent' in cmd:
                return command.CommandResult(stdout=fp_log_output)
            if 'rev-parse' in cmd:
                # detect_sub_merges: return two parents (it's a merge)
                return command.CommandResult(stdout='bbb222\nddd444\n')
            return command.CommandResult(stdout=full_log_output)

        command.TEST_RESULT = mock_git

        args = argparse.Namespace(cmd='next-set', source='us/next')
        with terminal.capture() as (stdout, _):
            ret = control.do_pickman(args)
        self.assertEqual(ret, 0)
        output = stdout.getvalue()
        self.assertIn('Next set from us/next (3 commits):', output)
        self.assertIn('aaa111a First commit', output)
        self.assertIn('bbb222b Second commit', output)
        self.assertIn('ccc333c Merge branch feature', output)
        # Should not include commits after the merge
        self.assertNotIn('eee555e', output)

    def test_next_set_no_merge(self):
        """Test next-set with no merge commit found"""
        # Add source to database
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'abc123')
            dbs.commit()
            dbs.close()

        database.Database.instances.clear()

        # Mock git log without merge commits
        log_output = (
            'aaa111|aaa111a|Author 1|First commit|abc123\n'
            'bbb222|bbb222b|Author 2|Second commit|aaa111\n'
        )
        command.TEST_RESULT = command.CommandResult(stdout=log_output)

        args = argparse.Namespace(cmd='next-set', source='us/next')
        with terminal.capture() as (stdout, _):
            ret = control.do_pickman(args)
        self.assertEqual(ret, 0)
        output = stdout.getvalue()
        self.assertIn('Remaining commits from us/next (2 commits, '
                      'no merge found):', output)
        self.assertIn('aaa111a First commit', output)
        self.assertIn('bbb222b Second commit', output)


class TestNextMerges(unittest.TestCase):
    """Tests for next-merges command."""

    def setUp(self):
        """Set up test fixtures."""
        fd, self.db_path = tempfile.mkstemp(suffix='.db')
        os.close(fd)
        os.unlink(self.db_path)
        self.old_db_fname = control.DB_FNAME
        control.DB_FNAME = self.db_path
        database.Database.instances.clear()

    def tearDown(self):
        """Clean up test fixtures."""
        control.DB_FNAME = self.old_db_fname
        if os.path.exists(self.db_path):
            os.unlink(self.db_path)
        database.Database.instances.clear()
        command.TEST_RESULT = None

    def _make_simple_merge_mock(self, log_output):
        """Create a mock handler for merges with no sub-merges"""
        def mock_git(pipe_list):
            cmd = pipe_list[0] if pipe_list else []
            # Initial merge listing
            if '--reverse' in cmd and '--format=%H|%h|%s' in cmd:
                return command.CommandResult(stdout=log_output)
            # Sub-merge detection: no sub-merges
            if '--first-parent' in cmd and '--merges' in cmd:
                return command.CommandResult(stdout='')
            # Parent lookup for detect_sub_merges
            if 'rev-parse' in cmd:
                return command.CommandResult(
                    stdout='parent1\nparent2\n')
            return command.CommandResult(stdout='')
        return mock_git

    def test_next_merges(self):
        """Test next-merges shows upcoming merges"""
        # Add source to database
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'abc123')
            dbs.commit()
            dbs.close()

        database.Database.instances.clear()

        log_output = (
            'aaa111|aaa111a|Merge branch feature-1\n'
            'bbb222|bbb222b|Merge branch feature-2\n'
            'ccc333|ccc333c|Merge branch feature-3\n'
        )
        command.TEST_RESULT = self._make_simple_merge_mock(log_output)

        args = argparse.Namespace(cmd='next-merges', source='us/next', count=10)
        with terminal.capture() as (stdout, _):
            ret = control.do_pickman(args)
        self.assertEqual(ret, 0)
        output = stdout.getvalue()
        self.assertIn('3 from 3 first-parent', output)
        self.assertIn('1. aaa111a Merge branch feature-1', output)
        self.assertIn('2. bbb222b Merge branch feature-2', output)
        self.assertIn('3. ccc333c Merge branch feature-3', output)

    def test_next_merges_with_count(self):
        """Test next-merges respects count parameter"""
        # Add source to database
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'abc123')
            dbs.commit()
            dbs.close()

        database.Database.instances.clear()

        log_output = (
            'aaa111|aaa111a|Merge branch feature-1\n'
            'bbb222|bbb222b|Merge branch feature-2\n'
            'ccc333|ccc333c|Merge branch feature-3\n'
        )
        command.TEST_RESULT = self._make_simple_merge_mock(log_output)

        args = argparse.Namespace(cmd='next-merges', source='us/next', count=2)
        with terminal.capture() as (stdout, _):
            ret = control.do_pickman(args)
        self.assertEqual(ret, 0)
        output = stdout.getvalue()
        self.assertIn('2 from 2 first-parent', output)
        self.assertIn('1. aaa111a', output)
        self.assertIn('2. bbb222b', output)
        self.assertNotIn('3. ccc333c', output)

    def test_next_merges_expands_mega_merge(self):
        """Test next-merges expands mega-merges into sub-merges"""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'abc123')
            dbs.commit()
            dbs.close()

        database.Database.instances.clear()

        def mock_git(pipe_list):
            cmd = pipe_list[0] if pipe_list else []
            cmd_str = ' '.join(cmd)
            # Initial merge listing - one mega-merge
            if '--reverse' in cmd and '--format=%H|%h|%s' in cmd:
                return command.CommandResult(
                    stdout='mega111|mega111a|Merge branch next\n')
            # Parent lookup
            if 'rev-parse' in cmd and '^@' in cmd_str:
                return command.CommandResult(
                    stdout='first_parent\nsecond_parent\n')
            # Sub-merge detection on second parent chain
            if ('--first-parent' in cmd and '--merges' in cmd
                    and '--format=%H' in cmd):
                return command.CommandResult(
                    stdout='sub_aaa\nsub_bbb\n')
            # Sub-merge detail lookup
            if 'log' in cmd and '-1' in cmd and '--format=%h|%s' in cmd:
                if 'sub_aaa' in cmd_str:
                    return command.CommandResult(
                        stdout='sub_aaa1|Merge feature-A\n')
                if 'sub_bbb' in cmd_str:
                    return command.CommandResult(
                        stdout='sub_bbb1|Merge feature-B\n')
            return command.CommandResult(stdout='')

        command.TEST_RESULT = mock_git

        args = argparse.Namespace(cmd='next-merges', source='us/next', count=10)
        with terminal.capture() as (stdout, _):
            ret = control.do_pickman(args)
        self.assertEqual(ret, 0)
        output = stdout.getvalue()
        self.assertIn('2 from 1 first-parent', output)
        self.assertIn('mega111a Merge branch next', output)
        self.assertIn('2 sub-merges', output)
        self.assertIn('1. sub_aaa1 Merge feature-A', output)
        self.assertIn('2. sub_bbb1 Merge feature-B', output)

    def test_next_merges_no_merges(self):
        """Test next-merges with no merges remaining"""
        # Add source to database
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'abc123')
            dbs.commit()
            dbs.close()

        database.Database.instances.clear()

        command.TEST_RESULT = command.CommandResult(stdout='')

        args = argparse.Namespace(cmd='next-merges', source='us/next', count=10)
        with terminal.capture() as (stdout, _):
            ret = control.do_pickman(args)
        self.assertEqual(ret, 0)
        self.assertIn('No merges remaining', stdout.getvalue())


class TestCountMerges(unittest.TestCase):
    """Tests for count-merges command."""

    def setUp(self):
        """Set up test fixtures."""
        fd, self.db_path = tempfile.mkstemp(suffix='.db')
        os.close(fd)
        os.unlink(self.db_path)
        self.old_db_fname = control.DB_FNAME
        control.DB_FNAME = self.db_path
        database.Database.instances.clear()

    def tearDown(self):
        """Clean up test fixtures."""
        control.DB_FNAME = self.old_db_fname
        if os.path.exists(self.db_path):
            os.unlink(self.db_path)
        database.Database.instances.clear()
        command.TEST_RESULT = None

    def test_count_merges(self):
        """Test count-merges shows total remaining"""
        # Add source to database
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'abc123')
            dbs.commit()
            dbs.close()

        database.Database.instances.clear()

        # Mock git log with merge commits (oneline format)
        log_output = (
            'aaa111a Merge branch feature-1\n'
            'bbb222b Merge branch feature-2\n'
            'ccc333c Merge branch feature-3\n'
        )
        command.TEST_RESULT = command.CommandResult(stdout=log_output)

        args = argparse.Namespace(cmd='count-merges', source='us/next')
        with terminal.capture() as (stdout, _):
            ret = control.do_pickman(args)
        self.assertEqual(ret, 0)
        self.assertIn('3 merges remaining from us/next', stdout.getvalue())

    def test_count_merges_none(self):
        """Test count-merges with no merges remaining"""
        # Add source to database
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'abc123')
            dbs.commit()
            dbs.close()

        database.Database.instances.clear()

        command.TEST_RESULT = command.CommandResult(stdout='')

        args = argparse.Namespace(cmd='count-merges', source='us/next')
        with terminal.capture() as (stdout, _):
            ret = control.do_pickman(args)
        self.assertEqual(ret, 0)
        self.assertIn('0 merges remaining', stdout.getvalue())

    def test_count_merges_source_not_found(self):
        """Test count-merges with unknown source"""
        # Create empty database
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.close()

        database.Database.instances.clear()

        args = argparse.Namespace(cmd='count-merges', source='unknown')
        with terminal.capture() as (_, stderr):
            ret = control.do_pickman(args)
        self.assertEqual(ret, 1)
        self.assertIn("Source 'unknown' not found", stderr.getvalue())


class TestGetNextCommits(unittest.TestCase):
    """Tests for get_next_commits function."""

    def setUp(self):
        """Set up test fixtures."""
        fd, self.db_path = tempfile.mkstemp(suffix='.db')
        os.close(fd)
        os.unlink(self.db_path)
        self.old_db_fname = control.DB_FNAME
        control.DB_FNAME = self.db_path
        database.Database.instances.clear()

    def tearDown(self):
        """Clean up test fixtures."""
        control.DB_FNAME = self.old_db_fname
        if os.path.exists(self.db_path):
            os.unlink(self.db_path)
        database.Database.instances.clear()
        command.TEST_RESULT = None

    def test_get_next_commits_source_not_found(self):
        """Test get_next_commits with unknown source"""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            info, err = control.get_next_commits(dbs, 'unknown')
            self.assertIsNone(info)
            self.assertIn('not found', err)
            dbs.close()

    def test_get_next_commits_with_merge(self):
        """Test get_next_commits finding commits up to merge"""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'abc123')
            dbs.commit()

            # First-parent log (to find next merge on mainline)
            fp_log_output = (
                'aaa111|aaa111a|Author 1|First commit|abc123\n'
                'bbb222|bbb222b|Author 2|Merge branch|aaa111 ccc333\n'
                'ddd444|ddd444d|Author 3|After merge|bbb222\n'
            )
            # Full log (to get all commits up to the merge)
            full_log_output = (
                'aaa111|aaa111a|Author 1|First commit|abc123\n'
                'bbb222|bbb222b|Author 2|Merge branch|aaa111 ccc333\n'
            )

            def mock_git(pipe_list):
                cmd = pipe_list[0] if pipe_list else []
                if '--first-parent' in cmd and '--merges' in cmd:
                    # detect_sub_merges: no sub-merges
                    return command.CommandResult(stdout='')
                if '--first-parent' in cmd:
                    return command.CommandResult(stdout=fp_log_output)
                if 'rev-parse' in cmd:
                    # detect_sub_merges: return parents
                    return command.CommandResult(stdout='aaa111\nccc333\n')
                return command.CommandResult(stdout=full_log_output)

            command.TEST_RESULT = mock_git

            info, err = control.get_next_commits(dbs, 'us/next')
            self.assertIsNone(err)
            self.assertTrue(info.merge_found)
            self.assertEqual(len(info.commits), 2)
            self.assertEqual(info.commits[0].chash, 'aaa111a')
            self.assertEqual(info.commits[1].chash, 'bbb222b')
            dbs.close()


class TestApply(unittest.TestCase):
    """Tests for apply command."""

    def setUp(self):
        """Set up test fixtures."""
        fd, self.db_path = tempfile.mkstemp(suffix='.db')
        os.close(fd)
        os.unlink(self.db_path)
        self.old_db_fname = control.DB_FNAME
        control.DB_FNAME = self.db_path
        database.Database.instances.clear()

    def tearDown(self):
        """Clean up test fixtures."""
        control.DB_FNAME = self.old_db_fname
        if os.path.exists(self.db_path):
            os.unlink(self.db_path)
        database.Database.instances.clear()
        command.TEST_RESULT = None

    def test_apply_source_not_found(self):
        """Test apply with unknown source"""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.close()

        database.Database.instances.clear()

        args = argparse.Namespace(cmd='apply', source='unknown', branch=None,
                                  remote='ci', target='master')
        with terminal.capture() as (_, stderr):
            ret = control.do_pickman(args)
        self.assertEqual(ret, 1)
        self.assertIn("Source 'unknown' not found", stderr.getvalue())

    def test_apply_no_commits(self):
        """Test apply with no new commits"""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'abc123')
            dbs.commit()
            dbs.close()

        database.Database.instances.clear()
        command.TEST_RESULT = command.CommandResult(stdout='')

        args = argparse.Namespace(cmd='apply', source='us/next', branch=None,
                                  remote='ci', target='master')
        with terminal.capture() as (stdout, _):
            ret = control.do_pickman(args)
        self.assertEqual(ret, 0)
        self.assertIn('No new commits to cherry-pick', stdout.getvalue())


class TestCommitSource(unittest.TestCase):
    """Tests for commit-source command."""

    def setUp(self):
        """Set up test fixtures."""
        fd, self.db_path = tempfile.mkstemp(suffix='.db')
        os.close(fd)
        os.unlink(self.db_path)
        self.old_db_fname = control.DB_FNAME
        control.DB_FNAME = self.db_path
        database.Database.instances.clear()

    def tearDown(self):
        """Clean up test fixtures."""
        control.DB_FNAME = self.old_db_fname
        if os.path.exists(self.db_path):
            os.unlink(self.db_path)
        database.Database.instances.clear()
        command.TEST_RESULT = None

    def test_commit_source_not_found(self):
        """Test commit-source with unknown source."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.close()

        database.Database.instances.clear()
        command.TEST_RESULT = command.CommandResult(stdout='fullhash123')

        args = argparse.Namespace(cmd='commit-source', source='unknown',
                                  commit='abc123')
        with terminal.capture() as (_, stderr):
            ret = control.do_pickman(args)
        self.assertEqual(ret, 1)
        self.assertIn("Source 'unknown' not found", stderr.getvalue())

    def test_commit_source_success(self):
        """Test commit-source updates database."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'oldcommit12345')
            dbs.commit()
            dbs.close()

        database.Database.instances.clear()
        command.TEST_RESULT = command.CommandResult(stdout='newcommit67890')

        args = argparse.Namespace(cmd='commit-source', source='us/next',
                                  commit='abc123')
        with terminal.capture() as (stdout, _):
            ret = control.do_pickman(args)
        self.assertEqual(ret, 0)
        self.assertIn('oldcommit123', stdout.getvalue())
        self.assertIn('newcommit678', stdout.getvalue())


class TestParseUrl(unittest.TestCase):
    """Tests for parse_url function."""

    def test_parse_ssh_url(self):
        """Test parsing SSH URL."""
        host, path = gitlab.parse_url(
            'git@gitlab.com:group/project.git')
        self.assertEqual(host, 'gitlab.com')
        self.assertEqual(path, 'group/project')

    def test_parse_ssh_url_no_git_suffix(self):
        """Test parsing SSH URL without .git suffix."""
        host, path = gitlab.parse_url(
            'git@gitlab.com:group/project')
        self.assertEqual(host, 'gitlab.com')
        self.assertEqual(path, 'group/project')

    def test_parse_ssh_url_nested_group(self):
        """Test parsing SSH URL with nested group."""
        host, path = gitlab.parse_url(
            'git@gitlab.denx.de:u-boot/custodians/u-boot-dm.git')
        self.assertEqual(host, 'gitlab.denx.de')
        self.assertEqual(path, 'u-boot/custodians/u-boot-dm')

    def test_parse_https_url(self):
        """Test parsing HTTPS URL."""
        host, path = gitlab.parse_url(
            'https://gitlab.com/group/project.git')
        self.assertEqual(host, 'gitlab.com')
        self.assertEqual(path, 'group/project')

    def test_parse_https_url_no_git_suffix(self):
        """Test parsing HTTPS URL without .git suffix."""
        host, path = gitlab.parse_url(
            'https://gitlab.com/group/project')
        self.assertEqual(host, 'gitlab.com')
        self.assertEqual(path, 'group/project')

    def test_parse_http_url(self):
        """Test parsing HTTP URL."""
        host, path = gitlab.parse_url(
            'http://gitlab.example.com/group/project.git')
        self.assertEqual(host, 'gitlab.example.com')
        self.assertEqual(path, 'group/project')

    def test_parse_invalid_url(self):
        """Test parsing invalid URL."""
        host, path = gitlab.parse_url('not-a-valid-url')
        self.assertIsNone(host)
        self.assertIsNone(path)

    def test_parse_empty_url(self):
        """Test parsing empty URL."""
        host, path = gitlab.parse_url('')
        self.assertIsNone(host)
        self.assertIsNone(path)


class TestCheckAvailable(unittest.TestCase):
    """Tests for GitLab availability checks."""

    def test_check_available_false(self):
        """Test check_available returns False when gitlab not installed."""
        with mock.patch.object(gitlab, 'AVAILABLE', False):
            with terminal.capture():
                result = gitlab.check_available()
            self.assertFalse(result)

    def test_check_available_true(self):
        """Test check_available returns True when gitlab is installed."""
        with mock.patch.object(gitlab, 'AVAILABLE', True):
            with terminal.capture():
                result = gitlab.check_available()
            self.assertTrue(result)


class TestGetPushUrl(unittest.TestCase):
    """Tests for get_push_url function."""

    def test_get_push_url_success(self):
        """Test successful push URL generation."""
        with mock.patch.object(gitlab, 'get_token',
                               return_value='test-token'):
            with mock.patch.object(
                    gitlab, 'get_remote_url',
                    return_value=TEST_SSH_URL):
                url = gitlab.get_push_url('origin')
        self.assertEqual(url, TEST_OAUTH_URL)

    def test_get_push_url_no_token(self):
        """Test returns None when no token available."""
        with mock.patch.object(gitlab, 'get_token', return_value=None):
            url = gitlab.get_push_url('origin')
        self.assertIsNone(url)

    def test_get_push_url_invalid_remote(self):
        """Test returns None for invalid remote URL."""
        with mock.patch.object(gitlab, 'get_token',
                               return_value='test-token'):
            with mock.patch.object(gitlab, 'get_remote_url',
                                   return_value='not-a-valid-url'):
                url = gitlab.get_push_url('origin')
        self.assertIsNone(url)

    def test_get_push_url_https_remote(self):
        """Test with HTTPS remote URL."""
        with mock.patch.object(gitlab, 'get_token',
                               return_value='test-token'):
            with mock.patch.object(gitlab, 'get_remote_url',
                                   return_value=TEST_HTTPS_URL):
                url = gitlab.get_push_url('origin')
        self.assertEqual(url, TEST_OAUTH_URL)


class TestPushBranch(unittest.TestCase):
    """Tests for push_branch function."""

    def test_push_branch_force_with_remote_ref(self):
        """Test force push when remote branch exists uses --force-with-lease."""
        with mock.patch.object(gitlab, 'get_push_url',
                               return_value=TEST_SHORT_OAUTH_URL):
            with mock.patch.object(command, 'output') as mock_output:
                mock_output.side_effect = [
                    None,  # fetch succeeds
                    'abc123def\n',  # rev-parse returns OID
                    None,  # push succeeds
                ]
                result = gitlab.push_branch('ci', 'test-branch', force=True)

        self.assertTrue(result)
        # Should fetch, rev-parse, then push with --force-with-lease
        calls = mock_output.call_args_list
        self.assertEqual(len(calls), 3)
        self.assertEqual(calls[0], mock.call(
            'git', 'fetch', 'ci',
            '+refs/heads/test-branch:refs/remotes/ci/test-branch'))
        self.assertEqual(calls[1], mock.call(
            'git', 'rev-parse', 'refs/remotes/ci/test-branch'))
        push_args = calls[2][0]
        self.assertIn('--force-with-lease=test-branch:abc123def',
                      push_args)

    def test_push_branch_force_no_remote_ref(self):
        """Test force push when remote branch doesn't exist uses --force."""
        with mock.patch.object(gitlab, 'get_push_url',
                               return_value=TEST_SHORT_OAUTH_URL):
            with mock.patch.object(command, 'output') as mock_output:
                # Fetch fails (branch doesn't exist on remote)
                mock_output.side_effect = [
                    command.CommandExc('fetch failed',
                                       command.CommandResult()),  # fetch fails
                    None,  # push succeeds
                ]
                result = gitlab.push_branch('ci', 'new-branch', force=True)

        self.assertTrue(result)
        # Should try fetch, fail, then push with --force
        # (not --force-with-lease)
        calls = mock_output.call_args_list
        self.assertEqual(len(calls), 2)
        push_args = calls[1][0]
        self.assertIn('--force', push_args)
        self.assertNotIn('--force-with-lease', ' '.join(push_args))

    def test_push_branch_no_force(self):
        """Test regular push without force doesn't fetch or use force flags."""
        with mock.patch.object(gitlab, 'get_push_url',
                               return_value=TEST_SHORT_OAUTH_URL):
            with mock.patch.object(command, 'output') as mock_output:
                result = gitlab.push_branch('ci', 'test-branch', force=False)

        self.assertTrue(result)
        # Should only push, no fetch, no force flags
        calls = mock_output.call_args_list
        self.assertEqual(len(calls), 1)
        push_args = calls[0][0]
        self.assertNotIn('--force', ' '.join(push_args))
        self.assertNotIn('fetch', ' '.join(push_args))


class TestConfigFile(unittest.TestCase):
    """Tests for config file support."""

    def setUp(self):
        """Set up test fixtures."""
        self.config_dir = tempfile.mkdtemp()
        self.config_file = os.path.join(self.config_dir, 'pickman.conf')

    def tearDown(self):
        """Clean up test fixtures."""
        shutil.rmtree(self.config_dir)

    def test_get_token_from_config(self):
        """Test getting token from config file."""
        tools.write_file(self.config_file,
                         '[gitlab]\ntoken = test-config-token\n',
                         binary=False)

        with mock.patch.object(gitlab, 'CONFIG_FILE', self.config_file):
            token = gitlab.get_token()
        self.assertEqual(token, 'test-config-token')

    def test_get_token_fallback_to_env(self):
        """Test falling back to environment variable."""
        # Config file doesn't exist
        with mock.patch.object(gitlab, 'CONFIG_FILE', '/nonexistent/path'):
            with mock.patch.dict(os.environ, {'GITLAB_TOKEN': 'env-token'}):
                token = gitlab.get_token()
        self.assertEqual(token, 'env-token')

    def test_get_token_config_missing_section(self):
        """Test config file without gitlab section."""
        tools.write_file(self.config_file, '[other]\nkey = value\n',
                         binary=False)

        with mock.patch.object(gitlab, 'CONFIG_FILE', self.config_file):
            with mock.patch.dict(os.environ, {'GITLAB_TOKEN': 'env-token'}):
                token = gitlab.get_token()
        self.assertEqual(token, 'env-token')

    def test_get_config_value(self):
        """Test get_config_value function."""
        tools.write_file(self.config_file, '[section1]\nkey1 = value1\n',
                         binary=False)

        with mock.patch.object(gitlab, 'CONFIG_FILE', self.config_file):
            value = gitlab.get_config_value('section1', 'key1')
        self.assertEqual(value, 'value1')


class TestCheckPermissions(unittest.TestCase):
    """Tests for check_permissions function."""

    @mock.patch.object(gitlab, 'get_remote_url')
    @mock.patch.object(gitlab, 'get_token')
    @mock.patch.object(gitlab, 'AVAILABLE', True)
    def test_check_permissions_developer(self, mock_token, mock_url):
        """Test checking permissions for a developer."""
        mock_token.return_value = 'test-token'
        mock_url.return_value = 'git@gitlab.com:group/project.git'

        mock_user = mock.MagicMock()
        mock_user.username = 'testuser'
        mock_user.id = 123

        mock_member = mock.MagicMock()
        mock_member.access_level = 30  # Developer

        mock_project = mock.MagicMock()
        mock_project.members.get.return_value = mock_member

        mock_glab = mock.MagicMock()
        mock_glab.user = mock_user
        mock_glab.projects.get.return_value = mock_project

        with mock.patch('gitlab.Gitlab', return_value=mock_glab):
            perms = gitlab.check_permissions('origin')

        self.assertIsNotNone(perms)
        self.assertEqual(perms.user, 'testuser')
        self.assertEqual(perms.access_level, 30)
        self.assertEqual(perms.access_name, 'Developer')
        self.assertTrue(perms.can_push)
        self.assertTrue(perms.can_create_mr)
        self.assertFalse(perms.can_merge)

    @mock.patch.object(gitlab, 'AVAILABLE', False)
    def test_check_permissions_not_available(self):
        """Test check_permissions when gitlab not available."""
        with terminal.capture():
            perms = gitlab.check_permissions('origin')
        self.assertIsNone(perms)

    @mock.patch.object(gitlab, 'get_token')
    @mock.patch.object(gitlab, 'AVAILABLE', True)
    def test_check_permissions_no_token(self, mock_token):
        """Test check_permissions when no token set."""
        mock_token.return_value = None
        with terminal.capture():
            perms = gitlab.check_permissions('origin')
        self.assertIsNone(perms)


class TestUpdateMrDescription(unittest.TestCase):
    """Tests for update_mr_desc function."""

    @mock.patch.object(gitlab, 'get_remote_url')
    @mock.patch.object(gitlab, 'get_token')
    @mock.patch.object(gitlab, 'AVAILABLE', True)
    def test_update_mr_desc_success(self, mock_token, mock_url):
        """Test successful MR description update."""
        mock_token.return_value = 'test-token'
        mock_url.return_value = 'git@gitlab.com:group/project.git'

        mock_mr = mock.MagicMock()
        mock_project = mock.MagicMock()
        mock_project.mergerequests.get.return_value = mock_mr

        with mock.patch('gitlab.Gitlab') as mock_gitlab:
            mock_gitlab.return_value.projects.get.return_value = mock_project

            result = gitlab.update_mr_desc('origin', 123,
                                                      'New description')

            self.assertTrue(result)
            self.assertEqual(mock_mr.description, 'New description')
            mock_mr.save.assert_called_once()

    @mock.patch.object(gitlab, 'AVAILABLE', False)
    def test_update_mr_desc_not_available(self):
        """Test update_mr_desc when gitlab not available."""
        with terminal.capture():
            result = gitlab.update_mr_desc('origin', 123, 'desc')
        self.assertFalse(result)

    @mock.patch.object(gitlab, 'get_token')
    @mock.patch.object(gitlab, 'AVAILABLE', True)
    def test_update_mr_desc_no_token(self, mock_token):
        """Test update_mr_desc when no token set."""
        mock_token.return_value = None
        with terminal.capture():
            result = gitlab.update_mr_desc('origin', 123, 'desc')
        self.assertFalse(result)


class TestGetPickmanMrs(unittest.TestCase):
    """Tests for get_pickman_mrs function."""

    @mock.patch.object(gitlab, 'get_remote_url')
    @mock.patch.object(gitlab, 'get_token')
    @mock.patch.object(gitlab, 'AVAILABLE', True)
    def test_get_pickman_mrs_sorted_oldest_first(self, mock_token, mock_url):
        """Test that MRs are requested sorted by created_at ascending."""
        mock_token.return_value = 'test-token'
        mock_url.return_value = 'git@gitlab.com:group/project.git'

        # Create mock MRs with [pickman] in the title
        mock_mr1 = mock.MagicMock()
        mock_mr1.iid = 1
        mock_mr1.title = '[pickman] Older MR'
        mock_mr1.web_url = TEST_MR_1_URL
        mock_mr1.source_branch = 'cherry-1'
        mock_mr1.description = 'desc1'
        mock_mr1.has_conflicts = False
        mock_mr1.detailed_merge_status = 'mergeable'
        mock_mr1.diverged_commits_count = 0

        mock_mr2 = mock.MagicMock()
        mock_mr2.iid = 2
        mock_mr2.title = '[pickman] Newer MR'
        mock_mr2.web_url = 'https://gitlab.com/mr/2'
        mock_mr2.source_branch = 'cherry-2'
        mock_mr2.description = 'desc2'
        mock_mr2.has_conflicts = False
        mock_mr2.detailed_merge_status = 'mergeable'
        mock_mr2.diverged_commits_count = 0

        mock_project = mock.MagicMock()
        # Return MRs in the order they would come from GitLab (oldest first)
        mock_project.mergerequests.list.return_value = [mock_mr1, mock_mr2]
        mock_project.mergerequests.get.side_effect = [mock_mr1, mock_mr2]

        with mock.patch('gitlab.Gitlab') as mock_gitlab:
            mock_gitlab.return_value.projects.get.return_value = mock_project

            result = gitlab.get_pickman_mrs('origin', state='opened')

        # Verify the list call includes sorting parameters
        mock_project.mergerequests.list.assert_called_once_with(
            state='opened', order_by='created_at', sort='asc', get_all=True)

        # Verify we got both MRs in order
        self.assertEqual(len(result), 2)
        self.assertEqual(result[0].iid, 1)
        self.assertEqual(result[1].iid, 2)


class TestCreateMr(unittest.TestCase):
    """Tests for create_mr function."""

    @mock.patch.object(gitlab, 'get_token')
    @mock.patch.object(gitlab, 'AVAILABLE', True)
    def test_create_mr_409_returns_existing(self, mock_token):
        """Test that 409 error returns existing MR URL."""
        tout.init(tout.INFO)
        mock_token.return_value = 'test-token'

        # Create mock existing MR
        mock_existing_mr = mock.MagicMock()
        mock_existing_mr.web_url = TEST_MR_URL

        mock_project = mock.MagicMock()
        mock_project.mergerequests.list.return_value = [mock_existing_mr]

        # Simulate 409 Conflict error
        mock_project.mergerequests.create.side_effect = \
            gitlab.MrCreateError(response_code=409)

        with mock.patch('gitlab.Gitlab') as mock_gitlab:
            mock_gitlab.return_value.projects.get.return_value = mock_project

            with terminal.capture():
                result = gitlab.create_mr(
                    'gitlab.com', 'group/project',
                    'cherry-abc', 'master', 'Test MR')

        self.assertEqual(result, mock_existing_mr.web_url)
        mock_project.mergerequests.list.assert_called_once_with(
            source_branch='cherry-abc', state='opened')


class TestParseApplyWithPush(unittest.TestCase):
    """Tests for apply command with push options."""

    def test_parse_apply_with_push(self):
        """Test parsing apply command with push option."""
        args = pickman.parse_args(['apply', 'us/next', '-p'])
        self.assertEqual(args.cmd, 'apply')
        self.assertEqual(args.source, 'us/next')
        self.assertTrue(args.push)
        self.assertEqual(args.remote, 'ci')
        self.assertEqual(args.target, 'master')

    def test_parse_apply_with_push_options(self):
        """Test parsing apply command with all push options."""
        args = pickman.parse_args([
            'apply', 'us/next', '-p',
            '-r', 'origin', '-t', 'main'
        ])
        self.assertEqual(args.cmd, 'apply')
        self.assertTrue(args.push)
        self.assertEqual(args.remote, 'origin')
        self.assertEqual(args.target, 'main')


class TestParseStep(unittest.TestCase):
    """Tests for step command argument parsing."""

    def test_parse_step_defaults(self):
        """Test parsing step command with defaults."""
        args = pickman.parse_args(['step', 'us/next'])
        self.assertEqual(args.cmd, 'step')
        self.assertEqual(args.source, 'us/next')
        self.assertEqual(args.max_mrs, 5)
        self.assertEqual(args.remote, 'ci')
        self.assertEqual(args.target, 'master')

    def test_parse_step_with_options(self):
        """Test parsing step command with all options."""
        args = pickman.parse_args(['step', 'us/next', '-m', '3',
                                   '-r', 'origin', '-t', 'main'])
        self.assertEqual(args.cmd, 'step')
        self.assertEqual(args.source, 'us/next')
        self.assertEqual(args.max_mrs, 3)
        self.assertEqual(args.remote, 'origin')
        self.assertEqual(args.target, 'main')


class TestParseMrDescription(unittest.TestCase):
    """Tests for parse_mr_description function."""

    def test_parse_mr_description(self):
        """Test parsing a valid MR description."""
        description = """## 2025-01-15: us/next

Branch: cherry-abc123

Commits:
- abc123a First commit
- def456b Second commit
- caf789c Third commit

### Conversation log
Some log text"""
        source, last_hash = control.parse_mr_description(description)
        self.assertEqual(source, 'us/next')
        self.assertEqual(last_hash, 'caf789c')

    def test_parse_mr_description_single_commit(self):
        """Test parsing MR description with single commit."""
        description = """## 2025-01-15: feature/branch

Branch: cherry-xyz

Commits:
- abc1234 Only commit"""
        source, last_hash = control.parse_mr_description(description)
        self.assertEqual(source, 'feature/branch')
        self.assertEqual(last_hash, 'abc1234')

    def test_parse_mr_description_invalid(self):
        """Test parsing invalid MR description."""
        source, last_hash = control.parse_mr_description('invalid description')
        self.assertIsNone(source)
        self.assertIsNone(last_hash)

    def test_parse_mr_description_no_commits(self):
        """Test parsing MR description without commits."""
        description = """## 2025-01-15: us/next

Branch: cherry-abc"""
        source, last_hash = control.parse_mr_description(description)
        self.assertIsNone(source)
        self.assertIsNone(last_hash)

    def test_parse_mr_description_ignores_chashes(self):
        """Test that short numbers in conversation log are not matched."""
        description = """## 2025-01-15: us/next

Branch: cherry-abc123

Commits:
- abc123a First commit
- def456b Second commit

### Conversation log
- 1 board built (sandbox)
- 2 tests passed"""
        source, last_hash = control.parse_mr_description(description)
        self.assertEqual(source, 'us/next')
        # Should match def456b, not "1" or "2" from conversation log
        self.assertEqual(last_hash, 'def456b')


class TestStep(unittest.TestCase):
    """Tests for step command."""

    def test_step_with_pending_mr(self):
        """Test step does nothing when MR is pending."""
        mock_mr = gitlab.PickmanMr(
            iid=123,
            title='[pickman] Test MR',
            web_url='https://gitlab.com/mr/123',
            source_branch='cherry-test',
            description='Test',
        )
        mock_info = control.NextCommitsInfo(
            commits=['fake'], merge_found=True, advance_to='abc123')
        with mock.patch.object(control, 'run_git'):
            with mock.patch.object(gitlab, 'get_merged_pickman_mrs',
                                   return_value=[]):
                with mock.patch.object(gitlab, 'get_open_pickman_mrs',
                                       return_value=[mock_mr]):
                    with mock.patch.object(
                            control, '_prepare_get_commits',
                            return_value=(mock_info, None)):
                        args = argparse.Namespace(
                            cmd='step', source='us/next', remote='ci',
                            target='master', max_mrs=1, fix_retries=3)
                        with terminal.capture():
                            ret = control.do_step(args, None)

        self.assertEqual(ret, 0)

    def test_step_gitlab_error(self):
        """Test step when GitLab API returns error."""
        with mock.patch.object(gitlab, 'get_merged_pickman_mrs',
                               return_value=None):
            args = argparse.Namespace(cmd='step', source='us/next',
                                      remote='ci', target='master',
                                      max_mrs=5)
            with terminal.capture():
                ret = control.do_step(args, None)

        self.assertEqual(ret, 1)

    def test_step_open_mrs_error(self):
        """Test step when get_open_pickman_mrs returns error."""
        with mock.patch.object(gitlab, 'get_merged_pickman_mrs',
                               return_value=[]):
            with mock.patch.object(gitlab, 'get_open_pickman_mrs',
                                   return_value=None):
                args = argparse.Namespace(cmd='step', source='us/next',
                                          remote='ci', target='master',
                                          max_mrs=5)
                with terminal.capture():
                    ret = control.do_step(args, None)

        self.assertEqual(ret, 1)

    def test_step_allows_below_max(self):
        """Test step allows new MR when count is below max_mrs."""
        mock_mr = gitlab.PickmanMr(
            iid=123,
            title='[pickman] Test MR',
            web_url='https://gitlab.com/mr/123',
            source_branch='cherry-test',
            description='Test',
        )
        mock_info = control.NextCommitsInfo(
            commits=['fake'], merge_found=True, advance_to='abc123')
        with mock.patch.object(control, 'run_git'):
            with mock.patch.object(gitlab, 'get_merged_pickman_mrs',
                                   return_value=[]):
                with mock.patch.object(gitlab, 'get_open_pickman_mrs',
                                       return_value=[mock_mr]):
                    with mock.patch.object(
                            control, '_prepare_get_commits',
                            return_value=(mock_info, None)):
                        with mock.patch.object(control, 'do_apply',
                                               return_value=0) as mock_apply:
                            args = argparse.Namespace(
                                cmd='step', source='us/next', remote='ci',
                                target='master', max_mrs=5, fix_retries=3)
                            with terminal.capture():
                                ret = control.do_step(args, None)

        # With 1 open MR and max_mrs=5, it should try to create a new one
        self.assertEqual(ret, 0)
        mock_apply.assert_called_once()

    def test_step_blocks_at_max(self):
        """Test step blocks new MR when at max_mrs limit."""
        mock_mrs = [
            gitlab.PickmanMr(
                iid=i,
                title=f'[pickman] Test MR {i}',
                web_url=f'https://gitlab.com/mr/{i}',
                source_branch=f'cherry-test-{i}',
                description='Test',
            )
            for i in range(3)
        ]
        mock_info = control.NextCommitsInfo(
            commits=['fake'], merge_found=True, advance_to='abc123')
        with mock.patch.object(control, 'run_git'):
            with mock.patch.object(gitlab, 'get_merged_pickman_mrs',
                                   return_value=[]):
                with mock.patch.object(gitlab, 'get_open_pickman_mrs',
                                       return_value=mock_mrs):
                    with mock.patch.object(
                            control, '_prepare_get_commits',
                            return_value=(mock_info, None)):
                        with mock.patch.object(control, 'do_apply') \
                                as mock_apply:
                            args = argparse.Namespace(
                                cmd='step', source='us/next', remote='ci',
                                target='master', max_mrs=3, fix_retries=3)
                            with terminal.capture():
                                ret = control.do_step(args, None)

        # With 3 open MRs and max_mrs=3, should not create new MR
        self.assertEqual(ret, 0)
        mock_apply.assert_not_called()


class TestParseReview(unittest.TestCase):
    """Tests for review command argument parsing."""

    def test_parse_review_defaults(self):
        """Test parsing review command with defaults."""
        args = pickman.parse_args(['review'])
        self.assertEqual(args.cmd, 'review')
        self.assertEqual(args.remote, 'ci')

    def test_parse_review_with_remote(self):
        """Test parsing review command with custom remote."""
        args = pickman.parse_args(['review', '-r', 'origin'])
        self.assertEqual(args.cmd, 'review')
        self.assertEqual(args.remote, 'origin')


class TestReview(unittest.TestCase):
    """Tests for review command."""

    def test_review_no_mrs(self):
        """Test review when no open MRs found."""
        with mock.patch.object(gitlab, 'get_open_pickman_mrs',
                               return_value=[]):
            args = argparse.Namespace(cmd='review', remote='ci')
            with terminal.capture():
                ret = control.do_review(args, None)

        self.assertEqual(ret, 0)

    def test_review_gitlab_error(self):
        """Test review when GitLab API returns error."""
        with mock.patch.object(gitlab, 'get_open_pickman_mrs',
                               return_value=None):
            args = argparse.Namespace(cmd='review', remote='ci')
            with terminal.capture():
                ret = control.do_review(args, None)

        self.assertEqual(ret, 1)


class TestUpdateHistoryWithReview(unittest.TestCase):
    """Tests for update_history function."""

    def setUp(self):
        """Set up test fixtures."""
        self.test_dir = tempfile.mkdtemp()
        self.orig_dir = os.getcwd()
        os.chdir(self.test_dir)

        # Initialize git repo
        subprocess.run(['git', 'init'], check=True, capture_output=True)
        subprocess.run(['git', 'config', 'user.email', 'test@test.com'],
                       check=True, capture_output=True)
        subprocess.run(['git', 'config', 'user.name', 'Test'],
                       check=True, capture_output=True)

    def tearDown(self):
        """Clean up test fixtures."""
        os.chdir(self.orig_dir)
        shutil.rmtree(self.test_dir)

    def test_update_history(self):
        """Test that review handling is appended to history."""
        comments = [
            gitlab.MrComment(id=1, author='reviewer1',
                                 body='Please fix the indentation here',
                                 created_at='2025-01-01', resolvable=True,
                                 resolved=False),
            gitlab.MrComment(id=2, author='reviewer2', body='Add a docstring',
                                 created_at='2025-01-01', resolvable=True,
                                 resolved=False),
        ]
        conversation_log = 'Fixed indentation and added docstring.'

        control.update_history('cherry-abc123', comments,
                                           conversation_log)

        # Check history file was created
        self.assertTrue(os.path.exists(control.HISTORY_FILE))

        content = tools.read_file(control.HISTORY_FILE, binary=False)

        self.assertIn('### Review:', content)
        self.assertIn('Branch: cherry-abc123', content)
        self.assertIn('reviewer1', content)
        self.assertIn('reviewer2', content)
        self.assertIn('Fixed indentation', content)

    def test_update_history_appends(self):
        """Test that review handling appends to existing history."""
        # Create existing history
        tools.write_file(control.HISTORY_FILE,
                         'Existing history content\n', binary=False)
        subprocess.run(['git', 'add', control.HISTORY_FILE],
                       check=True, capture_output=True)
        subprocess.run(['git', 'commit', '-m', 'Initial'],
                       check=True, capture_output=True)

        comms = [gitlab.MrComment(id=1, author='reviewer', body='Fix this',
                                      created_at='2025-01-01', resolvable=True,
                                      resolved=False)]
        control.update_history('cherry-xyz', comms, 'Fixed it')

        content = tools.read_file(control.HISTORY_FILE, binary=False)

        self.assertIn('Existing history content', content)
        self.assertIn('### Review:', content)


class TestProcessMrReviewsCommentTracking(unittest.TestCase):
    """Tests for comment tracking in process_mr_reviews."""

    def setUp(self):
        """Set up test fixtures."""
        fd, self.db_path = tempfile.mkstemp(suffix='.db')
        os.close(fd)
        os.unlink(self.db_path)
        self.test_dir = tempfile.mkdtemp()
        self.orig_dir = os.getcwd()
        os.chdir(self.test_dir)

        # Initialize git repo
        subprocess.run(['git', 'init'], check=True, capture_output=True)
        subprocess.run(['git', 'config', 'user.email', 'test@test.com'],
                       check=True, capture_output=True)
        subprocess.run(['git', 'config', 'user.name', 'Test'],
                       check=True, capture_output=True)

    def tearDown(self):
        """Clean up test fixtures."""
        os.chdir(self.orig_dir)
        shutil.rmtree(self.test_dir)
        if os.path.exists(self.db_path):
            os.unlink(self.db_path)
        database.Database.instances.clear()

    def test_skips_processed_comments(self):
        """Test that already-processed comments are skipped."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()

            # Mark comment as processed
            dbs.comment_mark_processed(100, 1)
            dbs.commit()

            mrs = [gitlab.PickmanMr(
                iid=100,
                title='[pickman] Test MR',
                source_branch='cherry-test',
                description='Test',
                web_url='https://gitlab.com/mr/100',
            )]

            # Comment 1 is processed, comment 2 is new
            comments = [
                gitlab.MrComment(id=1, author='reviewer', body='Old comment',
                                     created_at='2025-01-01', resolvable=True,
                                     resolved=False),
                gitlab.MrComment(id=2, author='reviewer', body='New comment',
                                     created_at='2025-01-01', resolvable=True,
                                     resolved=False),
            ]

            with mock.patch.object(control, 'run_git'):
                with mock.patch.object(gitlab, 'get_mr_comments',
                                       return_value=comments):
                    with mock.patch.object(agent, 'handle_mr_comments',
                                           return_value=(True, 'Done')) as moc:
                        with mock.patch.object(gitlab, 'update_mr_desc'):
                            with mock.patch.object(control, 'update_history'):
                                control.process_mr_reviews('ci', mrs, dbs)

            # Agent should only receive the new comment
            call_args = moc.call_args
            passed_comments = call_args[0][2]
            self.assertEqual(len(passed_comments), 1)
            self.assertEqual(passed_comments[0].id, 2)

            dbs.close()

    def test_rebase_without_comments(self):
        """Test that MRs needing rebase trigger agent even without comments."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()

            # MR needs rebase but has no comments
            mrs = [gitlab.PickmanMr(
                iid=100,
                title='[pickman] Test MR',
                source_branch='cherry-test',
                description='Test',
                web_url='https://gitlab.com/mr/100',
                has_conflicts=False,
                needs_rebase=True,
            )]

            with mock.patch.object(control, 'run_git'):
                with mock.patch.object(gitlab, 'get_mr_comments',
                                       return_value=[]):
                    with mock.patch.object(agent, 'handle_mr_comments',
                                           return_value=(True, 'Rebased')) as m:
                        with mock.patch.object(gitlab, 'update_mr_desc'):
                            with mock.patch.object(control, 'update_history'):
                                control.process_mr_reviews('ci', mrs, dbs)

            # Agent should be called with needs_rebase=True
            m.assert_called_once()
            call_kwargs = m.call_args[1]
            self.assertTrue(call_kwargs.get('needs_rebase'))
            self.assertFalse(call_kwargs.get('has_conflicts'))

            dbs.close()

    def test_skips_mr_no_rebase_no_comments(self):
        """Test that MRs without rebase need or comments are skipped."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()

            # MR has no comments and doesn't need rebase
            mrs = [gitlab.PickmanMr(
                iid=100,
                title='[pickman] Test MR',
                source_branch='cherry-test',
                description='Test',
                web_url='https://gitlab.com/mr/100',
                has_conflicts=False,
                needs_rebase=False,
            )]

            with mock.patch.object(control, 'run_git'):
                with mock.patch.object(gitlab, 'get_mr_comments',
                                       return_value=[]):
                    with mock.patch.object(agent, 'handle_mr_comments',
                                           return_value=(True, 'Done')) as moc:
                        control.process_mr_reviews('ci', mrs, dbs)

            # Agent should NOT be called
            moc.assert_not_called()

            dbs.close()


class TestParsePoll(unittest.TestCase):
    """Tests for poll command argument parsing."""

    def test_parse_poll_defaults(self):
        """Test parsing poll command with defaults."""
        args = pickman.parse_args(['poll', 'us/next'])
        self.assertEqual(args.cmd, 'poll')
        self.assertEqual(args.source, 'us/next')
        self.assertEqual(args.interval, 300)
        self.assertEqual(args.max_mrs, 5)
        self.assertEqual(args.remote, 'ci')
        self.assertEqual(args.target, 'master')

    def test_parse_poll_with_options(self):
        """Test parsing poll command with all options."""
        args = pickman.parse_args([
            'poll', 'us/next',
            '-i', '60', '-m', '3', '-r', 'origin', '-t', 'main'
        ])
        self.assertEqual(args.cmd, 'poll')
        self.assertEqual(args.source, 'us/next')
        self.assertEqual(args.interval, 60)
        self.assertEqual(args.max_mrs, 3)
        self.assertEqual(args.remote, 'origin')
        self.assertEqual(args.target, 'main')


class TestPoll(unittest.TestCase):
    """Tests for poll command."""

    def test_poll_stops_on_keyboard_interrupt(self):
        """Test poll stops gracefully on KeyboardInterrupt."""
        call_count = [0]

        def mock_step(_args, _dbs):
            call_count[0] += 1
            if call_count[0] >= 2:
                raise KeyboardInterrupt
            return 0

        with mock.patch.object(control, 'do_step', mock_step):
            with mock.patch('time.sleep'):
                args = argparse.Namespace(
                    cmd='poll', source='us/next', interval=1,
                    remote='ci', target='master'
                )
                with terminal.capture():
                    ret = control.do_poll(args, None)

        self.assertEqual(ret, 0)
        self.assertEqual(call_count[0], 2)

    def test_poll_continues_on_step_error(self):
        """Test poll continues when step returns non-zero."""
        call_count = [0]

        def mock_step(_args, _dbs):
            call_count[0] += 1
            if call_count[0] >= 2:
                raise KeyboardInterrupt
            return 1  # Return error

        with mock.patch.object(control, 'do_step', mock_step):
            with mock.patch('time.sleep'):
                args = argparse.Namespace(
                    cmd='poll', source='us/next', interval=1,
                    remote='ci', target='master'
                )
                with terminal.capture() as (_, stderr):
                    ret = control.do_poll(args, None)

        self.assertEqual(ret, 0)
        self.assertIn('returned 1', stderr.getvalue())


class TestParseInstruction(unittest.TestCase):
    """Tests for parse_instruction function."""

    def test_pickman_skip(self):
        """Test 'pickman skip' format."""
        self.assertEqual(control.parse_instruction('pickman skip'), 'skip')

    def test_pickman_colon_skip(self):
        """Test 'pickman: skip' format."""
        self.assertEqual(control.parse_instruction('pickman: skip'), 'skip')

    def test_at_pickman_skip(self):
        """Test '@pickman skip' format."""
        self.assertEqual(control.parse_instruction('@pickman skip'), 'skip')

    def test_at_pickman_colon_skip(self):
        """Test '@pickman: skip' format."""
        self.assertEqual(control.parse_instruction('@pickman: skip'), 'skip')

    def test_pickman_unskip(self):
        """Test 'pickman unskip' format."""
        self.assertEqual(control.parse_instruction('pickman unskip'), 'unskip')

    def test_at_pickman_unskip(self):
        """Test '@pickman unskip' format."""
        self.assertEqual(control.parse_instruction('@pickman unskip'), 'unskip')

    def test_case_insensitive(self):
        """Test case insensitivity."""
        self.assertEqual(control.parse_instruction('PICKMAN SKIP'), 'skip')
        self.assertEqual(control.parse_instruction('Pickman: Skip'), 'skip')

    def test_in_longer_text(self):
        """Test instruction embedded in longer comment."""
        body = 'Please pickman skip this MR, it does not apply'
        self.assertEqual(control.parse_instruction(body), 'skip')

    def test_no_instruction(self):
        """Test comment without pickman instruction."""
        self.assertIsNone(control.parse_instruction('Just a regular comment'))

    def test_pickman_without_command(self):
        """Test 'pickman' alone without a command."""
        self.assertIsNone(control.parse_instruction('pickman'))

    def test_has_instruction(self):
        """Test has_instruction helper."""
        self.assertTrue(control.has_instruction('pickman skip', 'skip'))
        self.assertTrue(control.has_instruction('@pickman: unskip', 'unskip'))
        self.assertFalse(control.has_instruction('pickman skip', 'unskip'))
        self.assertFalse(control.has_instruction('regular comment', 'skip'))


class TestFormatHistorySummary(unittest.TestCase):
    """Tests for format_history function."""

    def test_format_history(self):
        """Test formatting history summary."""
        commits = [
            control.CommitInfo('aaa111', 'aaa111a', 'First commit', 'Author 1'),
            control.CommitInfo('bbb222', 'bbb222b', 'Second one', 'Author 2'),
        ]
        result = control.format_history('us/next', commits, 'cherry-abc')

        self.assertIn('us/next', result)
        self.assertIn('Branch: cherry-abc', result)
        self.assertIn('- aaa111a First commit', result)
        self.assertIn('- bbb222b Second one', result)


class TestGetHistory(unittest.TestCase):
    """Tests for get_history function."""

    def setUp(self):
        """Set up test fixtures."""
        fd, self.history_file = tempfile.mkstemp(suffix='.history')
        os.close(fd)
        os.unlink(self.history_file)  # Remove so we start fresh

    def tearDown(self):
        """Clean up test fixtures."""
        if os.path.exists(self.history_file):
            os.unlink(self.history_file)

    def test_get_history_empty(self):
        """Test get_history with no existing file."""
        commits = [
            control.CommitInfo('aaa111', 'aaa111a', 'First commit', 'Author 1'),
        ]
        content, commit_msg = control.get_history(
            self.history_file, 'us/next', commits, 'cherry-abc',
            'Conversation output')

        self.assertIn('us/next', content)
        self.assertIn('Branch: cherry-abc', content)
        self.assertIn('- aaa111a First commit', content)
        self.assertIn('### Conversation log', content)
        self.assertIn('Conversation output', content)
        self.assertIn('---', content)

        # Verify commit message
        self.assertIn('pickman: Record cherry-pick of 1 commits', commit_msg)
        self.assertIn('- aaa111a First commit', commit_msg)

        # Verify file was written
        file_content = tools.read_file(self.history_file, binary=False)
        self.assertEqual(file_content, content)

    def test_get_history_with_existing(self):
        """Test get_history appends to existing content."""
        # Create existing file
        tools.write_file(self.history_file,
                         'Previous history content\n', binary=False)

        commits = [
            control.CommitInfo('bbb222', 'bbb222b', 'New commit', 'Author 2'),
        ]
        content, commit_msg = control.get_history(
            self.history_file, 'us/next', commits, 'cherry-new',
            'New conversation')

        self.assertIn('Previous history content', content)
        self.assertIn('cherry-new', content)
        self.assertIn('New conversation', content)
        self.assertIn('- bbb222b New commit', commit_msg)

    def test_get_history_replaces_existing_branch(self):
        """Test get_history removes existing entry for same branch."""
        # Create existing file with an entry for cherry-abc
        existing = """## 2025-01-01: us/next

Branch: cherry-abc

Commits:
- aaa111a Old commit

### Conversation log
Old conversation

---

Other content
"""
        tools.write_file(self.history_file, existing, binary=False)

        commits = [
            control.CommitInfo('ccc333', 'ccc333c', 'Updated commit', 'Author'),
        ]
        content, _ = control.get_history(self.history_file, 'us/next', commits,
                                         'cherry-abc', 'New conversation')

        # Old entry should be removed
        self.assertNotIn('Old commit', content)
        self.assertNotIn('Old conversation', content)
        # New entry should be present
        self.assertIn('Updated commit', content)
        self.assertIn('New conversation', content)
        # Other content should be preserved
        self.assertIn('Other content', content)

    def test_get_history_multiple_commits(self):
        """Test get_history with multiple commits."""
        commits = [
            control.CommitInfo('aaa111', 'aaa111a', 'First commit', 'Author 1'),
            control.CommitInfo('bbb222', 'bbb222b', 'Second one', 'Author 2'),
            control.CommitInfo('ccc333', 'ccc333c', 'Third commit', 'Author 3'),
        ]
        content, commit_msg = control.get_history(
            self.history_file, 'us/next', commits, 'cherry-abc', 'Log')

        # Verify all commits in content
        self.assertIn('- aaa111a First commit', content)
        self.assertIn('- bbb222b Second one', content)
        self.assertIn('- ccc333c Third commit', content)

        # Verify commit message
        self.assertIn('pickman: Record cherry-pick of 3 commits', commit_msg)
        self.assertIn('- aaa111a First commit', commit_msg)
        self.assertIn('- bbb222b Second one', commit_msg)
        self.assertIn('- ccc333c Third commit', commit_msg)


class TestPrepareApply(unittest.TestCase):
    """Tests for prepare_apply function."""

    def setUp(self):
        """Set up test fixtures."""
        fd, self.db_path = tempfile.mkstemp(suffix='.db')
        os.close(fd)
        os.unlink(self.db_path)
        self.old_db_fname = control.DB_FNAME
        control.DB_FNAME = self.db_path
        database.Database.instances.clear()

    def tearDown(self):
        """Clean up test fixtures."""
        control.DB_FNAME = self.old_db_fname
        if os.path.exists(self.db_path):
            os.unlink(self.db_path)
        database.Database.instances.clear()
        command.TEST_RESULT = None

    def test_prepare_apply_error(self):
        """Test prepare_apply returns error code 1 on source not found."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()

            info, ret = control.prepare_apply(dbs, 'unknown', None)

            self.assertIsNone(info)
            self.assertEqual(ret, 1)
            dbs.close()

    def test_prepare_apply_no_commits(self):
        """Test prepare_apply returns code 0 when no commits."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'abc123')
            dbs.commit()

            command.TEST_RESULT = command.CommandResult(stdout='')

            info, ret = control.prepare_apply(dbs, 'us/next', None)

            self.assertIsNone(info)
            self.assertEqual(ret, 0)
            dbs.close()

    def test_prepare_apply_with_commits(self):
        """Test prepare_apply returns ApplyInfo with commits."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'abc123')
            dbs.commit()

            log_output = 'aaa111|aaa111a|Author 1|First commit|abc123\n'

            def mock_git(pipe_list):
                cmd = pipe_list[0] if pipe_list else []
                if 'log' in cmd:
                    return command.CommandResult(stdout=log_output)
                if 'rev-parse' in cmd:
                    return command.CommandResult(stdout='master')
                return command.CommandResult(stdout='')

            command.TEST_RESULT = mock_git

            info, ret = control.prepare_apply(dbs, 'us/next', None)

            self.assertIsNotNone(info)
            self.assertEqual(ret, 0)
            self.assertEqual(len(info.commits), 1)
            self.assertEqual(info.branch_name, 'cherry-aaa111a')
            self.assertEqual(info.original_branch, 'master')
            dbs.close()

    def test_prepare_apply_custom_branch(self):
        """Test prepare_apply uses custom branch name."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'abc123')
            dbs.commit()

            log_output = 'aaa111|aaa111a|Author 1|First commit|abc123\n'

            def mock_git(pipe_list):
                cmd = pipe_list[0] if pipe_list else []
                if 'log' in cmd:
                    return command.CommandResult(stdout=log_output)
                if 'rev-parse' in cmd:
                    return command.CommandResult(stdout='master')
                return command.CommandResult(stdout='')

            command.TEST_RESULT = mock_git

            info, _ = control.prepare_apply(dbs, 'us/next', 'my-branch')

            self.assertIsNotNone(info)
            self.assertEqual(info.branch_name, 'my-branch')
            dbs.close()

    def test_prepare_apply_deletes_existing_branch(self):
        """Test prepare_apply deletes a branch that already exists."""
        git_cmds = []

        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'abc123')
            dbs.commit()

            log_output = 'aaa111|aaa111a|Author 1|First commit|abc123\n'

            def mock_git(pipe_list):
                cmd = pipe_list[0] if pipe_list else []
                git_cmds.append(cmd)
                if 'log' in cmd:
                    return command.CommandResult(stdout=log_output)
                if 'rev-parse' in cmd:
                    return command.CommandResult(stdout='master')
                if 'branch' in cmd and '--list' in cmd:
                    return command.CommandResult(stdout='cherry-aaa111a\n')
                return command.CommandResult(stdout='')

            command.TEST_RESULT = mock_git

            info, ret = control.prepare_apply(dbs, 'us/next', None)

            self.assertIsNotNone(info)
            self.assertEqual(ret, 0)
            # Check that branch -D was called
            self.assertTrue(
                any('branch' in c and '-D' in c for c in git_cmds))
            dbs.close()

    def test_prepare_apply_merge_found(self):
        """Test prepare_apply sets merge_found and advance_to."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'abc123')
            dbs.commit()

            merge_hash = 'ccc333ccc333ccc333'

            merge_info = control.NextCommitsInfo(
                commits=[
                    control.CommitInfo('aaa111', 'aaa111a', 'First commit',
                                       'Author 1'),
                    control.CommitInfo('bbb222', 'bbb222b', 'Second commit',
                                       'Author 2'),
                ],
                merge_found=True,
                advance_to=merge_hash,
            )

            def mock_git(pipe_list):
                cmd = pipe_list[0] if pipe_list else []
                if 'rev-parse' in cmd:
                    return command.CommandResult(stdout='master')
                return command.CommandResult(stdout='')

            with mock.patch.object(control, 'get_next_commits',
                                   return_value=(merge_info, None)):
                command.TEST_RESULT = mock_git
                info, ret = control.prepare_apply(dbs, 'us/next', None)

            self.assertIsNotNone(info)
            self.assertEqual(ret, 0)
            self.assertTrue(info.merge_found)
            self.assertEqual(info.advance_to, merge_hash)
            self.assertEqual(len(info.commits), 2)
            dbs.close()

    def test_prepare_apply_no_merge(self):
        """Test prepare_apply reports no merge found."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'abc123')
            dbs.commit()

            log_output = 'aaa111|aaa111a|Author 1|First commit|abc123\n'

            def mock_git(pipe_list):
                cmd = pipe_list[0] if pipe_list else []
                if 'log' in cmd:
                    return command.CommandResult(stdout=log_output)
                if 'rev-parse' in cmd:
                    return command.CommandResult(stdout='master')
                return command.CommandResult(stdout='')

            command.TEST_RESULT = mock_git

            info, ret = control.prepare_apply(dbs, 'us/next', None)

            self.assertIsNotNone(info)
            self.assertEqual(ret, 0)
            self.assertFalse(info.merge_found)
            dbs.close()


class TestExecuteApply(unittest.TestCase):
    """Tests for execute_apply function."""

    def setUp(self):
        """Set up test fixtures."""
        fd, self.db_path = tempfile.mkstemp(suffix='.db')
        os.close(fd)
        os.unlink(self.db_path)
        self.old_db_fname = control.DB_FNAME
        control.DB_FNAME = self.db_path
        database.Database.instances.clear()

    def tearDown(self):
        """Clean up test fixtures."""
        control.DB_FNAME = self.old_db_fname
        if os.path.exists(self.db_path):
            os.unlink(self.db_path)
        database.Database.instances.clear()

    def test_execute_apply_success(self):
        """Test execute_apply with successful cherry-pick."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'abc123')
            dbs.commit()

            commits = [control.CommitInfo('aaa111', 'aaa111a', 'Test commit',
                                          'Author')]
            args = argparse.Namespace(push=False)

            with mock.patch.object(control.agent, 'cherry_pick_commits',
                                   return_value=(True, 'conversation log')):
                with mock.patch.object(control, 'run_git',
                                       return_value='abc123'):
                    ret, success, conv_log = control.execute_apply(
                        dbs, 'us/next', commits, 'cherry-branch', args)

            self.assertEqual(ret, 0)
            self.assertTrue(success)
            self.assertEqual(conv_log, 'conversation log')

            # Check commit was added to database
            commit_rec = dbs.commit_get('aaa111')
            self.assertIsNotNone(commit_rec)
            self.assertEqual(commit_rec[6], 'applied')  # status field
            dbs.close()

    def test_execute_apply_failure(self):
        """Test execute_apply with failed cherry-pick."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'abc123')
            dbs.commit()

            commits = [control.CommitInfo('bbb222', 'bbb222b', 'Test commit',
                                          'Author')]
            args = argparse.Namespace(push=False)

            with mock.patch.object(control.agent, 'cherry_pick_commits',
                                   return_value=(False, 'error log')):
                ret, success, _ = control.execute_apply(
                    dbs, 'us/next', commits, 'cherry-branch', args)

            self.assertEqual(ret, 1)
            self.assertFalse(success)

            # Check commit status is conflict
            commit_rec = dbs.commit_get('bbb222')
            self.assertEqual(commit_rec[6], 'conflict')
            dbs.close()

    def test_execute_apply_with_push(self):
        """Test execute_apply with push enabled."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'abc123')
            dbs.commit()

            commits = [control.CommitInfo('ccc333', 'ccc333c', 'Test commit',
                                          'Author')]
            args = argparse.Namespace(push=True, remote='origin',
                                      target='main')

            with mock.patch.object(control.agent, 'cherry_pick_commits',
                                   return_value=(True, 'log')):
                with mock.patch.object(control, 'run_git',
                                       return_value='abc123'):
                    with mock.patch.object(gitlab, 'push_and_create_mr',
                                           return_value='https://mr/url'):
                        ret, success, _ = control.execute_apply(
                            dbs, 'us/next', commits, 'cherry-branch', args)

            self.assertEqual(ret, 0)
            self.assertTrue(success)
            dbs.close()

    def test_execute_apply_push_fails(self):
        """Test execute_apply when MR creation fails."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'abc123')
            dbs.commit()

            commits = [control.CommitInfo('ddd444', 'ddd444d', 'Test commit',
                                          'Author')]
            args = argparse.Namespace(push=True, remote='origin',
                                      target='main')

            with mock.patch.object(control.agent, 'cherry_pick_commits',
                                   return_value=(True, 'log')):
                with mock.patch.object(control, 'run_git',
                                       return_value='abc123'):
                    with mock.patch.object(gitlab, 'push_and_create_mr',
                                           return_value=None):
                        ret, success, _ = control.execute_apply(
                            dbs, 'us/next', commits, 'cherry-branch', args)

            self.assertEqual(ret, 1)
            self.assertTrue(success)  # cherry-pick succeeded, MR failed
            dbs.close()

    def test_execute_apply_agent_aborted(self):
        """Test execute_apply when agent aborts and branch doesn't exist."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'abc123')
            dbs.commit()

            commits = [control.CommitInfo('fff666', 'fff666f', 'Test commit',
                                          'Author')]
            args = argparse.Namespace(push=False)

            # Agent reports success but branch doesn't exist (agent aborted)
            with mock.patch.object(control.agent, 'cherry_pick_commits',
                                   return_value=(True, 'aborted log')):
                with mock.patch.object(control, 'run_git',
                                       side_effect=Exception('not found')):
                    ret, success, _ = control.execute_apply(
                        dbs, 'us/next', commits, 'cherry-branch', args)

            # Should detect failure since branch doesn't exist
            self.assertEqual(ret, 1)
            self.assertFalse(success)

            # Check commit status is conflict (not applied)
            commit_rec = dbs.commit_get('fff666')
            self.assertEqual(commit_rec[6], 'conflict')
            dbs.close()

    def test_execute_apply_already_applied(self):
        """Test execute_apply when agent detects commits already applied."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'abc123')
            dbs.commit()

            commits = [control.CommitInfo('ggg777', 'ggg777g', 'Test commit',
                                          'Author'),
                       control.CommitInfo('hhh888', 'hhh888h', 'Merge commit',
                                          'Author')]
            args = argparse.Namespace(push=False)

            # Agent returns success but leaves signal file
            with mock.patch.object(control.agent, 'cherry_pick_commits',
                                   return_value=(True, 'already applied log')):
                with mock.patch.object(control.agent, 'read_signal_file',
                                       return_value=(agent.SIGNAL_APPLIED,
                                                     'hhh888')):
                    ret, success, _ = control.execute_apply(
                        dbs, 'us/next', commits, 'cherry-branch', args)

            # Should return success (skip MR created), but success=False
            self.assertEqual(ret, 0)
            self.assertFalse(success)

            # Check commits are marked as skipped
            commit_rec = dbs.commit_get('ggg777')
            self.assertEqual(commit_rec[6], 'skipped')
            commit_rec = dbs.commit_get('hhh888')
            self.assertEqual(commit_rec[6], 'skipped')

            # Check source was updated
            source_commit = dbs.source_get('us/next')
            self.assertEqual(source_commit, 'hhh888')
            dbs.close()


class TestRunAgentCollect(unittest.TestCase):
    """Tests for run_agent_collect function."""

    def test_success(self):
        """Test successful agent run collects text blocks."""
        block1 = mock.MagicMock()
        block1.text = 'hello'
        block2 = mock.MagicMock()
        block2.text = 'world'
        msg = mock.MagicMock()
        msg.content = [block1, block2]

        async def fake_query(**kwargs):
            yield msg

        with mock.patch.object(agent, 'query', fake_query, create=True):
            with terminal.capture():
                opts = mock.MagicMock()
                success, log = asyncio.run(
                    agent.run_agent_collect('prompt', opts))

        self.assertTrue(success)
        self.assertEqual(log, 'hello\n\nworld')

    def test_failure(self):
        """Test agent failure returns False with partial log."""
        block = mock.MagicMock()
        block.text = 'partial'
        msg = mock.MagicMock()
        msg.content = [block]

        async def fake_query(**kwargs):
            yield msg
            raise RuntimeError('agent crashed')

        with mock.patch.object(agent, 'query', fake_query, create=True):
            with terminal.capture():
                opts = mock.MagicMock()
                success, log = asyncio.run(
                    agent.run_agent_collect('prompt', opts))

        self.assertFalse(success)
        self.assertEqual(log, 'partial')

    def test_no_content(self):
        """Test messages without content are skipped."""
        msg = mock.MagicMock(spec=[])

        async def fake_query(**kwargs):
            yield msg

        with mock.patch.object(agent, 'query', fake_query, create=True):
            with terminal.capture():
                opts = mock.MagicMock()
                success, log = asyncio.run(
                    agent.run_agent_collect('prompt', opts))

        self.assertTrue(success)
        self.assertEqual(log, '')


class TestSignalFile(unittest.TestCase):
    """Tests for signal file handling."""

    def setUp(self):
        """Set up test fixtures."""
        self.test_dir = tempfile.mkdtemp()
        self.signal_path = os.path.join(self.test_dir, agent.SIGNAL_FILE)

    def tearDown(self):
        """Clean up test fixtures."""
        if os.path.exists(self.signal_path):
            os.unlink(self.signal_path)
        os.rmdir(self.test_dir)

    def test_read_signal_file_not_exists(self):
        """Test read_signal_file when file doesn't exist."""
        status, commit = agent.read_signal_file(self.test_dir)
        self.assertIsNone(status)
        self.assertIsNone(commit)

    def test_read_signal_file_already_applied(self):
        """Test read_signal_file with already_applied status."""
        tools.write_file(self.signal_path,
                         'already_applied\nabc123def456\n', binary=False)

        status, commit = agent.read_signal_file(self.test_dir)
        self.assertEqual(status, 'already_applied')
        self.assertEqual(commit, 'abc123def456')

        # File should be removed after reading
        self.assertFalse(os.path.exists(self.signal_path))

    def test_read_signal_file_status_only(self):
        """Test read_signal_file with only status line."""
        tools.write_file(self.signal_path, 'conflict\n', binary=False)

        status, commit = agent.read_signal_file(self.test_dir)
        self.assertEqual(status, 'conflict')
        self.assertIsNone(commit)

        self.assertFalse(os.path.exists(self.signal_path))


class TestGetNextCommitsEmptyLine(unittest.TestCase):
    """Tests for get_next_commits with empty lines."""

    def setUp(self):
        """Set up test fixtures."""
        fd, self.db_path = tempfile.mkstemp(suffix='.db')
        os.close(fd)
        os.unlink(self.db_path)
        self.old_db_fname = control.DB_FNAME
        control.DB_FNAME = self.db_path
        database.Database.instances.clear()

    def tearDown(self):
        """Clean up test fixtures."""
        control.DB_FNAME = self.old_db_fname
        if os.path.exists(self.db_path):
            os.unlink(self.db_path)
        database.Database.instances.clear()
        command.TEST_RESULT = None

    def test_get_next_commits_with_empty_lines(self):
        """Test get_next_commits handles empty lines in output."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'abc123')
            dbs.commit()

            # Log output with empty lines
            log_output = (
                'aaa111|aaa111a|Author 1|First commit|abc123\n'
                '\n'  # Empty line
                'bbb222|bbb222b|Author 2|Second commit|aaa111\n'
                '\n'  # Another empty line
            )
            command.TEST_RESULT = command.CommandResult(stdout=log_output)

            info, err = control.get_next_commits(dbs, 'us/next')
            self.assertIsNone(err)
            self.assertFalse(info.merge_found)
            self.assertEqual(len(info.commits), 2)
            dbs.close()

    def test_get_next_commits_skips_db_commits(self):
        """Test get_next_commits skips commits already in database."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'abc123')

            # Add first commit to database (simulating pending MR)
            source_id = dbs.source_get_id('us/next')
            dbs.commit_add('aaa111', source_id, 'First commit', 'Author 1',
                           status='pending')
            dbs.commit()

            # Log output with two commits, first already in DB
            log_output = (
                'aaa111|aaa111a|Author 1|First commit|abc123\n'
                'bbb222|bbb222b|Author 2|Second commit|aaa111\n'
            )
            command.TEST_RESULT = command.CommandResult(stdout=log_output)

            info, err = control.get_next_commits(dbs, 'us/next')
            self.assertIsNone(err)
            self.assertFalse(info.merge_found)
            # Only second commit should be returned (first is in DB)
            self.assertEqual(len(info.commits), 1)
            self.assertEqual(info.commits[0].chash, 'bbb222b')
            dbs.close()

    def test_get_next_commits_all_in_db(self):
        """Test get_next_commits returns empty when all commits in database."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'abc123')

            # Add both commits to database
            source_id = dbs.source_get_id('us/next')
            dbs.commit_add('aaa111', source_id, 'First commit', 'Author 1',
                           status='pending')
            dbs.commit_add('bbb222', source_id, 'Second commit', 'Author 2',
                           status='pending')
            dbs.commit()

            # Log output with two commits, both in DB
            log_output = (
                'aaa111|aaa111a|Author 1|First commit|abc123\n'
                'bbb222|bbb222b|Author 2|Second commit|aaa111\n'
            )
            command.TEST_RESULT = command.CommandResult(stdout=log_output)

            info, err = control.get_next_commits(dbs, 'us/next')
            self.assertIsNone(err)
            self.assertFalse(info.merge_found)
            # No commits should be returned (all in DB)
            self.assertEqual(len(info.commits), 0)
            dbs.close()

    def test_get_next_commits_skips_processed_merge(self):
        """Test get_next_commits skips merge with all commits in database."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'abc123')

            # Add commits from first merge to database (simulating pending MR)
            source_id = dbs.source_get_id('us/next')
            dbs.commit_add('aaa111', source_id, 'First commit', 'Author 1',
                           status='pending')
            dbs.commit_add('merge1', source_id, 'Merge branch', 'Author 2',
                           status='pending')
            dbs.commit()

            # First-parent log shows two merges
            fp_log = (
                'aaa111|aaa111a|Author 1|First commit|abc123\n'
                'merge1|merge1m|Author 2|Merge branch|aaa111 side1\n'
                'ccc333|ccc333c|Author 3|Third commit|merge1\n'
                'merge2|merge2m|Author 4|Second merge|ccc333 side2\n'
            )

            # When asked for first merge's commits (all in DB)
            merge1_log = (
                'aaa111|aaa111a|Author 1|First commit|abc123\n'
                'merge1|merge1m|Author 2|Merge branch|aaa111 side1\n'
            )

            # When asked for second merge's commits (not in DB)
            merge2_log = (
                'ccc333|ccc333c|Author 3|Third commit|merge1\n'
                'merge2|merge2m|Author 4|Second merge|ccc333 side2\n'
            )

            def mock_git(pipe_list):
                cmd = pipe_list[0] if pipe_list else []
                if '--first-parent' in cmd and '--merges' in cmd:
                    # detect_sub_merges: no sub-merges
                    return command.CommandResult(stdout='')
                if '--first-parent' in cmd:
                    return command.CommandResult(stdout=fp_log)
                if 'rev-parse' in cmd:
                    # detect_sub_merges: return parents for merges
                    return command.CommandResult(stdout='aaa111\nside1\n')
                # Determine which merge range by checking the cmd args
                cmd_str = ' '.join(cmd)
                if 'merge1' in cmd_str and 'abc123' in cmd_str:
                    return command.CommandResult(stdout=merge1_log)
                if 'merge2' in cmd_str and 'merge1' in cmd_str:
                    return command.CommandResult(stdout=merge2_log)
                return command.CommandResult(stdout=merge2_log)

            command.TEST_RESULT = mock_git

            info, err = control.get_next_commits(dbs, 'us/next')
            self.assertIsNone(err)
            self.assertTrue(info.merge_found)
            # Should return commits from second merge (first was skipped)
            self.assertEqual(len(info.commits), 2)
            self.assertEqual(info.commits[0].chash, 'ccc333c')
            self.assertEqual(info.commits[1].chash, 'merge2m')
            dbs.close()


class TestDetectSubMerges(unittest.TestCase):
    """Tests for detect_sub_merges function."""

    def tearDown(self):
        """Clean up test fixtures."""
        command.TEST_RESULT = None

    def test_not_a_merge(self):
        """Test detect_sub_merges returns empty for non-merge commit."""
        # Single parent means not a merge
        command.TEST_RESULT = command.CommandResult(stdout='abc123\n')
        result = control.detect_sub_merges('abc123')
        self.assertEqual(result, [])

    def test_no_sub_merges(self):
        """Test detect_sub_merges returns empty when no sub-merges exist."""
        call_count = [0]

        def mock_git(pipe_list):  # pylint: disable=unused-argument
            call_count[0] += 1
            if call_count[0] == 1:
                # rev-parse ^@ returns two parents (it's a merge)
                return command.CommandResult(stdout='parent1\nparent2\n')
            # log --merges returns empty (no sub-merges)
            return command.CommandResult(stdout='')

        command.TEST_RESULT = mock_git
        result = control.detect_sub_merges('merge123')
        self.assertEqual(result, [])

    def test_found_sub_merges(self):
        """Test detect_sub_merges finds sub-merges."""
        call_count = [0]

        def mock_git(pipe_list):  # pylint: disable=unused-argument
            call_count[0] += 1
            if call_count[0] == 1:
                # rev-parse ^@ returns two parents
                return command.CommandResult(stdout='parent1\nparent2\n')
            # log --merges returns sub-merge hashes
            return command.CommandResult(
                stdout='sub_merge1\nsub_merge2\nsub_merge3\n')

        command.TEST_RESULT = mock_git
        result = control.detect_sub_merges('mega_merge')
        self.assertEqual(result, ['sub_merge1', 'sub_merge2', 'sub_merge3'])

    def test_error_handling(self):
        """Test detect_sub_merges returns empty on git error."""
        def mock_git_fail(**_kwargs):
            raise command.CommandExc('git error', command.CommandResult())

        command.TEST_RESULT = mock_git_fail
        result = control.detect_sub_merges('bad_hash')
        self.assertEqual(result, [])


class TestDecomposeMegaMerge(unittest.TestCase):
    """Tests for decompose_mega_merge function."""

    def setUp(self):
        """Set up test fixtures."""
        fd, self.db_path = tempfile.mkstemp(suffix='.db')
        os.close(fd)
        os.unlink(self.db_path)
        database.Database.instances.clear()

    def tearDown(self):
        """Clean up test fixtures."""
        if os.path.exists(self.db_path):
            os.unlink(self.db_path)
        database.Database.instances.clear()
        command.TEST_RESULT = None

    def test_first_batch_mainline(self):
        """Test decompose returns mainline commits first."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'base')
            dbs.commit()

            call_count = [0]

            def mock_git(pipe_list):  # pylint: disable=unused-argument
                call_count[0] += 1
                if call_count[0] == 1:
                    # rev-parse ^@ for mega-merge parents
                    return command.CommandResult(
                        stdout='first_parent\nsecond_parent\n')
                if call_count[0] == 2:
                    # log -1 for mega-merge subject/author (pre-add)
                    return command.CommandResult(
                        stdout='Mega merge subject|Author\n')
                if call_count[0] == 3:
                    # Mainline commits (prev..first_parent)
                    return command.CommandResult(
                        stdout='aaa|aaa1|A|Mainline commit|base\n')
                return command.CommandResult(stdout='')

            command.TEST_RESULT = mock_git

            commits, advance_to = control.decompose_mega_merge(
                dbs, 'base', 'mega_hash', ['sub1', 'sub2'])

            self.assertEqual(len(commits), 1)
            self.assertEqual(commits[0].chash, 'aaa1')
            self.assertEqual(advance_to, 'first_parent')
            dbs.close()

    def test_sub_merge_batch(self):
        """Test decompose returns sub-merge batch when mainline is done."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'base')
            dbs.commit()

            call_count = [0]

            def mock_git(pipe_list):  # pylint: disable=unused-argument
                call_count[0] += 1
                if call_count[0] == 1:
                    # rev-parse ^@ for mega-merge parents
                    return command.CommandResult(
                        stdout='first_parent\nsecond_parent\n')
                if call_count[0] == 2:
                    # log -1 for mega-merge subject/author
                    return command.CommandResult(
                        stdout='Mega merge|Author\n')
                if call_count[0] == 3:
                    # Mainline commits - empty (already processed)
                    return command.CommandResult(stdout='')
                if call_count[0] == 4:
                    # Sub-merge 1 commits
                    return command.CommandResult(
                        stdout='bbb|bbb1|B|Sub commit 1|first_parent\n'
                               'ccc|ccc1|C|Sub commit 2|bbb\n')
                return command.CommandResult(stdout='')

            command.TEST_RESULT = mock_git

            commits, advance_to = control.decompose_mega_merge(
                dbs, 'base', 'mega_hash', ['sub1', 'sub2'])

            self.assertEqual(len(commits), 2)
            self.assertEqual(commits[0].chash, 'bbb1')
            self.assertIsNone(advance_to)
            dbs.close()

    def test_skips_processed_sub_merge(self):
        """Test decompose skips sub-merges already in database."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'base')
            dbs.commit()

            # Add sub-merge 1 commits to database
            source_id = dbs.source_get_id('us/next')
            dbs.commit_add('bbb', source_id, 'Sub commit 1', 'B',
                           status='applied')
            dbs.commit()

            call_count = [0]

            def mock_git(pipe_list):  # pylint: disable=unused-argument
                call_count[0] += 1
                if call_count[0] == 1:
                    return command.CommandResult(
                        stdout='first_parent\nsecond_parent\n')
                if call_count[0] == 2:
                    return command.CommandResult(
                        stdout='Mega merge|Author\n')
                if call_count[0] == 3:
                    # Mainline - empty
                    return command.CommandResult(stdout='')
                if call_count[0] == 4:
                    # Sub-merge 1 commits (already in DB)
                    return command.CommandResult(
                        stdout='bbb|bbb1|B|Sub commit 1|first_parent\n')
                if call_count[0] == 5:
                    # Sub-merge 2 commits (not in DB)
                    return command.CommandResult(
                        stdout='ddd|ddd1|D|Sub commit 3|sub1\n')
                return command.CommandResult(stdout='')

            command.TEST_RESULT = mock_git

            commits, advance_to = control.decompose_mega_merge(
                dbs, 'base', 'mega_hash', ['sub1', 'sub2'])

            self.assertEqual(len(commits), 1)
            self.assertEqual(commits[0].chash, 'ddd1')
            self.assertIsNone(advance_to)
            dbs.close()

    def test_all_done(self):
        """Test decompose returns empty when all sub-merges are processed."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'base')
            dbs.commit()

            # Add all commits to database
            source_id = dbs.source_get_id('us/next')
            dbs.commit_add('bbb', source_id, 'Sub commit 1', 'B',
                           status='applied')
            dbs.commit_add('ddd', source_id, 'Sub commit 2', 'D',
                           status='applied')
            dbs.commit()

            call_count = [0]

            def mock_git(pipe_list):  # pylint: disable=too-many-return-statements,unused-argument
                call_count[0] += 1
                if call_count[0] == 1:
                    return command.CommandResult(
                        stdout='first_parent\nsecond_parent\n')
                if call_count[0] == 2:
                    return command.CommandResult(
                        stdout='Mega merge|Author\n')
                if call_count[0] == 3:
                    # Mainline - empty
                    return command.CommandResult(stdout='')
                if call_count[0] == 4:
                    # Sub-merge 1
                    return command.CommandResult(
                        stdout='bbb|bbb1|B|Sub commit 1|first_parent\n')
                if call_count[0] == 5:
                    # Sub-merge 2
                    return command.CommandResult(
                        stdout='ddd|ddd1|D|Sub commit 2|sub1\n')
                if call_count[0] == 6:
                    # Remainder - empty
                    return command.CommandResult(stdout='')
                return command.CommandResult(stdout='')

            command.TEST_RESULT = mock_git

            commits, advance_to = control.decompose_mega_merge(
                dbs, 'base', 'mega_hash', ['sub1', 'sub2'])

            self.assertEqual(len(commits), 0)
            self.assertIsNone(advance_to)
            dbs.close()


class TestGetNextCommitsMegaMerge(unittest.TestCase):
    """Tests for get_next_commits with mega-merges."""

    def setUp(self):
        """Set up test fixtures."""
        fd, self.db_path = tempfile.mkstemp(suffix='.db')
        os.close(fd)
        os.unlink(self.db_path)
        database.Database.instances.clear()

    def tearDown(self):
        """Clean up test fixtures."""
        if os.path.exists(self.db_path):
            os.unlink(self.db_path)
        database.Database.instances.clear()
        command.TEST_RESULT = None

    def test_returns_sub_batch(self):
        """Test get_next_commits returns sub-merge batch for mega-merge."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'base')
            dbs.commit()

            call_count = [0]

            def mock_git(pipe_list):  # pylint: disable=too-many-return-statements,unused-argument
                call_count[0] += 1
                if call_count[0] == 1:
                    # First-parent log shows one mega-merge
                    return command.CommandResult(
                        stdout='mega|mega1|A|Merge branch next|'
                               'base second_parent\n')
                if call_count[0] == 2:
                    # Subtree check: log -1 --format=%s
                    return command.CommandResult(
                        stdout='Merge branch next')
                if call_count[0] == 3:
                    # detect_sub_merges: rev-parse ^@
                    return command.CommandResult(
                        stdout='base\nsecond_parent\n')
                if call_count[0] == 4:
                    # detect_sub_merges: log --merges (found sub-merges)
                    return command.CommandResult(stdout='sub1\n')
                if call_count[0] == 5:
                    # decompose: rev-parse ^@ for mega-merge
                    return command.CommandResult(
                        stdout='base\nsecond_parent\n')
                if call_count[0] == 6:
                    # decompose: log -1 for mega-merge info
                    return command.CommandResult(
                        stdout='Mega merge|Author\n')
                if call_count[0] == 7:
                    # decompose: mainline commits (empty)
                    return command.CommandResult(stdout='')
                if call_count[0] == 8:
                    # decompose: sub-merge 1 commits
                    return command.CommandResult(
                        stdout='aaa|aaa1|A|Sub commit|base\n')
                return command.CommandResult(stdout='')

            command.TEST_RESULT = mock_git

            info, err = control.get_next_commits(dbs, 'us/next')

            self.assertIsNone(err)
            self.assertTrue(info.merge_found)
            self.assertEqual(len(info.commits), 1)
            self.assertEqual(info.commits[0].chash, 'aaa1')
            # Sub-merge batch: advance_to should be None
            self.assertIsNone(info.advance_to)
            dbs.close()

    def test_all_done_advances_past(self):
        """Test get_next_commits advances past fully-processed mega-merge."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'base')
            dbs.commit()

            # Add all sub-merge commits to database
            source_id = dbs.source_get_id('us/next')
            dbs.commit_add('aaa', source_id, 'Sub commit', 'A',
                           status='applied')
            dbs.commit()

            call_count = [0]

            def mock_git(pipe_list):  # pylint: disable=too-many-return-statements,unused-argument
                call_count[0] += 1
                if call_count[0] == 1:
                    # First-parent log shows mega-merge
                    return command.CommandResult(
                        stdout='mega|mega1|A|Merge branch next|'
                               'base second_parent\n')
                if call_count[0] == 2:
                    # Subtree check: log -1 --format=%s
                    return command.CommandResult(
                        stdout='Merge branch next')
                if call_count[0] == 3:
                    # detect_sub_merges: rev-parse ^@
                    return command.CommandResult(
                        stdout='base\nsecond_parent\n')
                if call_count[0] == 4:
                    # detect_sub_merges: log --merges
                    return command.CommandResult(stdout='sub1\n')
                if call_count[0] == 5:
                    # decompose: rev-parse ^@
                    return command.CommandResult(
                        stdout='base\nsecond_parent\n')
                if call_count[0] == 6:
                    # decompose: log -1 for mega-merge info
                    return command.CommandResult(
                        stdout='Mega merge|Author\n')
                if call_count[0] == 7:
                    # decompose: mainline (empty)
                    return command.CommandResult(stdout='')
                if call_count[0] == 8:
                    # decompose: sub-merge 1 (in DB)
                    return command.CommandResult(
                        stdout='aaa|aaa1|A|Sub commit|base\n')
                if call_count[0] == 9:
                    # decompose: remainder (empty)
                    return command.CommandResult(stdout='')
                if call_count[0] == 10:
                    # Remaining commits after mega-merge (empty)
                    return command.CommandResult(stdout='')
                return command.CommandResult(stdout='')

            command.TEST_RESULT = mock_git

            info, err = control.get_next_commits(dbs, 'us/next')

            self.assertIsNone(err)
            self.assertFalse(info.merge_found)
            self.assertEqual(len(info.commits), 0)
            # Should advance past the mega-merge
            self.assertEqual(info.advance_to, 'mega')
            dbs.close()

    def test_normal_merge_returns_advance_to(self):
        """Test get_next_commits returns advance_to for normal merges."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'base')
            dbs.commit()

            call_count = [0]

            def mock_git(pipe_list):  # pylint: disable=unused-argument
                call_count[0] += 1
                if call_count[0] == 1:
                    # First-parent log shows a normal merge
                    return command.CommandResult(
                        stdout='merge1|m1|A|Merge branch feat|'
                               'base side1\n')
                if call_count[0] == 2:
                    # Subtree check: log -1 --format=%s
                    return command.CommandResult(
                        stdout='Merge branch feat')
                if call_count[0] == 3:
                    # detect_sub_merges: rev-parse ^@
                    return command.CommandResult(
                        stdout='base\nside1\n')
                if call_count[0] == 4:
                    # detect_sub_merges: log --merges (no sub-merges)
                    return command.CommandResult(stdout='')
                if call_count[0] == 5:
                    # Commits for this merge
                    return command.CommandResult(
                        stdout='aaa|aaa1|A|Commit 1|base\n'
                               'merge1|m1|A|Merge branch feat|'
                               'base side1\n')
                return command.CommandResult(stdout='')

            command.TEST_RESULT = mock_git

            info, err = control.get_next_commits(dbs, 'us/next')

            self.assertIsNone(err)
            self.assertTrue(info.merge_found)
            self.assertEqual(len(info.commits), 2)
            # Normal merge: advance_to is the merge hash
            self.assertEqual(info.advance_to, 'merge1')
            dbs.close()


class TestSubtreeMergeDetection(unittest.TestCase):
    """Tests for subtree merge detection in find_unprocessed_commits."""

    def setUp(self):
        """Set up test fixtures."""
        fd, self.db_path = tempfile.mkstemp(suffix='.db')
        os.close(fd)
        os.unlink(self.db_path)
        database.Database.instances.clear()

    def tearDown(self):
        """Clean up test fixtures."""
        if os.path.exists(self.db_path):
            os.unlink(self.db_path)
        database.Database.instances.clear()
        command.TEST_RESULT = None

    def test_detects_dts_subtree_merge(self):
        """Test find_unprocessed_commits detects dts/upstream subtree merge."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'base')
            dbs.commit()

            command.TEST_RESULT = command.CommandResult(
                stdout="Subtree merge tag 'v6.15-dts' of "
                       "https://example.com/dts.git into dts/upstream")

            info = control.find_unprocessed_commits(
                dbs, 'base', 'us/next', ['merge1'])

            self.assertTrue(info.merge_found)
            self.assertEqual(info.commits, [])
            self.assertEqual(info.advance_to, 'merge1')
            self.assertEqual(info.subtree_update, ('dts', 'v6.15-dts'))
            dbs.close()

    def test_detects_mbedtls_subtree_merge(self):
        """Test find_unprocessed_commits detects mbedtls subtree merge."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'base')
            dbs.commit()

            command.TEST_RESULT = command.CommandResult(
                stdout="Subtree merge tag 'v3.6.2' of "
                       "https://example.com/mbedtls.git into "
                       "lib/mbedtls/external/mbedtls")

            info = control.find_unprocessed_commits(
                dbs, 'base', 'us/next', ['merge1'])

            self.assertEqual(info.subtree_update,
                             ('mbedtls', 'v3.6.2'))
            dbs.close()

    def test_detects_lwip_subtree_merge(self):
        """Test find_unprocessed_commits detects lwip subtree merge."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'base')
            dbs.commit()

            command.TEST_RESULT = command.CommandResult(
                stdout="Subtree merge tag 'STABLE-2_2_0' of "
                       "https://example.com/lwip.git into lib/lwip/lwip")

            info = control.find_unprocessed_commits(
                dbs, 'base', 'us/next', ['merge1'])

            self.assertEqual(info.subtree_update,
                             ('lwip', 'STABLE-2_2_0'))
            dbs.close()

    def test_skips_unknown_subtree_path(self):
        """Test find_unprocessed_commits skips unknown subtree paths."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'base')
            dbs.commit()

            call_count = [0]

            def mock_git(pipe_list):  # pylint: disable=unused-argument
                call_count[0] += 1
                if call_count[0] == 1:
                    # Subject for merge1: unknown subtree
                    return command.CommandResult(
                        stdout="Subtree merge tag 'v1.0' of "
                               "https://x.com/x.git into lib/unknown")
                if call_count[0] == 2:
                    # Subject for merge2: not a subtree merge
                    return command.CommandResult(
                        stdout='Normal merge commit')
                if call_count[0] == 3:
                    # detect_sub_merges: rev-parse ^@
                    return command.CommandResult(
                        stdout='merge1\nside1\n')
                if call_count[0] == 4:
                    # detect_sub_merges: log --merges (no sub-merges)
                    return command.CommandResult(stdout='')
                if call_count[0] == 5:
                    # Commits for merge2
                    return command.CommandResult(
                        stdout='aaa|aaa1|A|Commit 1|merge1\n')
                return command.CommandResult(stdout='')

            command.TEST_RESULT = mock_git

            info = control.find_unprocessed_commits(
                dbs, 'base', 'us/next', ['merge1', 'merge2'])

            # Should have skipped merge1 and found commits in merge2
            self.assertIsNone(info.subtree_update)
            self.assertTrue(info.merge_found)
            self.assertEqual(len(info.commits), 1)
            self.assertEqual(info.commits[0].chash, 'aaa1')
            dbs.close()

    def test_subtree_merge_via_get_next_commits(self):
        """Test get_next_commits returns subtree_update for subtree merge."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'base')
            dbs.commit()

            call_count = [0]

            def mock_git(pipe_list):  # pylint: disable=unused-argument
                call_count[0] += 1
                if call_count[0] == 1:
                    # First-parent log shows one merge
                    return command.CommandResult(
                        stdout='merge1|m1|A|Subtree merge tag '
                               "'v6.15-dts' of https://x.com/dts.git"
                               ' into dts/upstream|base second\n')
                if call_count[0] == 2:
                    # find_unprocessed: log -1 --format=%s for merge1
                    return command.CommandResult(
                        stdout="Subtree merge tag 'v6.15-dts' of "
                               "https://x.com/dts.git into "
                               "dts/upstream")
                return command.CommandResult(stdout='')

            command.TEST_RESULT = mock_git

            info, err = control.get_next_commits(dbs, 'us/next')

            self.assertIsNone(err)
            self.assertEqual(info.subtree_update, ('dts', 'v6.15-dts'))
            self.assertEqual(info.advance_to, 'merge1')
            self.assertEqual(info.commits, [])
            dbs.close()

    def test_non_subtree_merge_has_no_subtree_update(self):
        """Test normal merges have subtree_update=None."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'base')
            dbs.commit()

            call_count = [0]

            def mock_git(pipe_list):  # pylint: disable=unused-argument
                call_count[0] += 1
                if call_count[0] == 1:
                    # Subject: not a subtree merge
                    return command.CommandResult(
                        stdout='Merge branch some-feature')
                if call_count[0] == 2:
                    # detect_sub_merges: rev-parse ^@
                    return command.CommandResult(
                        stdout='base\nside1\n')
                if call_count[0] == 3:
                    # detect_sub_merges: log --merges (no sub-merges)
                    return command.CommandResult(stdout='')
                if call_count[0] == 4:
                    # Commits in merge
                    return command.CommandResult(
                        stdout='aaa|aaa1|A|Commit 1|base\n')
                return command.CommandResult(stdout='')

            command.TEST_RESULT = mock_git

            info = control.find_unprocessed_commits(
                dbs, 'base', 'us/next', ['merge1'])

            self.assertIsNone(info.subtree_update)
            self.assertTrue(info.merge_found)
            self.assertEqual(len(info.commits), 1)
            dbs.close()


class TestApplySubtreeUpdate(unittest.TestCase):
    """Tests for apply_subtree_update function."""

    def setUp(self):
        """Set up test fixtures."""
        fd, self.db_path = tempfile.mkstemp(suffix='.db')
        os.close(fd)
        os.unlink(self.db_path)
        database.Database.instances.clear()

    def tearDown(self):
        """Clean up test fixtures."""
        if os.path.exists(self.db_path):
            os.unlink(self.db_path)
        database.Database.instances.clear()
        command.TEST_RESULT = None

    def test_apply_success(self):
        """Test apply_subtree_update succeeds and updates database."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'base')
            dbs.commit()

            args = argparse.Namespace(push=False, remote='ci',
                                      target='master')

            def run_git_handler(git_args):
                if 'rev-parse' in git_args:
                    # Parents of merge: first_parent squash_hash
                    return 'first_parent\nsquash_hash'
                if 'checkout' in git_args:
                    return ''
                if '--format=%s|%an' in git_args:
                    if 'squash_hash' in git_args:
                        return "Squashed 'dts/upstream/' changes|Author"
                    return "Subtree merge tag 'v6.15-dts'|Author"
                return ''

            mock_result = command.CommandResult(
                'Subtree updated', '', '', 0)
            with mock.patch.object(control, 'run_git',
                                   side_effect=run_git_handler):
                with mock.patch.object(
                        control.command, 'run_one',
                        return_value=mock_result):
                    ret = control.apply_subtree_update(
                        dbs, 'us/next', 'dts', 'v6.15-dts',
                        'merge_hash', 'ci', 'master',
                        push=args.push)

            self.assertEqual(ret, 0)

            # Source should be advanced past the merge
            self.assertEqual(dbs.source_get('us/next'), 'merge_hash')

            # Both commits should be in the database
            squash = dbs.commit_get('squash_hash')
            self.assertIsNotNone(squash)
            merge = dbs.commit_get('merge_hash')
            self.assertIsNotNone(merge)
            dbs.close()

    def test_apply_with_push(self):
        """Test apply_subtree_update pushes when args.push is True."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'base')
            dbs.commit()

            args = argparse.Namespace(push=True, remote='ci',
                                      target='master')

            def run_git_handler(git_args):
                if 'rev-parse' in git_args:
                    return 'first_parent\nsquash_hash'
                if 'checkout' in git_args:
                    return ''
                if '--format=%s|%an' in git_args:
                    return 'Commit subject|Author'
                return ''

            pushed = [False]

            def mock_push(remote, branch, skip_ci=False):
                pushed[0] = True
                return True

            mock_result = command.CommandResult('ok', '', '', 0)
            with mock.patch.object(control, 'run_git',
                                   side_effect=run_git_handler):
                with mock.patch.object(
                        control.command, 'run_one',
                        return_value=mock_result):
                    with mock.patch.object(
                            control.gitlab_api, 'push_branch',
                            side_effect=mock_push):
                        ret = control.apply_subtree_update(
                            dbs, 'us/next', 'dts', 'v6.15-dts',
                            'merge_hash', 'ci', 'master',
                            push=args.push)

            self.assertEqual(ret, 0)
            self.assertTrue(pushed[0])
            dbs.close()

    def test_apply_push_defaults_to_true(self):
        """Test apply_subtree_update pushes when push is not specified."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'base')
            dbs.commit()

            def run_git_handler(git_args):
                if 'rev-parse' in git_args:
                    return 'first_parent\nsquash_hash'
                if 'checkout' in git_args:
                    return ''
                if '--format=%s|%an' in git_args:
                    return 'Commit subject|Author'
                return ''

            pushed = [False]

            def mock_push(remote, branch, skip_ci=False):
                pushed[0] = True
                return True

            mock_result = command.CommandResult('ok', '', '', 0)
            with mock.patch.object(control, 'run_git',
                                   side_effect=run_git_handler):
                with mock.patch.object(
                        control.command, 'run_one',
                        return_value=mock_result):
                    with mock.patch.object(
                            control.gitlab_api, 'push_branch',
                            side_effect=mock_push):
                        ret = control.apply_subtree_update(
                            dbs, 'us/next', 'dts', 'v6.15-dts',
                            'merge_hash', 'ci', 'master')

            self.assertEqual(ret, 0)
            self.assertTrue(pushed[0])
            dbs.close()

    def test_apply_checkout_failure(self):
        """Test apply_subtree_update returns 1 on checkout failure."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'base')
            dbs.commit()

            args = argparse.Namespace(push=False, remote='ci',
                                      target='master')

            def run_git_handler(git_args):
                if 'rev-parse' in git_args:
                    return 'first_parent\nsquash_hash'
                if 'checkout' in git_args:
                    raise command.CommandExc('checkout failed', None)
                return ''

            with mock.patch.object(control, 'run_git',
                                   side_effect=run_git_handler):
                ret = control.apply_subtree_update(
                    dbs, 'us/next', 'dts', 'v6.15-dts',
                    'merge_hash', 'ci', 'master',
                    push=args.push)

            self.assertEqual(ret, 1)
            # Source should not be advanced
            self.assertEqual(dbs.source_get('us/next'), 'base')
            dbs.close()

    def test_apply_checkout_fallback(self):
        """Test apply_subtree_update falls back to -b when checkout fails."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'base')
            dbs.commit()

            args = argparse.Namespace(push=False, remote='ci',
                                      target='master')

            checkout_calls = []

            def run_git_handler(git_args):
                if 'rev-parse' in git_args:
                    return 'first_parent\nsquash_hash'
                if 'checkout' in git_args:
                    checkout_calls.append(list(git_args))
                    if '-b' not in git_args:
                        raise command.CommandExc(
                            'ambiguous checkout', None)
                    return ''
                if 'log' in git_args:
                    return 'subject|author'
                return ''

            with mock.patch.object(control, 'run_git',
                                   side_effect=run_git_handler):
                with mock.patch.object(control, '_subtree_run_update',
                                       return_value=0):
                    ret = control.apply_subtree_update(
                        dbs, 'us/next', 'dts', 'v6.15-dts',
                        'merge_hash', 'ci', 'master',
                        push=args.push)

            self.assertEqual(ret, 0)
            # Should have tried bare checkout, then fallback
            self.assertEqual(len(checkout_calls), 2)
            self.assertEqual(checkout_calls[0], ['checkout', 'master'])
            self.assertEqual(checkout_calls[1],
                             ['checkout', '-b', 'master', 'ci/master'])
            dbs.close()

    def test_apply_no_second_parent(self):
        """Test apply_subtree_update returns 1 when merge has no 2nd parent."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'base')
            dbs.commit()

            args = argparse.Namespace(push=False, remote='ci',
                                      target='master')

            # Only one parent
            with mock.patch.object(control, 'run_git',
                                   return_value='single_parent'):
                ret = control.apply_subtree_update(
                    dbs, 'us/next', 'dts', 'v6.15-dts',
                    'merge_hash', 'ci', 'master',
                    push=args.push)

            self.assertEqual(ret, 1)
            dbs.close()

    def test_apply_script_exception(self):
        """Test apply_subtree_update returns 1 on script exception."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'base')
            dbs.commit()

            args = argparse.Namespace(push=False, remote='ci',
                                      target='master')

            def run_git_handler(git_args):
                if 'rev-parse' in git_args:
                    return 'first_parent\nsquash_hash'
                if 'checkout' in git_args:
                    return ''
                return ''

            with mock.patch.object(control, 'run_git',
                                   side_effect=run_git_handler):
                with mock.patch.object(
                        control.command, 'run_one',
                        side_effect=Exception('script failed')):
                    ret = control.apply_subtree_update(
                        dbs, 'us/next', 'dts', 'v6.15-dts',
                        'merge_hash', 'ci', 'master',
                        push=args.push)

            self.assertEqual(ret, 1)
            # Source should not be advanced
            self.assertEqual(dbs.source_get('us/next'), 'base')
            dbs.close()

    def test_apply_merge_conflict(self):
        """Test apply_subtree_update aborts merge on non-conflict failure."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'base')
            dbs.commit()

            args = argparse.Namespace(push=False, remote='ci',
                                      target='master')

            merge_aborted = [False]

            def run_git_handler(git_args):
                if 'rev-parse' in git_args:
                    if '--verify' in git_args:
                        raise Exception('no MERGE_HEAD')
                    return 'first_parent\nsquash_hash'
                if 'checkout' in git_args:
                    return ''
                if 'merge' in git_args and '--abort' in git_args:
                    merge_aborted[0] = True
                    return ''
                return ''

            mock_result = command.CommandResult(
                '', 'CONFLICT (content): Merge conflict', '', 1)
            with mock.patch.object(control, 'run_git',
                                   side_effect=run_git_handler):
                with mock.patch.object(
                        control.command, 'run_one',
                        return_value=mock_result):
                    ret = control.apply_subtree_update(
                        dbs, 'us/next', 'dts', 'v6.15-dts',
                        'merge_hash', 'ci', 'master',
                        push=args.push)

            self.assertEqual(ret, 1)
            self.assertTrue(merge_aborted[0])
            # Source should not be advanced
            self.assertEqual(dbs.source_get('us/next'), 'base')
            dbs.close()

    def test_apply_merge_conflict_agent_resolves(self):
        """Test apply_subtree_update invokes agent on conflict and succeeds."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'base')
            dbs.commit()

            args = argparse.Namespace(push=False, remote='ci',
                                      target='master')

            def run_git_handler(git_args):
                if 'rev-parse' in git_args:
                    if '--verify' in git_args:
                        return 'abc123'
                    return 'first_parent\nsquash_hash'
                if 'checkout' in git_args:
                    return ''
                if '--format=%s|%an' in git_args:
                    return 'subject|author'
                return ''

            mock_result = command.CommandResult(
                '', 'CONFLICT (content): Merge conflict', '', 1)
            with mock.patch.object(control, 'run_git',
                                   side_effect=run_git_handler):
                with mock.patch.object(
                        control.command, 'run_one',
                        return_value=mock_result):
                    with mock.patch.object(
                            agent, 'resolve_subtree_conflicts',
                            return_value=(True, 'resolved ok')):
                        ret = control.apply_subtree_update(
                            dbs, 'us/next', 'dts', 'v6.15-dts',
                            'merge_hash', 'ci', 'master',
                            push=args.push)

            self.assertEqual(ret, 0)
            # Source should be advanced
            self.assertEqual(dbs.source_get('us/next'), 'merge_hash')
            dbs.close()

    def test_apply_merge_conflict_agent_fails(self):
        """Test apply_subtree_update aborts when agent fails to resolve."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'base')
            dbs.commit()

            args = argparse.Namespace(push=False, remote='ci',
                                      target='master')

            merge_aborted = [False]

            def run_git_handler(git_args):
                if 'rev-parse' in git_args:
                    if '--verify' in git_args:
                        return 'abc123'
                    return 'first_parent\nsquash_hash'
                if 'checkout' in git_args:
                    return ''
                if 'merge' in git_args and '--abort' in git_args:
                    merge_aborted[0] = True
                    return ''
                return ''

            mock_result = command.CommandResult(
                '', 'CONFLICT (content): Merge conflict', '', 1)
            with mock.patch.object(control, 'run_git',
                                   side_effect=run_git_handler):
                with mock.patch.object(
                        control.command, 'run_one',
                        return_value=mock_result):
                    with mock.patch.object(
                            agent, 'resolve_subtree_conflicts',
                            return_value=(False, 'failed')):
                        ret = control.apply_subtree_update(
                            dbs, 'us/next', 'dts', 'v6.15-dts',
                            'merge_hash', 'ci', 'master',
                            push=args.push)

            self.assertEqual(ret, 1)
            self.assertTrue(merge_aborted[0])
            # Source should not be advanced
            self.assertEqual(dbs.source_get('us/next'), 'base')
            dbs.close()


class TestPrepareApplySubtreeUpdate(unittest.TestCase):
    """Tests for prepare_apply handling of subtree updates."""

    def setUp(self):
        """Set up test fixtures."""
        fd, self.db_path = tempfile.mkstemp(suffix='.db')
        os.close(fd)
        os.unlink(self.db_path)
        self.old_db_fname = control.DB_FNAME
        control.DB_FNAME = self.db_path
        database.Database.instances.clear()

    def tearDown(self):
        """Clean up test fixtures."""
        control.DB_FNAME = self.old_db_fname
        if os.path.exists(self.db_path):
            os.unlink(self.db_path)
        database.Database.instances.clear()
        command.TEST_RESULT = None

    def test_prepare_apply_calls_subtree_update(self):
        """Test prepare_apply applies subtree update and retries."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'base')
            dbs.commit()

            subtree_info = control.NextCommitsInfo(
                [], True, 'merge1', ('dts', 'v6.15-dts'))
            normal_info = control.NextCommitsInfo([], False, None)

            call_count = [0]

            def mock_get_next(dbs_arg, source):
                call_count[0] += 1
                if call_count[0] == 1:
                    return subtree_info, None
                return normal_info, None

            with mock.patch.object(control, 'get_next_commits',
                                   side_effect=mock_get_next):
                with mock.patch.object(
                        control, 'apply_subtree_update',
                        return_value=0) as mock_apply:
                    info, ret = control.prepare_apply(
                        dbs, 'us/next', None, 'ci', 'master')

            # Should have called apply_subtree_update
            mock_apply.assert_called_once_with(
                dbs, 'us/next', 'dts', 'v6.15-dts', 'merge1',
                'ci', 'master')
            # No commits after retry, so returns None/0
            self.assertIsNone(info)
            self.assertEqual(ret, 0)
            dbs.close()

    def test_prepare_apply_subtree_update_failure(self):
        """Test prepare_apply returns error when subtree update fails."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'base')
            dbs.commit()

            subtree_info = control.NextCommitsInfo(
                [], True, 'merge1', ('dts', 'v6.15-dts'))

            with mock.patch.object(control, 'get_next_commits',
                                   return_value=(subtree_info, None)):
                with mock.patch.object(
                        control, 'apply_subtree_update',
                        return_value=1):
                    info, ret = control.prepare_apply(
                        dbs, 'us/next', None, 'ci', 'master')

            self.assertIsNone(info)
            self.assertEqual(ret, 1)
            dbs.close()

    def test_prepare_apply_subtree_without_remote(self):
        """Test prepare_apply returns error when subtree needs remote=None."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'base')
            dbs.commit()

            subtree_info = control.NextCommitsInfo(
                [], True, 'merge1', ('dts', 'v6.15-dts'))

            with mock.patch.object(control, 'get_next_commits',
                                   return_value=(subtree_info, None)):
                info, ret = control.prepare_apply(
                    dbs, 'us/next', None)

            self.assertIsNone(info)
            self.assertEqual(ret, 1)
            dbs.close()


class TestNextCommitsInfoDefault(unittest.TestCase):
    """Tests for NextCommitsInfo subtree_update default value."""

    def test_default_subtree_update_is_none(self):
        """Test NextCommitsInfo defaults subtree_update to None."""
        info = control.NextCommitsInfo([], False, None)
        self.assertIsNone(info.subtree_update)

    def test_explicit_subtree_update(self):
        """Test NextCommitsInfo accepts explicit subtree_update."""
        info = control.NextCommitsInfo([], True, 'hash1',
                                       ('dts', 'v6.15-dts'))
        self.assertEqual(info.subtree_update, ('dts', 'v6.15-dts'))

    def test_explicit_none_subtree_update(self):
        """Test NextCommitsInfo accepts explicit None subtree_update."""
        info = control.NextCommitsInfo([], False, None, None)
        self.assertIsNone(info.subtree_update)


class TestSubtreeMergeRegex(unittest.TestCase):
    """Tests for RE_SUBTREE_MERGE regex pattern."""

    def test_matches_dts_merge(self):
        """Test regex matches dts subtree merge subject."""
        subject = ("Subtree merge tag 'v6.15-dts' of "
                   "https://git.kernel.org/pub/scm/linux/kernel/git/"
                   "devicetree/devicetree-rebasing.git into dts/upstream")
        match = control.RE_SUBTREE_MERGE.match(subject)
        self.assertIsNotNone(match)
        self.assertEqual(match.group(1), 'v6.15-dts')
        self.assertEqual(match.group(2), 'dts/upstream')

    def test_matches_mbedtls_merge(self):
        """Test regex matches mbedtls subtree merge subject."""
        subject = ("Subtree merge tag 'v3.6.2' of "
                   "https://github.com/Mbed-TLS/mbedtls.git into "
                   "lib/mbedtls/external/mbedtls")
        match = control.RE_SUBTREE_MERGE.match(subject)
        self.assertIsNotNone(match)
        self.assertEqual(match.group(1), 'v3.6.2')
        self.assertEqual(match.group(2), 'lib/mbedtls/external/mbedtls')

    def test_matches_lwip_merge(self):
        """Test regex matches lwip subtree merge subject."""
        subject = ("Subtree merge tag 'STABLE-2_2_0' of "
                   "https://git.savannah.gnu.org/git/lwip.git into "
                   "lib/lwip/lwip")
        match = control.RE_SUBTREE_MERGE.match(subject)
        self.assertIsNotNone(match)
        self.assertEqual(match.group(1), 'STABLE-2_2_0')
        self.assertEqual(match.group(2), 'lib/lwip/lwip')

    def test_no_match_normal_merge(self):
        """Test regex does not match normal merge subjects."""
        subject = "Merge branch 'feature-xyz' into main"
        match = control.RE_SUBTREE_MERGE.match(subject)
        self.assertIsNone(match)

    def test_no_match_squash_commit(self):
        """Test regex does not match subtree squash commits."""
        subject = ("Squashed 'dts/upstream/' changes from "
                   "v6.14-dts..v6.15-dts")
        match = control.RE_SUBTREE_MERGE.match(subject)
        self.assertIsNone(match)


class TestDoCommitSourceResolveError(unittest.TestCase):
    """Tests for do_commit_source error handling."""

    def setUp(self):
        """Set up test fixtures."""
        fd, self.db_path = tempfile.mkstemp(suffix='.db')
        os.close(fd)
        os.unlink(self.db_path)
        self.old_db_fname = control.DB_FNAME
        control.DB_FNAME = self.db_path
        database.Database.instances.clear()

    def tearDown(self):
        """Clean up test fixtures."""
        control.DB_FNAME = self.old_db_fname
        if os.path.exists(self.db_path):
            os.unlink(self.db_path)
        database.Database.instances.clear()
        command.TEST_RESULT = None

    def test_commit_source_resolve_error(self):
        """Test commit-source fails when commit can't be resolved."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'oldcommit12345')
            dbs.commit()

        database.Database.instances.clear()

        def mock_git_fail(**_kwargs):
            raise command.CommandExc('git error', command.CommandResult())

        command.TEST_RESULT = mock_git_fail

        args = argparse.Namespace(cmd='commit-source', source='us/next',
                                  commit='badcommit')
        with terminal.capture() as (_, stderr):
            ret = control.do_commit_source(args, None)
        self.assertEqual(ret, 1)
        self.assertIn('Could not resolve', stderr.getvalue())


class TestRewind(unittest.TestCase):
    """Tests for rewind command."""

    def setUp(self):
        """Set up test fixtures."""
        fd, self.db_path = tempfile.mkstemp(suffix='.db')
        os.close(fd)
        os.unlink(self.db_path)
        self.old_db_fname = control.DB_FNAME
        control.DB_FNAME = self.db_path
        database.Database.instances.clear()

    def tearDown(self):
        """Clean up test fixtures."""
        control.DB_FNAME = self.old_db_fname
        if os.path.exists(self.db_path):
            os.unlink(self.db_path)
        database.Database.instances.clear()
        command.TEST_RESULT = None

    def test_rewind_source_not_found(self):
        """Test rewind with unknown source."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.close()

        database.Database.instances.clear()

        args = argparse.Namespace(cmd='rewind', source='unknown', count=1,
                                  force=True, remote='ci')
        with terminal.capture() as (_, stderr):
            ret = control.do_pickman(args)
        self.assertEqual(ret, 1)
        self.assertIn("Source 'unknown' not found", stderr.getvalue())

    def test_rewind_dry_run(self):
        """Test rewind dry run shows what would happen without executing."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'current_hash')
            source_id = dbs.source_get_id('us/next')
            dbs.commit_add('commit_a', source_id, 'Commit A', 'Author')
            dbs.commit_add('commit_b', source_id, 'Commit B', 'Author')
            dbs.commit()
            dbs.close()

        database.Database.instances.clear()

        def mock_git(pipe_list):
            cmd = pipe_list[0] if pipe_list else []
            if '--merges' in cmd:
                return command.CommandResult(
                    stdout='current_hash|current1|Current merge\n'
                           'prev_hash|prev1234|Previous merge\n')
            if 'rev-list' in cmd:
                return command.CommandResult(
                    stdout='commit_a\ncommit_b\n')
            if 'branch' in cmd and '--list' in cmd:
                return command.CommandResult(stdout='')
            return command.CommandResult(stdout='')

        command.TEST_RESULT = mock_git

        args = argparse.Namespace(cmd='rewind', source='us/next', count=1,
                                  force=False, remote='ci')
        with terminal.capture() as (stdout, _):
            ret = control.do_pickman(args)
        self.assertEqual(ret, 0)
        output = stdout.getvalue()
        self.assertIn('dry run', output)
        self.assertIn('prev1234', output)
        self.assertIn('2', output)  # 2 commits to delete
        self.assertIn('--force', output)

        # Verify database was NOT modified
        database.Database.instances.clear()
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            self.assertEqual(dbs.source_get('us/next'), 'current_hash')
            self.assertIsNotNone(dbs.commit_get('commit_a'))
            self.assertIsNotNone(dbs.commit_get('commit_b'))
            dbs.close()

    def test_rewind_one_merge(self):
        """Test rewinding by one merge with --force."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'current_hash')
            source_id = dbs.source_get_id('us/next')
            # Add some commits that should be deleted
            dbs.commit_add('commit_a', source_id, 'Commit A', 'Author')
            dbs.commit_add('commit_b', source_id, 'Commit B', 'Author')
            dbs.commit()
            dbs.close()

        database.Database.instances.clear()

        def mock_git(pipe_list):
            cmd = pipe_list[0] if pipe_list else []
            if '--merges' in cmd:
                return command.CommandResult(
                    stdout='current_hash|current1|Current merge\n'
                           'prev_hash|prev1234|Previous merge\n')
            if 'rev-list' in cmd:
                return command.CommandResult(
                    stdout='commit_a\ncommit_b\n')
            if 'branch' in cmd and '--list' in cmd:
                return command.CommandResult(stdout='')
            return command.CommandResult(stdout='')

        command.TEST_RESULT = mock_git

        args = argparse.Namespace(cmd='rewind', source='us/next', count=1,
                                  force=True, remote='ci')
        with terminal.capture() as (stdout, _):
            ret = control.do_pickman(args)
        self.assertEqual(ret, 0)
        output = stdout.getvalue()
        self.assertIn('prev1234', output)
        self.assertIn('Deleted 2 commit(s)', output)

        # Verify source was updated
        database.Database.instances.clear()
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            self.assertEqual(dbs.source_get('us/next'), 'prev_hash')
            # Commits should be deleted
            self.assertIsNone(dbs.commit_get('commit_a'))
            self.assertIsNone(dbs.commit_get('commit_b'))
            dbs.close()

    def test_rewind_shows_mr_details(self):
        """Test rewind shows MR numbers, titles and URLs."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'current_hash')
            dbs.commit()
            dbs.close()

        database.Database.instances.clear()

        def mock_git(pipe_list):
            cmd = pipe_list[0] if pipe_list else []
            if '--merges' in cmd:
                return command.CommandResult(
                    stdout='current_hash|current1|Current merge\n'
                           'prev_hash|prev1234|Previous merge\n')
            if 'rev-list' in cmd:
                return command.CommandResult(
                    stdout='abc1234ffffff\ndef5678aaaaaa\n')
            if 'branch' in cmd and '--list' in cmd:
                return command.CommandResult(
                    stdout='  ci/cherry-abc1234f\n'
                           '  ci/cherry-other99\n')
            return command.CommandResult(stdout='')

        command.TEST_RESULT = mock_git

        mock_mrs = [
            gitlab.PickmanMr(
                iid=541, title='[pickman] Some cherry-pick',
                web_url='https://gitlab.com/proj/-/merge_requests/541',
                source_branch='cherry-abc1234f',
                description='desc'),
            gitlab.PickmanMr(
                iid=540, title='[pickman] Unrelated MR',
                web_url='https://gitlab.com/proj/-/merge_requests/540',
                source_branch='cherry-zzz9999',
                description='desc'),
        ]

        args = argparse.Namespace(cmd='rewind', source='us/next', count=1,
                                  force=False, remote='ci')
        with mock.patch.object(gitlab, 'get_open_pickman_mrs',
                               return_value=mock_mrs):
            with terminal.capture() as (stdout, _):
                ret = control.do_pickman(args)
        self.assertEqual(ret, 0)
        output = stdout.getvalue()
        self.assertIn('!541', output)
        self.assertIn('[pickman] Some cherry-pick', output)
        self.assertIn('merge_requests/541', output)
        # Unrelated MR should not appear
        self.assertNotIn('!540', output)
        self.assertIn('MRs to delete', output)

    def test_rewind_shows_branches_when_api_unavailable(self):
        """Test rewind falls back to branch names when GitLab unavailable."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'current_hash')
            dbs.commit()
            dbs.close()

        database.Database.instances.clear()

        def mock_git(pipe_list):
            cmd = pipe_list[0] if pipe_list else []
            if '--merges' in cmd:
                return command.CommandResult(
                    stdout='current_hash|current1|Current merge\n'
                           'prev_hash|prev1234|Previous merge\n')
            if 'rev-list' in cmd:
                return command.CommandResult(
                    stdout='abc1234ffffff\n')
            if 'branch' in cmd and '--list' in cmd:
                return command.CommandResult(
                    stdout='  ci/cherry-abc1234f\n')
            return command.CommandResult(stdout='')

        command.TEST_RESULT = mock_git

        args = argparse.Namespace(cmd='rewind', source='us/next', count=1,
                                  force=False, remote='ci')
        # GitLab API returns None (unavailable)
        with mock.patch.object(gitlab, 'get_open_pickman_mrs',
                               return_value=None):
            with terminal.capture() as (stdout, _):
                ret = control.do_pickman(args)
        self.assertEqual(ret, 0)
        output = stdout.getvalue()
        self.assertIn('cherry-abc1234f', output)
        self.assertIn('Branches to check', output)

    def test_rewind_two_merges(self):
        """Test rewinding by two merges with --force."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'current_hash')
            dbs.commit()
            dbs.close()

        database.Database.instances.clear()

        def mock_git(pipe_list):
            cmd = pipe_list[0] if pipe_list else []
            if '--merges' in cmd:
                return command.CommandResult(
                    stdout='current_hash|current1|Current merge\n'
                           'mid_hash|mid12345|Middle merge\n'
                           'old_hash|old12345|Old merge\n')
            if 'rev-list' in cmd:
                return command.CommandResult(stdout='')
            if 'branch' in cmd and '--list' in cmd:
                return command.CommandResult(stdout='')
            return command.CommandResult(stdout='')

        command.TEST_RESULT = mock_git

        args = argparse.Namespace(cmd='rewind', source='us/next', count=2,
                                  force=True, remote='ci')
        with terminal.capture() as (stdout, _):
            ret = control.do_pickman(args)
        self.assertEqual(ret, 0)
        self.assertIn('old12345', stdout.getvalue())

        # Verify source was updated to old_hash
        database.Database.instances.clear()
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            self.assertEqual(dbs.source_get('us/next'), 'old_hash')
            dbs.close()

    def test_rewind_not_enough_merges(self):
        """Test rewind fails when not enough merges in history."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'current_hash')
            dbs.commit()
            dbs.close()

        database.Database.instances.clear()

        def mock_git(pipe_list):
            cmd = pipe_list[0] if pipe_list else []
            if '--merges' in cmd:
                # Only one merge (the current position)
                return command.CommandResult(
                    stdout='current_hash|current1|Current merge\n')
            return command.CommandResult(stdout='')

        command.TEST_RESULT = mock_git

        args = argparse.Namespace(cmd='rewind', source='us/next', count=1,
                                  force=True, remote='ci')
        with terminal.capture() as (_, stderr):
            ret = control.do_pickman(args)
        self.assertEqual(ret, 1)
        self.assertIn('Not enough merges', stderr.getvalue())

    def test_parse_rewind(self):
        """Test parsing rewind command."""
        args = pickman.parse_args(['rewind', 'us/next'])
        self.assertEqual(args.cmd, 'rewind')
        self.assertEqual(args.source, 'us/next')
        self.assertEqual(args.count, 1)
        self.assertFalse(args.force)
        self.assertEqual(args.remote, 'ci')

    def test_parse_rewind_with_count(self):
        """Test parsing rewind command with count."""
        args = pickman.parse_args(['rewind', 'us/next', '-c', '3'])
        self.assertEqual(args.cmd, 'rewind')
        self.assertEqual(args.source, 'us/next')
        self.assertEqual(args.count, 3)

    def test_parse_rewind_with_force(self):
        """Test parsing rewind command with --force."""
        args = pickman.parse_args(['rewind', 'us/next', '-c', '2', '-f'])
        self.assertEqual(args.cmd, 'rewind')
        self.assertEqual(args.count, 2)
        self.assertTrue(args.force)


class TestDoPushBranch(unittest.TestCase):
    """Tests for do_push_branch command."""

    def test_push_branch_success(self):
        """Test successful push."""
        tout.init(tout.INFO)
        args = argparse.Namespace(cmd='push-branch', branch='test-branch',
                                  remote='ci', force=False, run_ci=False)
        with mock.patch.object(gitlab, 'push_branch',
                               return_value=True) as mock_push:
            with terminal.capture():
                ret = control.do_push_branch(args, None)
        self.assertEqual(ret, 0)
        mock_push.assert_called_once_with('ci', 'test-branch', False,
                                          skip_ci=True)

    def test_push_branch_force(self):
        """Test force push."""
        tout.init(tout.INFO)
        args = argparse.Namespace(cmd='push-branch', branch='test-branch',
                                  remote='origin', force=True, run_ci=False)
        with mock.patch.object(gitlab, 'push_branch',
                               return_value=True) as mock_push:
            with terminal.capture():
                ret = control.do_push_branch(args, None)
        self.assertEqual(ret, 0)
        mock_push.assert_called_once_with('origin', 'test-branch', True,
                                          skip_ci=True)

    def test_push_branch_failure(self):
        """Test push failure."""
        tout.init(tout.INFO)
        args = argparse.Namespace(cmd='push-branch', branch='test-branch',
                                  remote='ci', force=False, run_ci=False)
        with mock.patch.object(
                gitlab, 'push_branch',
                side_effect=command.CommandExc(
                    'push failed', command.CommandResult())):
            with terminal.capture():
                ret = control.do_push_branch(args, None)
        self.assertEqual(ret, 1)


class TestDoPickmanUnknownCommand(unittest.TestCase):
    """Tests for do_pickman with unknown command."""

    def setUp(self):
        """Set up test fixtures."""
        fd, self.db_path = tempfile.mkstemp(suffix='.db')
        os.close(fd)
        os.unlink(self.db_path)
        self.old_db_fname = control.DB_FNAME
        control.DB_FNAME = self.db_path
        database.Database.instances.clear()

    def tearDown(self):
        """Clean up test fixtures."""
        control.DB_FNAME = self.old_db_fname
        if os.path.exists(self.db_path):
            os.unlink(self.db_path)
        database.Database.instances.clear()

    def test_unknown_command(self):
        """Test do_pickman returns 1 for unknown command."""
        args = argparse.Namespace(cmd='unknown-command')
        with terminal.capture():
            ret = control.do_pickman(args)
        self.assertEqual(ret, 1)


class TestDoReviewWithMrs(unittest.TestCase):
    """Tests for do_review with open MRs."""

    def test_review_with_mrs_no_comments(self):
        """Test review with open MRs but no comments."""
        tout.init(tout.INFO)

        mock_mr = gitlab.PickmanMr(
            iid=123,
            title='[pickman] Test MR',
            web_url='https://gitlab.com/mr/123',
            source_branch='cherry-test',
            description='Test',
        )
        with mock.patch.object(control, 'run_git'):
            with mock.patch.object(gitlab, 'get_open_pickman_mrs',
                                   return_value=[mock_mr]):
                with mock.patch.object(gitlab, 'get_mr_comments',
                                       return_value=[]):
                    args = argparse.Namespace(cmd='review', remote='ci',
                                              target='master')
                    with terminal.capture() as (stdout, _):
                        ret = control.do_review(args, None)

        self.assertEqual(ret, 0)
        self.assertIn('Found 1 open pickman MR', stdout.getvalue())


class TestProcessMergedMrs(unittest.TestCase):
    """Tests for process_merged_mrs function."""

    def setUp(self):
        """Set up test fixtures."""
        fd, self.db_path = tempfile.mkstemp(suffix='.db')
        os.close(fd)
        os.unlink(self.db_path)
        database.Database.instances.clear()

    def tearDown(self):
        """Clean up test fixtures."""
        if os.path.exists(self.db_path):
            os.unlink(self.db_path)
        database.Database.instances.clear()
        command.TEST_RESULT = None

    def test_process_merged_mrs_updates_newer(self):
        """Test that newer commits update the database."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next', 'aaa111aaa111aaa111aaa111aaa111aaa111aaa')
            dbs.commit()

            merged_mrs = [gitlab.PickmanMr(
                iid=100,
                title='[pickman] Test MR',
                description='## 2025-01-01: us/next\n\n- bbb222b Subject',
                source_branch='cherry-test',
                web_url='https://gitlab.com/mr/100',
            )]

            def mock_git(args):
                if args[0] == 'rev-parse':
                    return 'bbb222bbb222bbb222bbb222bbb222bbb222bbb2'
                if args[0] == 'merge-base':
                    # current is ancestor of last_hash (newer)
                    return ''
                return ''

            with mock.patch.object(gitlab, 'get_merged_pickman_mrs',
                                   return_value=merged_mrs):
                with mock.patch.object(control, 'run_git', mock_git):
                    processed = control.process_merged_mrs('ci', 'us/next', dbs)

            self.assertEqual(processed, 1)
            new_commit = dbs.source_get('us/next')
            self.assertEqual(new_commit,
                             'bbb222bbb222bbb222bbb222bbb222bbb222bbb2')

            dbs.close()

    def test_process_merged_mrs_skips_older(self):
        """Test that older commits don't update the database."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()
            dbs.source_set('us/next',
                              'bbb222bbb222bbb222bbb222bbb222bbb222bbb2')
            dbs.commit()

            merged_mrs = [gitlab.PickmanMr(
                iid=100,
                title='[pickman] Test MR',
                description='## 2025-01-01: us/next\n\n- aaa111a Subject',
                source_branch='cherry-test',
                web_url='https://gitlab.com/mr/100',
            )]

            def mock_git(args):
                if args[0] == 'rev-parse':
                    return 'aaa111aaa111aaa111aaa111aaa111aaa111aaa1'
                if args[0] == 'merge-base':
                    # current is NOT ancestor of last_hash (older)
                    raise RuntimeError('Not an ancestor')
                return ''

            with mock.patch.object(gitlab, 'get_merged_pickman_mrs',
                                   return_value=merged_mrs):
                with mock.patch.object(control, 'run_git', mock_git):
                    processed = control.process_merged_mrs('ci', 'us/next', dbs)

            self.assertEqual(processed, 0)
            # Should remain unchanged
            current = dbs.source_get('us/next')
            self.assertEqual(current,
                             'bbb222bbb222bbb222bbb222bbb222bbb222bbb2')

            dbs.close()


class TestCheck(unittest.TestCase):
    """Tests for check command."""

    def setUp(self):
        """Set up test fixtures."""
        self.old_branch = 'old-branch'

    def test_parse_git_stat_output(self):
        """Test parsing git show --stat output."""
        stat_output = """commit abc123def456
Author: Test Author <test@example.com>
Date:   Mon Jan 15 10:30:00 2024 -0600

    Test commit message

 file1.c | 15 +++++++++++++++
 file2.h |  3 +--
 2 files changed, 16 insertions(+), 2 deletions(-)"""

        result = control.parse_git_stat_output(stat_output)
        files, insertions, deletions, file_set = result
        self.assertEqual(files, 2)
        self.assertEqual(insertions, 16)
        self.assertEqual(deletions, 2)
        self.assertEqual(file_set, {'file1.c', 'file2.h'})

    def test_parse_git_stat_output_empty(self):
        """Test parsing empty git show --stat output."""
        stat_output = """commit abc123def456
Author: Test Author <test@example.com>
Date:   Mon Jan 15 10:30:00 2024 -0600

    Empty commit message

 0 files changed"""

        result = control.parse_git_stat_output(stat_output)
        files, insertions, deletions, file_set = result
        self.assertEqual(files, 0)
        self.assertEqual(insertions, 0)
        self.assertEqual(deletions, 0)
        self.assertEqual(file_set, set())

    def test_calc_ratio_identical(self):
        """Test delta ratio calculation for identical commits."""
        orig_stats = control.GitStat(2, 15, 3, {'file1.c', 'file2.h'})
        cherry_stats = control.GitStat(2, 15, 3, {'file1.c', 'file2.h'})

        ratio = control.calc_ratio(orig_stats, cherry_stats)
        self.assertEqual(ratio, 0.0)

    def test_calc_ratio_different_files(self):
        """Test delta ratio calculation for different files."""
        orig_stats = control.GitStat(2, 15, 3, {'file1.c', 'file2.h'})
        cherry_stats = control.GitStat(
            3, 15, 3, {'file1.c', 'file2.h', 'file3.c'})

        ratio = control.calc_ratio(orig_stats, cherry_stats)
        self.assertGreater(ratio, 0.0)
        self.assertLessEqual(ratio, 1.0)

    def test_calc_ratio_different_lines(self):
        """Test delta ratio calculation for different line counts."""
        orig_stats = control.GitStat(2, 15, 3, {'file1.c', 'file2.h'})
        cherry_stats = control.GitStat(2, 30, 6, {'file1.c', 'file2.h'})

        ratio = control.calc_ratio(orig_stats, cherry_stats)
        self.assertGreater(ratio, 0.0)
        self.assertLessEqual(ratio, 1.0)

    def test_get_orig_commit(self):
        """Test finding original commit from cherry-pick message."""
        with mock.patch('pickman.control.run_git') as mock_run_git:
            commit_msg = """Test commit subject

This is the commit body.

(cherry picked from commit abc123def456789)
"""
            mock_run_git.return_value = commit_msg

            orig = control.get_orig_commit('def456abc123')
            self.assertEqual(orig, 'abc123def456789')

    def test_get_orig_commit_not_cherry_pick(self):
        """Test finding original commit for non-cherry-pick."""
        with mock.patch('pickman.control.run_git') as mock_run_git:
            commit_msg = """Test commit subject

This is a normal commit without cherry-pick info.
"""
            mock_run_git.return_value = commit_msg

            orig = control.get_orig_commit('def456abc123')
            self.assertIsNone(orig)

    def test_check_commits_no_commits(self):
        """Test check_commits with empty commit list."""
        commits = []
        results = list(control.check_commits(commits, 10))
        self.assertEqual(len(results), 0)

    def test_check_commits_large_delta(self):
        """Test check_commits finding commits with large deltas."""
        commits = [('abc123', 'abc123d', 'Test commit subject')]

        with mock.patch('pickman.control.run_git') as mock_run_git:
            with mock.patch('pickman.control.get_orig_commit') as \
                    mock_find_orig:
                with mock.patch('pickman.control.parse_git_stat_output') as \
                        mock_parse:
                    with mock.patch('pickman.control.calc_ratio') as mock_calc:
                        # Mock responses
                        mock_run_git.side_effect = [
                            ['def456'],  # parents (single parent)
                            'orig_stat_output',  # original commit stats
                            'cherry_stat_output'  # cherry-pick commit stats
                        ]
                        mock_find_orig.return_value = 'def456original'
                        mock_parse.side_effect = [
                            control.GitStat(2, 15, 3, {'file1.c', 'file2.h'}),
                            control.GitStat(3, 30, 6,
                                            {'file1.c', 'file2.h', 'file3.c'})
                        ]
                        mock_calc.return_value = 0.5  # 50% delta

                        results = list(control.check_commits(commits, 10))
                        self.assertEqual(len(results), 1)

                        result = results[0]
                        self.assertEqual(result.chash, 'abc123')
                        self.assertEqual(result.orig_hash, 'def456original')
                        self.assertEqual(result.delta_ratio, 0.5)
                        self.assertIsNone(result.reason)

    def test_check_commits_normal_commit(self):
        """Test check_commits processing a normal commit."""
        commits = [('abc123', 'abc123d', 'Test commit subject')]

        with mock.patch('pickman.control.run_git') as mock_run_git:
            with mock.patch('pickman.control.get_orig_commit') as \
                    mock_find_orig:
                with mock.patch('pickman.control.parse_git_stat_output') as \
                        mock_parse:
                    with mock.patch('pickman.control.calc_ratio') as mock_calc:
                        # Mock responses
                        mock_run_git.side_effect = [
                            ['def456'],  # parents (single parent)
                            'orig_stat_output',  # original commit stats
                            'cherry_stat_output'  # cherry-pick commit stats
                        ]
                        mock_find_orig.return_value = 'def456original'
                        mock_parse.side_effect = [
                            control.GitStat(2, 15, 3, {'file1.c', 'file2.h'}),
                            control.GitStat(3, 30, 6,
                                            {'file1.c', 'file2.h', 'file3.c'})
                        ]
                        mock_calc.return_value = 0.1  # 10% delta (low)

                        results = list(control.check_commits(commits, 10))
                        self.assertEqual(len(results), 1)

                        result = results[0]
                        self.assertEqual(result.chash, 'abc123')
                        self.assertEqual(result.orig_hash, 'def456original')
                        self.assertEqual(result.subject, 'Test commit subject')
                        self.assertEqual(result.delta_ratio, 0.1)
                        self.assertIsNone(result.reason)

    def test_check_commits_merge_skip(self):
        """Test check_commits skips merge commits."""
        commits = [('abc123', 'abc123d', 'Merge branch feature')]

        with mock.patch('pickman.control.run_git') as mock_run_git:
            # Mock multiple parents (merge commit)
            mock_run_git.return_value = ['parent1', 'parent2']

            results = list(control.check_commits(commits, 10))
            self.assertEqual(len(results), 1)

            result = results[0]
            self.assertEqual(result.reason, 'merge_commit')

    def test_check_commits_small_commit_skip(self):
        """Test check_commits skips small commits."""
        commits = [('abc123', 'abc123d', 'Fix typo')]

        with mock.patch('pickman.control.run_git') as mock_run_git:
            with mock.patch('pickman.control.get_orig_commit') as \
                    mock_find_orig:
                with mock.patch('pickman.control.parse_git_stat_output') as \
                        mock_parse:
                    # Mock responses for small commit
                    mock_run_git.side_effect = [
                        ['def456'],  # single parent
                        'orig_stat_output',
                        'cherry_stat_output'
                    ]
                    mock_find_orig.return_value = 'def456original'
                    mock_parse.side_effect = [
                        # 3 total lines (< 10)
                        control.GitStat(1, 2, 1, {'file1.c'}),
                        control.GitStat(1, 2, 1, {'file1.c'})
                    ]

                    results = list(control.check_commits(commits, 10))
                    self.assertEqual(len(results), 1)

                    result = results[0]
                    self.assertEqual(result.reason, 'small_commit_3_lines')

    @mock.patch('pickman.control.command')
    @mock.patch('pickman.control.run_git')
    @mock.patch('tempfile.NamedTemporaryFile')
    @mock.patch('os.unlink')
    def test_show_commit_diff_with_colour(self, unused_unlink, mock_temp,
                                         mock_run_git, mock_command):
        """Test show_commit_diff with colour enabled."""
        # Mock temporary files
        mock_temp.side_effect = [
            mock.mock_open()(),  # orig file
            mock.mock_open()()   # cherry file
        ]
        mock_temp.return_value.__enter__.return_value.name = '/tmp/test.patch'

        # Mock git show outputs
        mock_run_git.side_effect = [
            'orig patch content',
            'cherry patch content'
        ]

        # Mock diff command output
        mock_command.output.return_value = 'diff output'

        # Test data
        res = control.CheckResult(
            chash='abc123',
            orig_hash='def456',
            subject='Test',
            delta_ratio=0.5,
            orig_stats=None,
            cherry_stats=None,
            reason=None
        )

        with terminal.capture():
            control.show_commit_diff(res, no_colour=False)

        # Verify git show was called for both commits
        expected_calls = [
            mock.call(['show', '--no-ext-diff', 'def456']),
            mock.call(['show', '--no-ext-diff', 'abc123'])
        ]
        mock_run_git.assert_has_calls(expected_calls)

        # Verify diff was called with colour
        mock_command.output.assert_called_once()
        args, kwargs = mock_command.output.call_args
        self.assertIn('--color=always', args)
        self.assertEqual(kwargs.get('raise_on_error'), False)

    @mock.patch('pickman.control.command')
    @mock.patch('pickman.control.run_git')
    @mock.patch('tempfile.NamedTemporaryFile')
    @mock.patch('os.unlink')
    def test_show_commit_diff_no_colour(self, unused_unlink, mock_temp,
                                       mock_run_git, mock_command):
        """Test show_commit_diff with colour disabled."""
        # Mock temporary files
        mock_temp.side_effect = [
            mock.mock_open()(),  # orig file
            mock.mock_open()()   # cherry file
        ]
        mock_temp.return_value.__enter__.return_value.name = '/tmp/test.patch'

        # Mock git show outputs
        mock_run_git.side_effect = [
            'orig patch content',
            'cherry patch content'
        ]

        # Mock diff command output
        mock_command.output.return_value = 'diff output'

        # Test data
        res = control.CheckResult(
            chash='abc123',
            orig_hash='def456',
            subject='Test',
            delta_ratio=0.5,
            orig_stats=None,
            cherry_stats=None,
            reason=None
        )

        with terminal.capture():
            control.show_commit_diff(res, no_colour=True)

        # Verify diff was called without colour
        mock_command.output.assert_called_once()
        args, kwargs = mock_command.output.call_args
        self.assertNotIn('--color=always', args)
        self.assertEqual(kwargs.get('raise_on_error'), False)


class TestCheckAlreadyApplied(unittest.TestCase):
    """Tests for the check_already_applied function."""

    def setUp(self):
        """Set up test data."""
        self.commits = [
            control.CommitInfo('abc123def456', 'abc123d', 'Add new feature',
                               'Author <email>'),
            control.CommitInfo('def456abc123', 'def456a', 'Fix bug',
                               'Author <email>')
        ]
        self.quoted_commit = [
            control.CommitInfo('abc123def456', 'abc123d',
                               'Add "quoted" feature', 'Author <email>')
        ]
        self.single_commit = [
            control.CommitInfo('abc123def456', 'abc123d', 'Add new feature',
                               'Author <email>')
        ]

    @mock.patch('pickman.control.run_git')
    @mock.patch('pickman.control.tout')
    def test_check_already_applied_none_applied(self, mock_tout, mock_run_git):
        """Test check_already_applied when no commits are already applied."""
        # Mock git log returning empty (no matches)
        mock_run_git.return_value = ''

        new_commits, applied = control.check_already_applied(self.commits)

        self.assertEqual(len(new_commits), 2)
        self.assertEqual(len(applied), 0)
        self.assertEqual(new_commits, self.commits)
        mock_tout.info.assert_not_called()

    @mock.patch('pickman.control.run_git')
    @mock.patch('pickman.control.tout')
    def test_check_already_applied_some_applied(self, mock_tout, mock_run_git):
        """Test check_already_applied when some commits are already applied."""
        # First commit returns a match, second doesn't
        mock_run_git.side_effect = ['xyz789 Add new feature', '']

        new_commits, applied = control.check_already_applied(self.commits)

        self.assertEqual(len(new_commits), 1)
        self.assertEqual(len(applied), 1)
        self.assertEqual(new_commits[0].hash, 'def456abc123')
        self.assertEqual(applied[0].hash, 'abc123def456')
        mock_tout.info.assert_called_once()

    @mock.patch('pickman.control.run_git')
    @mock.patch('pickman.control.tout')
    def test_check_already_applied_all_applied(self, mock_tout, mock_run_git):
        """Test check_already_applied when all commits are already applied."""
        # Both commits return matches
        mock_run_git.side_effect = ['xyz789 Add new feature', 'uvw123 Fix bug']

        new_commits, applied = control.check_already_applied(self.commits)

        self.assertEqual(len(new_commits), 0)
        self.assertEqual(len(applied), 2)
        self.assertEqual(applied, self.commits)
        self.assertEqual(mock_tout.info.call_count, 2)

    @mock.patch('pickman.control.run_git')
    @mock.patch('pickman.control.tout')
    def test_check_already_applied_with_quotes_in_subject(
            self, unused_mock_tout, mock_run_git):
        """Test check_already_applied handles quotes in commit subjects."""
        mock_run_git.return_value = ''

        new_commits, applied = control.check_already_applied(self.quoted_commit)

        # Verify git was called with escaped quotes
        mock_run_git.assert_called_once_with([
            'log', '--oneline', 'ci/master',
            '--grep=Add \\"quoted\\" feature', '-1'
        ])
        self.assertEqual(len(new_commits), 1)
        self.assertEqual(len(applied), 0)

    @mock.patch('pickman.control.run_git')
    @mock.patch('pickman.control.tout')
    def test_check_already_applied_git_error(self, unused_mock_tout,
                                             mock_run_git):
        """Test check_already_applied handles git errors gracefully."""
        # Mock git command raising an exception
        mock_run_git.side_effect = Exception('Git error')

        new_commits, applied = control.check_already_applied(self.single_commit)

        # Should treat as not applied when git fails
        self.assertEqual(len(new_commits), 1)
        self.assertEqual(len(applied), 0)
        self.assertEqual(new_commits, self.single_commit)


class TestGetCommitsForPick(unittest.TestCase):
    """Tests for get_commits_for_pick function."""

    @mock.patch('pickman.control.run_git')
    def test_commit_range(self, mock_run_git):
        """Test parsing a commit range."""
        mock_run_git.return_value = (
            'aaa111|aaa111a|Author1|First commit\n'
            'bbb222|bbb222b|Author2|Second commit'
        )

        commits, err = control.get_commits_for_pick('abc123..def456')

        self.assertIsNone(err)
        self.assertEqual(len(commits), 2)
        self.assertEqual(commits[0].hash, 'aaa111')
        self.assertEqual(commits[0].chash, 'aaa111a')
        self.assertEqual(commits[0].subject, 'First commit')
        self.assertEqual(commits[1].hash, 'bbb222')
        mock_run_git.assert_called_with([
            'log', '--reverse', '--format=%H|%h|%an|%s', 'abc123..def456'
        ])

    @mock.patch('pickman.control.run_git')
    def test_commit_range_empty(self, mock_run_git):
        """Test empty commit range returns error."""
        mock_run_git.return_value = ''

        commits, err = control.get_commits_for_pick('abc123..abc123')

        self.assertEqual(commits, [])
        self.assertIn('No commits found', err)

    @mock.patch('pickman.control.run_git')
    def test_commit_range_invalid(self, mock_run_git):
        """Test invalid commit range returns error."""
        mock_run_git.side_effect = Exception('bad revision')

        commits, err = control.get_commits_for_pick('invalid..range')

        self.assertIsNone(commits)
        self.assertIn('Invalid commit range', err)

    @mock.patch('pickman.control.run_git')
    def test_single_commit_non_merge(self, mock_run_git):
        """Test single non-merge commit returns just that commit."""
        def git_handler(args):
            if 'rev-parse' in args:
                return 'parent123'  # Single parent = not a merge
            return 'abc123full|abc123|Author|Single commit'

        mock_run_git.side_effect = git_handler

        commits, err = control.get_commits_for_pick('abc123')

        self.assertIsNone(err)
        self.assertEqual(len(commits), 1)
        self.assertEqual(commits[0].hash, 'abc123full')
        self.assertEqual(commits[0].subject, 'Single commit')

    @mock.patch('pickman.control.run_git')
    def test_merge_commit(self, mock_run_git):
        """Test merge commit returns all child commits."""
        def git_handler(args):
            if 'rev-parse' in args:
                # Two parents = merge commit
                return 'parent1\nparent2'
            if '^parent1' in args:
                return (
                    'ccc333|ccc333c|Author1|Child commit 1\n'
                    'ddd444|ddd444d|Author2|Child commit 2'
                )
            return ''

        mock_run_git.side_effect = git_handler

        commits, err = control.get_commits_for_pick('merge123')

        self.assertIsNone(err)
        self.assertEqual(len(commits), 2)
        self.assertEqual(commits[0].hash, 'ccc333')
        self.assertEqual(commits[1].hash, 'ddd444')

    @mock.patch('pickman.control.run_git')
    def test_merge_commit_empty(self, mock_run_git):
        """Test merge commit with no children returns error."""
        def git_handler(args):
            if 'rev-parse' in args:
                return 'parent1\nparent2'
            return ''

        mock_run_git.side_effect = git_handler

        commits, err = control.get_commits_for_pick('merge123')

        self.assertEqual(commits, [])
        self.assertIn('No commits found in merge', err)

    @mock.patch('pickman.control.run_git')
    def test_invalid_single_commit(self, mock_run_git):
        """Test invalid single commit returns error."""
        mock_run_git.side_effect = Exception('unknown revision')

        commits, err = control.get_commits_for_pick('badcommit')

        self.assertIsNone(commits)
        self.assertIn('Invalid commit', err)

    @mock.patch('pickman.control.run_git')
    def test_subject_with_separator(self, mock_run_git):
        """Test commit subject containing pipe character."""
        mock_run_git.return_value = 'aaa111|aaa111a|Author|Subject|with|pipes'

        commits, err = control.get_commits_for_pick('abc..def')

        self.assertIsNone(err)
        self.assertEqual(commits[0].subject, 'Subject|with|pipes')


class TestParsePick(unittest.TestCase):
    """Tests for parsing pick command arguments."""

    def test_parse_pick_basic(self):
        """Test parsing basic pick command."""
        args = pickman.parse_args(['pick', 'abc123..def456'])
        self.assertEqual(args.cmd, 'pick')
        self.assertEqual(args.commits, 'abc123..def456')
        self.assertIsNone(args.branch)
        self.assertFalse(args.push)

    def test_parse_pick_with_branch(self):
        """Test parsing pick command with branch."""
        args = pickman.parse_args(['pick', 'abc123', '-b', 'my-branch'])
        self.assertEqual(args.commits, 'abc123')
        self.assertEqual(args.branch, 'my-branch')

    def test_parse_pick_with_push(self):
        """Test parsing pick command with push options."""
        args = pickman.parse_args([
            'pick', 'abc123..def456', '-p', '-r', 'origin', '-t', 'main'
        ])
        self.assertTrue(args.push)
        self.assertEqual(args.remote, 'origin')
        self.assertEqual(args.target, 'main')


class TestDoPick(unittest.TestCase):
    """Tests for do_pick function."""

    def setUp(self):
        """Set up test fixtures."""
        fd, self.db_path = tempfile.mkstemp(suffix='.db')
        os.close(fd)
        os.unlink(self.db_path)
        self.old_db_fname = control.DB_FNAME
        control.DB_FNAME = self.db_path
        database.Database.instances.clear()

    def tearDown(self):
        """Clean up test fixtures."""
        control.DB_FNAME = self.old_db_fname
        if os.path.exists(self.db_path):
            os.unlink(self.db_path)
        database.Database.instances.clear()

    def test_pick_error(self):
        """Test do_pick with invalid commit spec."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()

            args = argparse.Namespace(commits='invalid..range', branch=None,
                                      push=False)

            with mock.patch.object(control, 'get_commits_for_pick',
                                   return_value=(None, 'Invalid commit')):
                ret = control.do_pick(args, dbs)

            self.assertEqual(ret, 1)
            dbs.close()

    def test_pick_no_commits(self):
        """Test do_pick with empty commit range."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()

            args = argparse.Namespace(commits='abc..abc', branch=None,
                                      push=False)

            with mock.patch.object(control, 'get_commits_for_pick',
                                   return_value=([], None)):
                ret = control.do_pick(args, dbs)

            self.assertEqual(ret, 0)
            dbs.close()

    def test_pick_success(self):
        """Test do_pick with successful cherry-pick."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()

            commits = [control.CommitInfo('aaa111', 'aaa111a', 'Test commit',
                                          'Author')]
            args = argparse.Namespace(commits='abc..def', branch=None,
                                      push=False)

            with mock.patch.object(control, 'get_commits_for_pick',
                                   return_value=(commits, None)):
                with mock.patch.object(control, 'run_git',
                                       return_value='main'):
                    with mock.patch.object(control.agent, 'cherry_pick_commits',
                                           return_value=(True, 'log')):
                        ret = control.do_pick(args, dbs)

            self.assertEqual(ret, 0)
            dbs.close()

    def test_pick_with_custom_branch(self):
        """Test do_pick with custom branch name."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()

            commits = [control.CommitInfo('bbb222', 'bbb222b', 'Test commit',
                                          'Author')]
            args = argparse.Namespace(commits='abc..def', branch='my-branch',
                                      push=False)

            with mock.patch.object(control, 'get_commits_for_pick',
                                   return_value=(commits, None)):
                with mock.patch.object(control, 'run_git',
                                       return_value='main'):
                    with mock.patch.object(
                            control.agent, 'cherry_pick_commits',
                            return_value=(True, 'log')) as mock_agent:
                        ret = control.do_pick(args, dbs)

            # Verify agent was called with correct branch name
            call_args = mock_agent.call_args
            self.assertEqual(call_args[0][2], 'my-branch')
            self.assertEqual(ret, 0)
            dbs.close()

    def test_pick_with_push(self):
        """Test do_pick with push enabled."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()

            commits = [control.CommitInfo('ccc333', 'ccc333c', 'Test commit',
                                          'Author')]
            args = argparse.Namespace(commits='abc..def', branch=None,
                                      push=True, remote='origin', target='main')

            with mock.patch.object(control, 'get_commits_for_pick',
                                   return_value=(commits, None)):
                with mock.patch.object(control, 'run_git',
                                       return_value='main'):
                    with mock.patch.object(control.agent, 'cherry_pick_commits',
                                           return_value=(True, 'log')):
                        with mock.patch.object(gitlab, 'push_and_create_mr',
                                               return_value='https://mr/url'):
                            ret = control.do_pick(args, dbs)

            self.assertEqual(ret, 0)
            dbs.close()

    def test_pick_agent_fails(self):
        """Test do_pick when agent fails."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()

            commits = [control.CommitInfo('ddd444', 'ddd444d', 'Test commit',
                                          'Author')]
            args = argparse.Namespace(commits='abc..def', branch=None,
                                      push=False)

            with mock.patch.object(control, 'get_commits_for_pick',
                                   return_value=(commits, None)):
                with mock.patch.object(control, 'run_git',
                                       return_value='main'):
                    with mock.patch.object(control.agent, 'cherry_pick_commits',
                                           return_value=(False, 'error log')):
                        ret = control.do_pick(args, dbs)

            self.assertEqual(ret, 1)
            dbs.close()

    def test_pick_agent_aborts(self):
        """Test do_pick when agent aborts and branch doesn't exist."""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()

            commits = [control.CommitInfo('eee555', 'eee555e', 'Test commit',
                                          'Author')]
            args = argparse.Namespace(commits='abc..def', branch=None,
                                      push=False)

            def run_git_handler(args):
                if 'branch' in args and '--list' in args:
                    return ''  # Branch doesn't exist
                return 'main'

            with mock.patch.object(control, 'get_commits_for_pick',
                                   return_value=(commits, None)):
                with mock.patch.object(control, 'run_git',
                                       side_effect=run_git_handler):
                    with mock.patch.object(control.agent, 'cherry_pick_commits',
                                           return_value=(True, 'aborted')):
                        ret = control.do_pick(args, dbs)

            self.assertEqual(ret, 1)
            dbs.close()


class TestPickmanMrPipelineFields(unittest.TestCase):
    """Tests for PickmanMr pipeline fields."""

    def test_defaults_none(self):
        """Test that pipeline fields default to None"""
        pmr = gitlab.PickmanMr(
            iid=1,
            title='[pickman] Test',
            web_url='https://example.com/mr/1',
            source_branch='cherry-test',
            description='Test',
        )
        self.assertIsNone(pmr.pipeline_status)
        self.assertIsNone(pmr.pipeline_id)

    def test_with_pipeline(self):
        """Test creating PickmanMr with pipeline fields"""
        pmr = gitlab.PickmanMr(
            iid=1,
            title='[pickman] Test',
            web_url='https://example.com/mr/1',
            source_branch='cherry-test',
            description='Test',
            pipeline_status='failed',
            pipeline_id=42,
        )
        self.assertEqual(pmr.pipeline_status, 'failed')
        self.assertEqual(pmr.pipeline_id, 42)


class TestGetFailedJobs(unittest.TestCase):
    """Tests for get_failed_jobs function."""

    def _make_mock_job(self, job_id, name, stage, web_url, trace_bytes):
        """Helper to create a mock job object"""
        job = mock.MagicMock()
        job.id = job_id
        job.name = name
        job.stage = stage
        job.web_url = web_url
        return job

    @mock.patch.object(gitlab, 'get_remote_url',
                       return_value=TEST_SSH_URL)
    @mock.patch.object(gitlab, 'get_token', return_value='test-token')
    @mock.patch.object(gitlab, 'AVAILABLE', True)
    def test_success(self, _mock_token, _mock_url):
        """Test successful retrieval of failed jobs"""
        mock_job = self._make_mock_job(
            1, 'build:sandbox', 'build', 'https://gitlab.com/job/1',
            b'line1\nline2\nerror: build failed\n')

        mock_full_job = mock.MagicMock()
        mock_full_job.trace.return_value = b'line1\nline2\nerror: build failed\n'

        mock_pipeline = mock.MagicMock()
        mock_pipeline.jobs.list.return_value = [mock_job]

        mock_project = mock.MagicMock()
        mock_project.pipelines.get.return_value = mock_pipeline
        mock_project.jobs.get.return_value = mock_full_job

        mock_glab = mock.MagicMock()
        mock_glab.projects.get.return_value = mock_project

        with mock.patch('gitlab.Gitlab', return_value=mock_glab):
            with terminal.capture():
                result = gitlab.get_failed_jobs('ci', 100)

        self.assertIsNotNone(result)
        self.assertEqual(len(result), 1)
        self.assertEqual(result[0].name, 'build:sandbox')
        self.assertEqual(result[0].stage, 'build')
        self.assertIn('error: build failed', result[0].log_tail)

    @mock.patch.object(gitlab, 'get_remote_url',
                       return_value=TEST_SSH_URL)
    @mock.patch.object(gitlab, 'get_token', return_value='test-token')
    @mock.patch.object(gitlab, 'AVAILABLE', True)
    def test_empty(self, _mock_token, _mock_url):
        """Test when no failed jobs exist"""
        mock_pipeline = mock.MagicMock()
        mock_pipeline.jobs.list.return_value = []

        mock_project = mock.MagicMock()
        mock_project.pipelines.get.return_value = mock_pipeline

        mock_glab = mock.MagicMock()
        mock_glab.projects.get.return_value = mock_project

        with mock.patch('gitlab.Gitlab', return_value=mock_glab):
            with terminal.capture():
                result = gitlab.get_failed_jobs('ci', 100)

        self.assertIsNotNone(result)
        self.assertEqual(len(result), 0)

    @mock.patch.object(gitlab, 'get_remote_url',
                       return_value=TEST_SSH_URL)
    @mock.patch.object(gitlab, 'get_token', return_value='test-token')
    @mock.patch.object(gitlab, 'AVAILABLE', True)
    def test_log_truncation(self, _mock_token, _mock_url):
        """Test that log output is truncated to max_log_lines"""
        # Create a trace with 500 lines
        trace_lines = [f'line {i}' for i in range(500)]
        trace_bytes = '\n'.join(trace_lines).encode()

        mock_job = self._make_mock_job(
            1, 'test:sandbox', 'test', 'https://gitlab.com/job/1',
            trace_bytes)

        mock_full_job = mock.MagicMock()
        mock_full_job.trace.return_value = trace_bytes

        mock_pipeline = mock.MagicMock()
        mock_pipeline.jobs.list.return_value = [mock_job]

        mock_project = mock.MagicMock()
        mock_project.pipelines.get.return_value = mock_pipeline
        mock_project.jobs.get.return_value = mock_full_job

        mock_glab = mock.MagicMock()
        mock_glab.projects.get.return_value = mock_project

        with mock.patch('gitlab.Gitlab', return_value=mock_glab):
            with terminal.capture():
                result = gitlab.get_failed_jobs('ci', 100, max_log_lines=50)

        self.assertEqual(len(result), 1)
        # Should only have last 50 lines
        log_lines = result[0].log_tail.splitlines()
        self.assertEqual(len(log_lines), 50)
        self.assertIn('line 499', result[0].log_tail)


    @mock.patch.object(gitlab, 'get_remote_url',
                       return_value=TEST_SSH_URL)
    @mock.patch.object(gitlab, 'get_token', return_value='test-token')
    @mock.patch.object(gitlab, 'AVAILABLE', True)
    def test_null_bytes_stripped(self, _mock_token, _mock_url):
        """Test that null bytes in job logs are stripped"""
        trace_bytes = b'before\x00after\nline2\x00end\n'

        mock_job = self._make_mock_job(
            1, 'build:sandbox', 'build', 'https://gitlab.com/job/1',
            trace_bytes)

        mock_full_job = mock.MagicMock()
        mock_full_job.trace.return_value = trace_bytes

        mock_pipeline = mock.MagicMock()
        mock_pipeline.jobs.list.return_value = [mock_job]

        mock_project = mock.MagicMock()
        mock_project.pipelines.get.return_value = mock_pipeline
        mock_project.jobs.get.return_value = mock_full_job

        mock_glab = mock.MagicMock()
        mock_glab.projects.get.return_value = mock_project

        with mock.patch('gitlab.Gitlab', return_value=mock_glab):
            with terminal.capture():
                result = gitlab.get_failed_jobs('ci', 100)

        self.assertEqual(len(result), 1)
        self.assertNotIn('\0', result[0].log_tail)
        self.assertIn('beforeafter', result[0].log_tail)
        self.assertIn('line2end', result[0].log_tail)


class TestBuildPipelineFixPrompt(unittest.TestCase):
    """Tests for build_pipeline_fix_prompt function."""

    def setUp(self):
        """Set up temp directory for log files."""
        self.tmp_dir = tempfile.mkdtemp(prefix='pickman-test-')

    def tearDown(self):
        """Remove temp directory."""
        import shutil

        shutil.rmtree(self.tmp_dir, ignore_errors=True)

    def test_single_job(self):
        """Test prompt with a single failed job"""
        failed_jobs = [
            gitlab.FailedJob(
                id=1, name='build:sandbox', stage='build',
                web_url='https://gitlab.com/job/1',
                log_tail='error: undefined reference'),
        ]
        prompt, task_desc = agent.build_pipeline_fix_prompt(
            42, 'cherry-abc123', failed_jobs, 'ci', 'master',
            'Test MR desc', 1, tempdir=self.tmp_dir)

        self.assertIn('!42', prompt)
        self.assertIn('cherry-abc123', prompt)
        self.assertIn('build:sandbox', prompt)
        self.assertIn('attempt 1', prompt)
        self.assertIn('cherry-abc123-fix1', prompt)
        self.assertIn('1 failed', task_desc)

        # Log tail should be in the temp file, not in the prompt
        log_path = os.path.join(self.tmp_dir, 'job-1-build_sandbox.log')
        self.assertTrue(os.path.exists(log_path))
        with open(log_path, encoding='utf-8') as inf:
            self.assertEqual(inf.read(), 'error: undefined reference')
        self.assertIn(log_path, prompt)

    def test_multiple_jobs(self):
        """Test prompt with multiple failed jobs"""
        failed_jobs = [
            gitlab.FailedJob(
                id=1, name='build:sandbox', stage='build',
                web_url='https://gitlab.com/job/1',
                log_tail='build error'),
            gitlab.FailedJob(
                id=2, name='test:dm', stage='test',
                web_url='https://gitlab.com/job/2',
                log_tail='test failure'),
        ]
        prompt, task_desc = agent.build_pipeline_fix_prompt(
            42, 'cherry-abc123', failed_jobs, 'ci', 'master', '', 1,
            tempdir=self.tmp_dir)

        self.assertIn('build:sandbox', prompt)
        self.assertIn('test:dm', prompt)
        self.assertIn('2 failed', task_desc)

        # Both log files should exist
        self.assertTrue(os.path.exists(
            os.path.join(self.tmp_dir, 'job-1-build_sandbox.log')))
        self.assertTrue(os.path.exists(
            os.path.join(self.tmp_dir, 'job-2-test_dm.log')))

    def test_attempt_number(self):
        """Test that attempt number is reflected in prompt"""
        failed_jobs = [
            gitlab.FailedJob(
                id=1, name='build', stage='build',
                web_url='https://gitlab.com/job/1',
                log_tail='error'),
        ]
        prompt, task_desc = agent.build_pipeline_fix_prompt(
            42, 'cherry-abc123', failed_jobs, 'ci', 'master', '', 3,
            tempdir=self.tmp_dir)

        self.assertIn('attempt 3', prompt)
        self.assertIn('cherry-abc123-fix3', prompt)
        self.assertIn('attempt 3', task_desc)

    def test_uses_um_build(self):
        """Test that prompt uses 'um build sandbox' for sandbox"""
        failed_jobs = [
            gitlab.FailedJob(
                id=1, name='build:sandbox', stage='build',
                web_url='https://gitlab.com/job/1',
                log_tail='error'),
        ]
        prompt, _ = agent.build_pipeline_fix_prompt(
            42, 'cherry-abc123', failed_jobs, 'ci', 'master', '', 1,
            tempdir=self.tmp_dir)

        self.assertIn('um build sandbox', prompt)

    def test_extracts_board_names(self):
        """Test that board names are extracted from job names"""
        failed_jobs = [
            gitlab.FailedJob(
                id=1, name='build:imx8mm_venice', stage='build',
                web_url='https://gitlab.com/job/1',
                log_tail='error'),
            gitlab.FailedJob(
                id=2, name='build:rpi_4', stage='build',
                web_url='https://gitlab.com/job/2',
                log_tail='error'),
        ]
        prompt, _ = agent.build_pipeline_fix_prompt(
            42, 'cherry-abc123', failed_jobs, 'ci', 'master', '', 1,
            tempdir=self.tmp_dir)

        # Should include both boards plus sandbox in the buildman command
        self.assertIn('buildman', prompt)
        self.assertIn('imx8mm_venice', prompt)
        self.assertIn('rpi_4', prompt)
        self.assertIn('sandbox', prompt)

    def test_buildman_for_multiple_boards(self):
        """Test that buildman is used for building multiple boards"""
        failed_jobs = [
            gitlab.FailedJob(
                id=1, name='build:coral', stage='build',
                web_url='https://gitlab.com/job/1',
                log_tail='error'),
        ]
        prompt, _ = agent.build_pipeline_fix_prompt(
            42, 'cherry-abc123', failed_jobs, 'ci', 'master', '', 1,
            tempdir=self.tmp_dir)

        self.assertIn('buildman -o /tmp/pickman', prompt)
        self.assertIn('coral', prompt)

    def test_large_logs_stay_under_limit(self):
        """Test that large log tails are written to files, keeping the
        prompt well under the Linux MAX_ARG_STRLEN limit (128 KB)."""
        # Create 5 jobs with 200-line logs (~120 bytes per line)
        big_log = '\n'.join(f'line {i}: ' + 'x' * 100 for i in range(200))
        failed_jobs = [
            gitlab.FailedJob(
                id=i, name=f'build:board{i}', stage='build',
                web_url=f'https://gitlab.com/job/{i}',
                log_tail=big_log)
            for i in range(5)
        ]
        prompt, _ = agent.build_pipeline_fix_prompt(
            42, 'cherry-abc123', failed_jobs, 'ci', 'master',
            'x' * 50000, 1, tempdir=self.tmp_dir)

        # Prompt should be well under 128 KB (the logs are in files)
        self.assertLess(len(prompt), 128 * 1024)

        # All 5 log files plus mr-description should exist
        log_files = [f for f in os.listdir(self.tmp_dir)
                     if f.startswith('job-')]
        self.assertEqual(len(log_files), 5)
        self.assertTrue(os.path.exists(
            os.path.join(self.tmp_dir, 'mr-description.txt')))

    def test_no_tempdir_embeds_inline(self):
        """Test legacy behaviour when tempdir is None"""
        failed_jobs = [
            gitlab.FailedJob(
                id=1, name='build:sandbox', stage='build',
                web_url='https://gitlab.com/job/1',
                log_tail='error: undefined reference'),
        ]
        prompt, _ = agent.build_pipeline_fix_prompt(
            42, 'cherry-abc123', failed_jobs, 'ci', 'master',
            'Test MR desc', 1)

        self.assertIn('error: undefined reference', prompt)
        self.assertIn('Test MR desc', prompt)

    def test_small_mr_desc_stays_inline(self):
        """Test that a small MR description is kept inline"""
        failed_jobs = [
            gitlab.FailedJob(
                id=1, name='build:sandbox', stage='build',
                web_url='https://gitlab.com/job/1',
                log_tail='error'),
        ]
        prompt, _ = agent.build_pipeline_fix_prompt(
            42, 'cherry-abc123', failed_jobs, 'ci', 'master',
            'Short desc', 1, tempdir=self.tmp_dir)

        self.assertIn('Short desc', prompt)
        self.assertFalse(os.path.exists(
            os.path.join(self.tmp_dir, 'mr-description.txt')))


class TestProcessPipelineFailures(unittest.TestCase):
    """Tests for process_pipeline_failures function."""

    def setUp(self):
        """Set up test fixtures."""
        fd, self.db_path = tempfile.mkstemp(suffix='.db')
        os.close(fd)
        os.unlink(self.db_path)

    def tearDown(self):
        """Clean up test fixtures."""
        if os.path.exists(self.db_path):
            os.unlink(self.db_path)
        database.Database.instances.clear()

    def _make_mr(self, iid=1, pipeline_status='failed', pipeline_id=100,
                 needs_rebase=False, has_conflicts=False):
        """Helper to create a PickmanMr with pipeline fields"""
        return gitlab.PickmanMr(
            iid=iid,
            title=f'[pickman] Test MR {iid}',
            web_url=f'https://gitlab.com/mr/{iid}',
            source_branch=f'cherry-test-{iid}',
            description='Test description',
            has_conflicts=has_conflicts,
            needs_rebase=needs_rebase,
            pipeline_status=pipeline_status,
            pipeline_id=pipeline_id,
        )

    def test_skips_running(self):
        """Test that running pipelines are skipped"""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()

            mrs = [self._make_mr(pipeline_status='running')]
            with mock.patch.object(control, 'run_git'):
                result = control.process_pipeline_failures(
                    'ci', mrs, dbs, 'master', 3)

            self.assertEqual(result, 0)
            dbs.close()

    def test_skips_success(self):
        """Test that successful pipelines are skipped"""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()

            mrs = [self._make_mr(pipeline_status='success')]
            with mock.patch.object(control, 'run_git'):
                result = control.process_pipeline_failures(
                    'ci', mrs, dbs, 'master', 3)

            self.assertEqual(result, 0)
            dbs.close()

    def test_skips_already_processed(self):
        """Test that already-processed pipelines are skipped"""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()

            # Pre-record this pipeline
            dbs.pfix_add(1, 100, 1, 'success')
            dbs.commit()

            mrs = [self._make_mr()]
            with mock.patch.object(control, 'run_git'):
                result = control.process_pipeline_failures(
                    'ci', mrs, dbs, 'master', 3)

            self.assertEqual(result, 0)
            dbs.close()

    def test_respects_retry_limit(self):
        """Test that retry limit is respected"""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()

            # Pre-record 3 attempts with different pipeline IDs
            dbs.pfix_add(1, 10, 1, 'failure')
            dbs.pfix_add(1, 20, 2, 'failure')
            dbs.pfix_add(1, 30, 3, 'failure')
            dbs.commit()

            mrs = [self._make_mr(pipeline_id=40)]
            with mock.patch.object(control, 'run_git'):
                with mock.patch.object(gitlab, 'reply_to_mr',
                                       return_value=True):
                    result = control.process_pipeline_failures(
                        'ci', mrs, dbs, 'master', 3)

            # Should have been processed (comment posted) but not fixed
            self.assertEqual(result, 0)
            dbs.close()

    def test_posts_comment_at_limit(self):
        """Test that a comment is posted when retry limit is reached"""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()

            # Pre-record 3 attempts
            dbs.pfix_add(1, 10, 1, 'failure')
            dbs.pfix_add(1, 20, 2, 'failure')
            dbs.pfix_add(1, 30, 3, 'failure')
            dbs.commit()

            mrs = [self._make_mr(pipeline_id=40)]
            with mock.patch.object(control, 'run_git'):
                with mock.patch.object(gitlab, 'reply_to_mr',
                                       return_value=True) as mock_reply:
                    control.process_pipeline_failures(
                        'ci', mrs, dbs, 'master', 3)

            mock_reply.assert_called_once()
            call_args = mock_reply.call_args
            self.assertIn('retry limit', call_args[0][2])
            dbs.close()

    def test_processes_failed(self):
        """Test processing a failed pipeline"""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()

            failed_jobs = [
                gitlab.FailedJob(id=1, name='build', stage='build',
                                 web_url='https://gitlab.com/job/1',
                                 log_tail='error'),
            ]
            mrs = [self._make_mr()]

            with mock.patch.object(control, 'run_git'):
                with mock.patch.object(gitlab, 'get_failed_jobs',
                                       return_value=failed_jobs):
                    with mock.patch.object(agent, 'fix_pipeline',
                                           return_value=(True, 'Fixed it')):
                        with mock.patch.object(
                                gitlab, 'push_branch',
                                return_value=True) as mock_push:
                            with mock.patch.object(gitlab, 'update_mr_desc',
                                                   return_value=True):
                                with mock.patch.object(
                                        gitlab, 'reply_to_mr',
                                        return_value=True) as mock_reply:
                                    with mock.patch.object(
                                            control,
                                            'update_history_pipeline_fix'):
                                        result = \
                                            control.process_pipeline_failures(
                                                'ci', mrs, dbs, 'master', 3)

            self.assertEqual(result, 1)
            # Should be recorded in database
            self.assertTrue(dbs.pfix_has(1, 100))
            # Should push the branch
            mock_push.assert_called_once_with(
                'ci', 'cherry-test-1', force=True, skip_ci=False)
            # Should post a comment on the MR
            mock_reply.assert_called_once()
            reply_msg = mock_reply.call_args[0][2]
            self.assertIn('Fixed it', reply_msg)
            self.assertIn('build', reply_msg)
            dbs.close()

    def test_skips_skipped_mr(self):
        """Test that MRs without pipeline_id are skipped"""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()

            mrs = [self._make_mr(pipeline_id=None)]
            with mock.patch.object(control, 'run_git'):
                result = control.process_pipeline_failures(
                    'ci', mrs, dbs, 'master', 3)

            self.assertEqual(result, 0)
            dbs.close()

    def test_rebases_before_fix(self):
        """Test that a branch needing rebase is rebased instead of fixed"""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()

            mrs = [self._make_mr(needs_rebase=True)]
            with mock.patch.object(control, 'run_git'):
                with mock.patch.object(
                        gitlab, 'push_branch',
                        return_value=True) as mock_push:
                    with mock.patch.object(agent, 'fix_pipeline') as mock_fix:
                        result = control.process_pipeline_failures(
                            'ci', mrs, dbs, 'master', 3)

            self.assertEqual(result, 1)
            # Should push the rebased branch, not call fix_pipeline
            mock_push.assert_called_once_with(
                'ci', 'cherry-test-1', force=True, skip_ci=False)
            mock_fix.assert_not_called()
            # Should be recorded as 'rebased' in database
            self.assertTrue(dbs.pfix_has(1, 100))
            dbs.close()

    def test_rebase_with_conflicts_skips(self):
        """Test that a failed rebase skips the pipeline fix"""
        with terminal.capture():
            dbs = database.Database(self.db_path)
            dbs.start()

            mrs = [self._make_mr(has_conflicts=True)]

            def mock_run_git_fn(args):
                if args[0] == 'rebase':
                    raise command.CommandExc('conflict', None)
                return ''

            with mock.patch.object(control, 'run_git',
                                   side_effect=mock_run_git_fn):
                with mock.patch.object(agent, 'fix_pipeline') as mock_fix:
                    result = control.process_pipeline_failures(
                        'ci', mrs, dbs, 'master', 3)

            self.assertEqual(result, 0)
            mock_fix.assert_not_called()
            dbs.close()

    def test_disabled_with_zero(self):
        """Test that fix_retries=0 is handled in do_step (not called)"""
        mock_mr = gitlab.PickmanMr(
            iid=123,
            title='[pickman] Test MR',
            web_url='https://gitlab.com/mr/123',
            source_branch='cherry-test',
            description='Test',
            pipeline_status='failed',
            pipeline_id=100,
        )
        mock_info = control.NextCommitsInfo(
            commits=['fake'], merge_found=True, advance_to='abc123')
        with mock.patch.object(control, 'run_git'):
            with mock.patch.object(gitlab, 'get_merged_pickman_mrs',
                                   return_value=[]):
                with mock.patch.object(gitlab, 'get_open_pickman_mrs',
                                       return_value=[mock_mr]):
                    with mock.patch.object(
                            control, '_prepare_get_commits',
                            return_value=(mock_info, None)):
                        with mock.patch.object(
                                control,
                                'process_pipeline_failures') as mock_ppf:
                            args = argparse.Namespace(
                                cmd='step', source='us/next',
                                remote='ci', target='master',
                                max_mrs=1, fix_retries=0)
                            with terminal.capture():
                                control.do_step(args, None)

        mock_ppf.assert_not_called()


class TestStepFixRetries(unittest.TestCase):
    """Tests for --fix-retries argument parsing."""

    def test_default(self):
        """Test default fix-retries value for step"""
        args = pickman.parse_args(['step', 'us/next'])
        self.assertEqual(args.fix_retries, 3)

    def test_custom(self):
        """Test custom fix-retries value for step"""
        args = pickman.parse_args(['step', 'us/next', '--fix-retries', '5'])
        self.assertEqual(args.fix_retries, 5)

    def test_zero_disables(self):
        """Test that fix-retries=0 is accepted"""
        args = pickman.parse_args(['step', 'us/next', '--fix-retries', '0'])
        self.assertEqual(args.fix_retries, 0)

    def test_poll_default(self):
        """Test default fix-retries value for poll"""
        args = pickman.parse_args(['poll', 'us/next'])
        self.assertEqual(args.fix_retries, 3)

    def test_poll_custom(self):
        """Test custom fix-retries value for poll"""
        args = pickman.parse_args(['poll', 'us/next', '--fix-retries', '1'])
        self.assertEqual(args.fix_retries, 1)


class TestIsMergeInProgress(unittest.TestCase):
    """Tests for _is_merge_in_progress helper."""

    def test_merge_in_progress(self):
        """Test returns True when MERGE_HEAD exists."""
        with mock.patch.object(control, 'run_git', return_value='abc123'):
            self.assertTrue(control._is_merge_in_progress())

    def test_no_merge_in_progress(self):
        """Test returns False when MERGE_HEAD does not exist."""
        with mock.patch.object(control, 'run_git',
                               side_effect=Exception('not found')):
            self.assertFalse(control._is_merge_in_progress())


class TestSubtreeRunUpdateReturnValues(unittest.TestCase):
    """Tests for _subtree_run_update return values."""

    def test_returns_ok_on_success(self):
        """Test returns SUBTREE_OK on successful update."""
        mock_result = command.CommandResult('done', '', '', 0)
        with terminal.capture():
            with mock.patch.object(control.command, 'run_one',
                                   return_value=mock_result):
                ret = control._subtree_run_update('dts', 'v6.15-dts')
        self.assertEqual(ret, control.SUBTREE_OK)

    def test_returns_conflict_when_merge_in_progress(self):
        """Test returns SUBTREE_CONFLICT when merge state exists."""
        mock_result = command.CommandResult(
            '', 'CONFLICT', '', 1)
        with terminal.capture():
            with mock.patch.object(control.command, 'run_one',
                                   return_value=mock_result):
                with mock.patch.object(control, '_is_merge_in_progress',
                                       return_value=True):
                    ret = control._subtree_run_update('dts', 'v6.15-dts')
        self.assertEqual(ret, control.SUBTREE_CONFLICT)

    def test_returns_fail_when_no_merge(self):
        """Test returns SUBTREE_FAIL when script fails without merge."""
        mock_result = command.CommandResult(
            '', 'error', '', 1)
        with terminal.capture():
            with mock.patch.object(control.command, 'run_one',
                                   return_value=mock_result):
                with mock.patch.object(control, '_is_merge_in_progress',
                                       return_value=False):
                    with mock.patch.object(control, 'run_git'):
                        ret = control._subtree_run_update(
                            'dts', 'v6.15-dts')
        self.assertEqual(ret, control.SUBTREE_FAIL)

    def test_returns_fail_on_exception(self):
        """Test returns SUBTREE_FAIL when script raises exception."""
        with terminal.capture():
            with mock.patch.object(control.command, 'run_one',
                                   side_effect=Exception('boom')):
                ret = control._subtree_run_update('dts', 'v6.15-dts')
        self.assertEqual(ret, control.SUBTREE_FAIL)


class TestSubtreeConflictPrompt(unittest.TestCase):
    """Tests for build_subtree_conflict_prompt."""

    def test_dts_prompt_content(self):
        """Test prompt contains correct details for dts subtree."""
        prompt = agent.build_subtree_conflict_prompt(
            'dts', 'v6.15-dts', 'dts/upstream')
        self.assertIn('dts/upstream', prompt)
        self.assertIn('v6.15-dts', prompt)
        self.assertIn('MERGE_HEAD', prompt)
        self.assertIn('git commit --no-edit', prompt)
        self.assertIn('git merge --abort', prompt)

    def test_mbedtls_prompt_content(self):
        """Test prompt contains correct details for mbedtls subtree."""
        prompt = agent.build_subtree_conflict_prompt(
            'mbedtls', 'v3.6.0', 'lib/mbedtls/external/mbedtls')
        self.assertIn('lib/mbedtls/external/mbedtls', prompt)
        self.assertIn('v3.6.0', prompt)
        self.assertIn("'mbedtls'", prompt)


class TestResolveSubtreeConflicts(unittest.TestCase):
    """Tests for resolve_subtree_conflicts."""

    def test_success(self):
        """Test successful conflict resolution."""
        mock_collect = mock.AsyncMock(return_value=(True, 'resolved'))
        with terminal.capture():
            with mock.patch.object(agent, 'AGENT_AVAILABLE', True):
                with mock.patch.object(agent, 'run_agent_collect',
                                       mock_collect):
                    with mock.patch.object(agent, 'ClaudeAgentOptions',
                                           create=True):
                        success, log = agent.resolve_subtree_conflicts(
                            'dts', 'v6.15-dts', 'dts/upstream',
                            '/tmp/test')
        self.assertTrue(success)
        self.assertEqual(log, 'resolved')

    def test_failure(self):
        """Test failed conflict resolution."""
        mock_collect = mock.AsyncMock(return_value=(False, 'failed'))
        with terminal.capture():
            with mock.patch.object(agent, 'AGENT_AVAILABLE', True):
                with mock.patch.object(agent, 'run_agent_collect',
                                       mock_collect):
                    with mock.patch.object(agent, 'ClaudeAgentOptions',
                                           create=True):
                        success, log = agent.resolve_subtree_conflicts(
                            'dts', 'v6.15-dts', 'dts/upstream',
                            '/tmp/test')
        self.assertFalse(success)

    def test_sdk_unavailable(self):
        """Test returns failure when SDK is not available."""
        with terminal.capture():
            with mock.patch.object(agent, 'AGENT_AVAILABLE', False):
                success, log = agent.resolve_subtree_conflicts(
                    'dts', 'v6.15-dts', 'dts/upstream', '/tmp/test')
        self.assertFalse(success)
        self.assertEqual(log, '')


if __name__ == '__main__':
    unittest.main()