edgefirst-cli 2.9.0

EdgeFirst Client Library and CLI
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
// SPDX-License-Identifier: Apache-2.0
// Copyright © 2025 Au-Zone Technologies. All Rights Reserved.

// SPDX-License-Identifier: Apache-2.0
// Copyright © 2025 Au-Zone Technologies. All Rights Reserved.

use assert_cmd::Command;
use base64::Engine as _;
use chrono::Utc;
use directories::ProjectDirs;
use serial_test::file_serial;
use std::{
    collections::{BTreeSet, HashMap},
    env, fs,
    path::{Path, PathBuf},
    time::{SystemTime, UNIX_EPOCH},
};

/// Helper to create a Command for the edgefirst-client binary
fn edgefirst_cmd() -> Command {
    Command::new(assert_cmd::cargo::cargo_bin!("edgefirst-client"))
}

/// Get the test data directory (target/testdata)
/// Creates it if it doesn't exist
fn get_test_data_dir() -> PathBuf {
    let test_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .unwrap()
        .parent()
        .unwrap()
        .join("target")
        .join("testdata");

    fs::create_dir_all(&test_dir).expect("Failed to create test data directory");
    test_dir
}

/// Get the test dataset identifier from environment or default to "Deer"
/// Can be a dataset name (exact match) or dataset ID (ds-xxx format)
fn get_test_dataset() -> String {
    env::var("TEST_DATASET").unwrap_or_else(|_| "Deer".to_string())
}

/// Get the annotation types to test from environment or default to
/// "box2d,box3d,mask" Returns a vector of annotation type strings
fn get_test_dataset_types() -> Vec<String> {
    env::var("TEST_DATASET_TYPES")
        .unwrap_or_else(|_| "box2d,box3d,mask".to_string())
        .split(',')
        .map(|s| s.trim().to_string())
        .collect()
}

/// Get the test data directory for the configured test dataset
/// (e.g., target/testdata/deer-test or target/testdata/multisensor-test)
fn get_test_dataset_path() -> PathBuf {
    let dataset = get_test_dataset();
    // If it's a dataset ID (ds-xxx), extract a friendly name for the path
    let normalized_name = if let Some(stripped) = dataset.strip_prefix("ds-") {
        format!("dataset-{}", stripped)
    } else {
        dataset.to_lowercase().replace(' ', "-")
    };
    get_test_data_dir().join(format!("{}-test", normalized_name))
}

fn get_project_id_by_name(name: &str) -> Result<Option<String>, Box<dyn std::error::Error>> {
    let mut cmd = edgefirst_cmd();
    cmd.arg("projects").arg("--name").arg(name);

    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    Ok(output_str
        .lines()
        .filter_map(|line| {
            line.split(']')
                .next()
                .and_then(|s| s.strip_prefix('['))
                .map(|s| s.trim().to_string())
        })
        .next())
}

/// Get dataset and its first annotation set by dataset identifier
///
/// The dataset parameter can be:
/// - A dataset ID (ds-xxx format): Used directly
/// - A dataset name: Searches all projects for EXACT name match
///
/// # Important
///
/// This function performs an EXACT name match when searching by name.
/// The returned dataset name is verified to match exactly to prevent
/// accidentally finding a similarly-named dataset (e.g., "Deer Roundtrip"
/// instead of "Deer").
fn get_dataset_and_first_annotation_set(
    dataset: &str,
) -> Result<(String, String), Box<dyn std::error::Error>> {
    let (dataset_id, found_name) = if dataset.starts_with("ds-") {
        // It's a dataset ID - verify it exists and get its name
        let mut cmd = edgefirst_cmd();
        cmd.arg("dataset").arg(dataset);

        let output = cmd.ok()?.stdout;
        let output_str = String::from_utf8(output)?;

        // Extract dataset name from output (first line: [ds-xxx] Dataset Name)
        let name = output_str
            .lines()
            .next()
            .and_then(|line| {
                line.split(']')
                    .nth(1)
                    .map(|s| s.split(':').next().unwrap_or(s).trim().to_string())
            })
            .unwrap_or_else(|| "unknown".to_string());

        (dataset.to_string(), name)
    } else {
        // It's a dataset name - search all projects for EXACT match
        let mut cmd = edgefirst_cmd();
        cmd.arg("datasets").arg("--name").arg(dataset);

        let output = cmd.ok()?.stdout;
        let output_str = String::from_utf8(output)?;

        // Parse output and find EXACT name match (case-sensitive)
        // Output format: [ds-xxx] Dataset Name: project_name
        //
        // Note: The API returns results sorted by match quality (exact first),
        // but we still explicitly verify the exact match to be safe.
        let all_matches: Vec<_> = output_str
            .lines()
            .filter_map(|line| {
                let (id_part, rest) = line.split_once(']')?;
                let id = id_part.strip_prefix('[')?.trim();
                let name_and_project = rest.trim();
                let name = name_and_project.split(':').next()?.trim();
                Some((id.to_string(), name.to_string()))
            })
            .collect();

        // Find exact match first (case-sensitive)
        let exact_match = all_matches.iter().find(|(_, name)| name == dataset);

        match exact_match {
            Some((id, name)) => (id.clone(), name.clone()),
            None => {
                // No exact match found - provide helpful error
                if all_matches.is_empty() {
                    return Err(format!("Dataset '{}' not found in any project", dataset).into());
                } else {
                    return Err(format!(
                        "Dataset '{}' not found. Similar datasets found: {:?}",
                        dataset,
                        all_matches.iter().map(|(_, n)| n).collect::<Vec<_>>()
                    )
                    .into());
                }
            }
        }
    };

    // CRITICAL: Verify the found dataset name matches EXACTLY what was requested
    // This prevents accidentally testing with a similarly-named dataset
    if !dataset.starts_with("ds-") {
        assert_eq!(
            found_name, dataset,
            "Dataset name mismatch: requested '{}' but found '{}'. \
             The API may have returned a near-match instead of exact match.",
            dataset, found_name
        );
    }

    let mut cmd = edgefirst_cmd();
    cmd.arg("dataset").arg(&dataset_id).arg("--annotation-sets");

    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    let annotation_set_id = output_str
        .lines()
        .skip_while(|line| !line.contains("Annotation Sets:"))
        .skip(1)
        .find_map(|line| {
            line.split(']')
                .next()
                .and_then(|s| s.strip_prefix('['))
                .map(|s| s.trim().to_string())
                .filter(|id| id.starts_with("as-"))
        })
        .ok_or_else(|| format!("No annotation set found for dataset '{}'", dataset))?;

    Ok((dataset_id, annotation_set_id))
}

fn collect_relative_file_paths(dir: &Path) -> Result<Vec<String>, std::io::Error> {
    fn visit(current: &Path, base: &Path, files: &mut Vec<String>) -> Result<(), std::io::Error> {
        for entry in fs::read_dir(current)? {
            let entry = entry?;
            let path = entry.path();
            if path.is_dir() {
                visit(&path, base, files)?;
            } else if path.is_file() {
                if entry.file_name() == ".DS_Store" {
                    continue;
                }
                let rel = path.strip_prefix(base).unwrap();
                files.push(rel.to_string_lossy().replace('\\', "/"));
            }
        }
        Ok(())
    }

    let mut files = Vec::new();
    visit(dir, dir, &mut files)?;
    files.sort();
    Ok(files)
}

fn validate_dataset_structure(dir: &Path) -> Result<(), Box<dyn std::error::Error>> {
    let files = collect_relative_file_paths(dir)?;

    if files.is_empty() {
        return Err("Downloaded dataset is empty".into());
    }

    // Verify all files are image files with valid extensions
    let valid_extensions = ["jpg", "jpeg", "png", "bmp", "tiff", "tif", "pcd"];
    for file in &files {
        let path = Path::new(file);
        let extension = path
            .extension()
            .and_then(|ext| ext.to_str())
            .map(|ext| ext.to_lowercase());

        if let Some(ext) = extension {
            if !valid_extensions.contains(&ext.as_str()) {
                return Err(format!("Invalid file extension in dataset: {}", file).into());
            }
        } else {
            return Err(format!("File without extension in dataset: {}", file).into());
        }
    }

    Ok(())
}

fn download_dataset_from_server(dataset_id: &str) -> Result<PathBuf, Box<dyn std::error::Error>> {
    download_dataset_from_server_with_retries(dataset_id, 1) // default: 1 attempt
}

fn download_dataset_from_server_with_retries(
    dataset_id: &str,
    max_attempts: u32,
) -> Result<PathBuf, Box<dyn std::error::Error>> {
    let downloads_root = get_test_data_dir().join("downloads");
    fs::create_dir_all(&downloads_root)?;

    let timestamp = SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis();
    let safe_dataset_id = dataset_id.replace('/', "_");
    let download_dir = downloads_root.join(format!(
        "{}_{}_{}",
        safe_dataset_id,
        std::process::id(),
        timestamp
    ));
    fs::create_dir_all(&download_dir)?;

    for attempt in 1..=max_attempts {
        let mut cmd = edgefirst_cmd();
        cmd.arg("download-dataset")
            .arg(dataset_id)
            .arg("--output")
            .arg(&download_dir);
        let result = cmd.ok();
        if result.is_ok() {
            return Ok(download_dir);
        }
        if attempt < max_attempts {
            println!(
                "Download attempt {} failed, retrying in 5 seconds...",
                attempt
            );
            std::thread::sleep(std::time::Duration::from_secs(5));
            // Clear directory for retry
            if download_dir.exists() {
                let _ = fs::remove_dir_all(&download_dir);
                fs::create_dir_all(&download_dir)?;
            }
        } else {
            // On last attempt, propagate the error
            cmd = edgefirst_cmd();
            cmd.arg("download-dataset")
                .arg(dataset_id)
                .arg("--output")
                .arg(&download_dir);
            cmd.assert().success();
        }
    }

    Ok(download_dir)
}

fn download_annotations_from_server(
    annotation_set_id: &str,
) -> Result<PathBuf, Box<dyn std::error::Error>> {
    download_annotations_from_server_with_types(annotation_set_id, &["box2d"])
}

fn download_annotations_from_server_with_types(
    annotation_set_id: &str,
    types: &[&str],
) -> Result<PathBuf, Box<dyn std::error::Error>> {
    let downloads_root = get_test_data_dir().join("downloads");
    fs::create_dir_all(&downloads_root)?;

    let timestamp = SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis();
    let safe_annotation_set_id = annotation_set_id.replace('/', "_");
    let arrow_path = downloads_root.join(format!(
        "{}_{}_{}.arrow",
        safe_annotation_set_id,
        std::process::id(),
        timestamp
    ));

    let mut cmd = edgefirst_cmd();
    cmd.arg("download-annotations")
        .arg(annotation_set_id)
        .arg("--types")
        .arg(types.join(","))
        .arg(&arrow_path);
    cmd.assert().success();

    Ok(arrow_path)
}

/// Compare two Arrow files to verify groups and annotations are preserved
/// Returns an error if there are mismatches
#[cfg(feature = "polars")]
fn compare_arrow_files(
    original_path: &Path,
    redownloaded_path: &Path,
) -> Result<(), Box<dyn std::error::Error>> {
    use polars::prelude::*;
    use std::fs::File;

    println!("\n=== Arrow File Comparison ===");

    // Read both Arrow files
    let mut original_file = File::open(original_path)?;
    let original_df = IpcReader::new(&mut original_file).finish()?;

    let mut redownloaded_file = File::open(redownloaded_path)?;
    let redownloaded_df = IpcReader::new(&mut redownloaded_file).finish()?;

    println!("Original rows: {}", original_df.height());
    println!("Redownloaded rows: {}", redownloaded_df.height());

    // Debug: Find missing rows if counts don't match
    if original_df.height() != redownloaded_df.height() {
        println!("\n=== DEBUGGING ROW COUNT MISMATCH ===");

        // Build sets of (name, frame) tuples for both datasets
        let original_samples = if let Ok(names_col) = original_df.column("name")
            && let Ok(frames_col) = original_df.column("frame")
        {
            let names_cast = names_col.cast(&DataType::String)?;
            let frames_cast = frames_col.cast(&DataType::Int32)?;
            let names = names_cast.str()?;
            let frames = frames_cast.i32()?;

            let mut samples = std::collections::HashSet::new();
            for idx in 0..original_df.height() {
                if let Some(name) = names.get(idx) {
                    let frame = frames.get(idx);
                    samples.insert((name.to_string(), frame));
                }
            }
            Some(samples)
        } else {
            None
        };

        let redownloaded_samples = if let Ok(names_col) = redownloaded_df.column("name")
            && let Ok(frames_col) = redownloaded_df.column("frame")
        {
            let names_cast = names_col.cast(&DataType::String)?;
            let frames_cast = frames_col.cast(&DataType::Int32)?;
            let names = names_cast.str()?;
            let frames = frames_cast.i32()?;

            let mut samples = std::collections::HashSet::new();
            for idx in 0..redownloaded_df.height() {
                if let Some(name) = names.get(idx) {
                    let frame = frames.get(idx);
                    samples.insert((name.to_string(), frame));
                }
            }
            Some(samples)
        } else {
            None
        };

        if let (Some(orig), Some(redown)) = (&original_samples, &redownloaded_samples) {
            let missing_in_redownloaded: Vec<_> = orig.difference(redown).collect();
            let extra_in_redownloaded: Vec<_> = redown.difference(orig).collect();

            if !missing_in_redownloaded.is_empty() {
                println!(
                    "\nMissing in redownloaded ({} rows):",
                    missing_in_redownloaded.len()
                );
                for (name, frame) in missing_in_redownloaded.iter().take(20) {
                    println!("  - {} (frame: {:?})", name, frame);
                }
            }

            if !extra_in_redownloaded.is_empty() {
                println!(
                    "\nExtra in redownloaded ({} rows):",
                    extra_in_redownloaded.len()
                );
                for (name, frame) in extra_in_redownloaded.iter().take(20) {
                    println!("  - {} (frame: {:?})", name, frame);
                }
            }
        }

        return Err(format!(
            "Row count mismatch: {} vs {}",
            original_df.height(),
            redownloaded_df.height()
        )
        .into());
    }

    // Check that group column exists in both
    let original_has_group = original_df.column("group").is_ok();
    let redownloaded_has_group = redownloaded_df.column("group").is_ok();

    println!("Original has group column: {}", original_has_group);
    println!("Redownloaded has group column: {}", redownloaded_has_group);

    // Build sample -> group mapping for both datasets
    // Key is (name_base, frame) since a sample is uniquely identified by name+frame
    let original_groups = if let Ok(names_col) = original_df.column("name")
        && let Ok(groups_col) = original_df.column("group")
        && let Ok(frames_col) = original_df.column("frame")
    {
        // Cast to String to handle Categorical types
        let names_cast = names_col.cast(&DataType::String)?;
        let groups_cast = groups_col.cast(&DataType::String)?;
        let frames_cast = frames_col.cast(&DataType::Int32)?;
        let names = names_cast.str()?;
        let groups = groups_cast.str()?;
        let frames = frames_cast.i32()?;

        let mut map = HashMap::new();
        for idx in 0..original_df.height() {
            if let (Some(name), group_opt, frame_opt) =
                (names.get(idx), groups.get(idx), frames.get(idx))
            {
                let name_base = name.rsplit_once('.').map(|(base, _)| base).unwrap_or(name);
                let key = (name_base.to_string(), frame_opt);
                map.insert(key, group_opt.map(|g| g.to_string()));
            }
        }
        Some(map)
    } else {
        None
    };

    let redownloaded_groups = if let Ok(names_col) = redownloaded_df.column("name")
        && let Ok(groups_col) = redownloaded_df.column("group")
        && let Ok(frames_col) = redownloaded_df.column("frame")
    {
        let names_cast = names_col.cast(&DataType::String)?;
        let groups_cast = groups_col.cast(&DataType::String)?;
        let frames_cast = frames_col.cast(&DataType::Int32)?;
        let names = names_cast.str()?;
        let groups = groups_cast.str()?;
        let frames = frames_cast.i32()?;

        let mut map = HashMap::new();
        for idx in 0..redownloaded_df.height() {
            if let (Some(name), group_opt, frame_opt) =
                (names.get(idx), groups.get(idx), frames.get(idx))
            {
                let name_base = name.rsplit_once('.').map(|(base, _)| base).unwrap_or(name);
                let key = (name_base.to_string(), frame_opt);
                map.insert(key, group_opt.map(|g| g.to_string()));
            }
        }
        Some(map)
    } else {
        None
    };

    // Verify groups match if both exist
    // Key is (name_base, frame) tuple since samples are uniquely identified by
    // name+frame
    if let (Some(orig_groups), Some(redown_groups)) = (&original_groups, &redownloaded_groups) {
        let mut mismatches = Vec::new();

        for (key, orig_group) in orig_groups {
            if let Some(redown_group) = redown_groups.get(key)
                && orig_group != redown_group
            {
                let (name, frame) = key;
                let frame_str = frame.map(|f| format!("_frame_{}", f)).unwrap_or_default();
                mismatches.push(format!(
                    "  Sample '{}{}': group '{}' != '{}'",
                    name,
                    frame_str,
                    orig_group.as_deref().unwrap_or("None"),
                    redown_group.as_deref().unwrap_or("None")
                ));
            }
        }

        if !mismatches.is_empty() {
            println!("⚠️  GROUP MISMATCHES DETECTED:");
            for (i, mismatch) in mismatches.iter().take(10).enumerate() {
                println!("  {}: {}", i + 1, mismatch);
            }
            return Err(format!("Found {} group mismatches", mismatches.len()).into());
        }

        println!("✓ Groups verified: all samples have matching groups");
    } else if original_has_group && !redownloaded_has_group {
        return Err("Original file has groups but redownloaded file does not".into());
    } else if !original_has_group && redownloaded_has_group {
        return Err("Redownloaded file has groups but original file does not".into());
    }

    // CRITICAL DEBUG: Check samples with NO annotations
    // These are the most likely to lose group information
    println!("\n=== DEBUG: Samples with No Annotations ===");

    // Check original for samples with null labels (no annotations)
    if let Ok(labels_col) = original_df.column("label")
        && let Ok(groups_col) = original_df.column("group")
        && let Ok(names_col) = original_df.column("name")
    {
        let names_cast = names_col.cast(&DataType::String)?;
        let names = names_cast.str()?;
        let groups_cast = groups_col.cast(&DataType::String)?;
        let _groups = groups_cast.str()?;

        let label_is_null = labels_col.is_null();
        let group_is_null = groups_col.is_null();

        let mut no_annotation_count = 0;
        let mut no_annotation_with_group = 0;
        let mut no_annotation_without_group = Vec::new();

        for idx in 0..original_df.height() {
            if label_is_null.get(idx).unwrap_or(false) {
                no_annotation_count += 1;
                let has_group = !group_is_null.get(idx).unwrap_or(true);
                if has_group {
                    no_annotation_with_group += 1;
                } else if let Some(name) = names.get(idx) {
                    no_annotation_without_group.push(name.to_string());
                }
            }
        }

        println!(
            "Original - Samples with no annotations: {}",
            no_annotation_count
        );
        println!(
            "Original - Samples with no annotations BUT WITH group: {}",
            no_annotation_with_group
        );
        if !no_annotation_without_group.is_empty() {
            println!(
                "⚠️  Original - {} samples with no annotations AND no group:",
                no_annotation_without_group.len()
            );
            for (i, name) in no_annotation_without_group.iter().take(10).enumerate() {
                println!("    {}: {}", i + 1, name);
            }
        }
    }

    // Check redownloaded for the same
    if let Ok(labels_col) = redownloaded_df.column("label")
        && let Ok(groups_col) = redownloaded_df.column("group")
        && let Ok(names_col) = redownloaded_df.column("name")
    {
        let names_cast = names_col.cast(&DataType::String)?;
        let names = names_cast.str()?;
        let groups_cast = groups_col.cast(&DataType::String)?;
        let _groups = groups_cast.str()?;

        let label_is_null = labels_col.is_null();
        let group_is_null = groups_col.is_null();

        let mut no_annotation_count = 0;
        let mut no_annotation_with_group = 0;
        let mut no_annotation_without_group = Vec::new();

        for idx in 0..redownloaded_df.height() {
            if label_is_null.get(idx).unwrap_or(false) {
                no_annotation_count += 1;
                let has_group = !group_is_null.get(idx).unwrap_or(true);
                if has_group {
                    no_annotation_with_group += 1;
                } else if let Some(name) = names.get(idx) {
                    no_annotation_without_group.push(name.to_string());
                }
            }
        }

        println!(
            "Redownloaded - Samples with no annotations: {}",
            no_annotation_count
        );
        println!(
            "Redownloaded - Samples with no annotations BUT WITH group: {}",
            no_annotation_with_group
        );
        if !no_annotation_without_group.is_empty() {
            println!(
                "⚠️  Redownloaded - {} samples with no annotations AND no group:",
                no_annotation_without_group.len()
            );
            for (i, name) in no_annotation_without_group.iter().take(10).enumerate() {
                println!("    {}: {}", i + 1, name);
            }
        }
    }

    // Verify masks if present
    let original_has_mask = original_df.column("mask").is_ok();
    let redownloaded_has_mask = redownloaded_df.column("mask").is_ok();

    println!("Original has mask column: {}", original_has_mask);
    println!("Redownloaded has mask column: {}", redownloaded_has_mask);

    if original_has_mask && redownloaded_has_mask {
        // Count non-null masks
        let orig_mask_col = original_df.column("mask")?;
        let redown_mask_col = redownloaded_df.column("mask")?;

        let orig_mask_count = orig_mask_col.len() - orig_mask_col.null_count();
        let redown_mask_count = redown_mask_col.len() - redown_mask_col.null_count();

        println!("Original mask annotations: {}", orig_mask_count);
        println!("Redownloaded mask annotations: {}", redown_mask_count);

        if orig_mask_count != redown_mask_count {
            return Err(format!(
                "Mask count mismatch: {} vs {}",
                orig_mask_count, redown_mask_count
            )
            .into());
        }

        if orig_mask_count > 0 {
            println!(
                "✓ Mask annotations verified: {} masks preserved",
                orig_mask_count
            );
        }
    }

    // Verify box2d if present
    let original_has_box2d = original_df.column("box2d").is_ok();
    let redownloaded_has_box2d = redownloaded_df.column("box2d").is_ok();

    if original_has_box2d && redownloaded_has_box2d {
        let orig_box2d_col = original_df.column("box2d")?;
        let redown_box2d_col = redownloaded_df.column("box2d")?;

        let orig_box2d_count = orig_box2d_col.len() - orig_box2d_col.null_count();
        let redown_box2d_count = redown_box2d_col.len() - redown_box2d_col.null_count();

        println!("Original box2d annotations: {}", orig_box2d_count);
        println!("Redownloaded box2d annotations: {}", redown_box2d_count);

        if orig_box2d_count != redown_box2d_count {
            return Err(format!(
                "Box2d count mismatch: {} vs {}",
                orig_box2d_count, redown_box2d_count
            )
            .into());
        }

        if orig_box2d_count > 0 {
            println!(
                "✓ Box2d annotations verified: {} boxes preserved",
                orig_box2d_count
            );
        }
    }

    // Verify object_id references when both box2d and mask are present
    if original_has_box2d && original_has_mask && redownloaded_has_box2d && redownloaded_has_mask {
        let orig_box2d_col = original_df.column("box2d")?;
        let orig_mask_col = original_df.column("mask")?;
        let orig_object_id_col = original_df.column("object_id")?;

        // Cast object_id to String for easier comparison
        let orig_object_id_cast = orig_object_id_col.cast(&DataType::String)?;
        let orig_object_ids = orig_object_id_cast.str()?;

        // Get box2d and mask null counts to calculate non-null rows
        let _orig_box2d_null_count = orig_box2d_col.null_count();
        let _orig_mask_null_count = orig_mask_col.null_count();

        // Count rows where both box2d and mask are non-null by iterating
        let mut orig_dual_annotation_count = 0;
        let mut orig_dual_with_object_id = 0;

        // Create boolean masks for non-null values
        let orig_box2d_not_null = orig_box2d_col.is_not_null();
        let orig_mask_not_null = orig_mask_col.is_not_null();

        for idx in 0..original_df.height() {
            let has_box2d = orig_box2d_not_null.get(idx).unwrap_or(false);
            let has_mask = orig_mask_not_null.get(idx).unwrap_or(false);

            if has_box2d && has_mask {
                orig_dual_annotation_count += 1;
                if let Some(object_id) = orig_object_ids.get(idx)
                    && !object_id.is_empty()
                {
                    orig_dual_with_object_id += 1;
                }
            }
        }

        // Do the same for redownloaded
        let redown_box2d_col = redownloaded_df.column("box2d")?;
        let redown_mask_col = redownloaded_df.column("mask")?;
        let redown_object_id_col = redownloaded_df.column("object_id")?;

        let redown_object_id_cast = redown_object_id_col.cast(&DataType::String)?;
        let redown_object_ids = redown_object_id_cast.str()?;

        let mut redown_dual_annotation_count = 0;
        let mut redown_dual_with_object_id = 0;

        let redown_box2d_not_null = redown_box2d_col.is_not_null();
        let redown_mask_not_null = redown_mask_col.is_not_null();

        for idx in 0..redownloaded_df.height() {
            let has_box2d = redown_box2d_not_null.get(idx).unwrap_or(false);
            let has_mask = redown_mask_not_null.get(idx).unwrap_or(false);

            if has_box2d && has_mask {
                redown_dual_annotation_count += 1;
                if let Some(object_id) = redown_object_ids.get(idx)
                    && !object_id.is_empty()
                {
                    redown_dual_with_object_id += 1;
                }
            }
        }

        println!(
            "Original annotations with both box2d and mask: {}",
            orig_dual_annotation_count
        );
        println!(
            "Original dual annotations with object_id: {}",
            orig_dual_with_object_id
        );
        println!(
            "Redownloaded annotations with both box2d and mask: {}",
            redown_dual_annotation_count
        );
        println!(
            "Redownloaded dual annotations with object_id: {}",
            redown_dual_with_object_id
        );

        if orig_dual_annotation_count != redown_dual_annotation_count {
            return Err(format!(
                "Dual annotation count mismatch: {} vs {}",
                orig_dual_annotation_count, redown_dual_annotation_count
            )
            .into());
        }

        if orig_dual_with_object_id != redown_dual_with_object_id {
            return Err(format!(
                "Dual annotation object_id count mismatch: {} vs {}",
                orig_dual_with_object_id, redown_dual_with_object_id
            )
            .into());
        }

        if orig_dual_annotation_count > 0 {
            if orig_dual_with_object_id == 0 {
                return Err(
                    "Expected object_id references for annotations with both box2d and mask"
                        .to_string()
                        .into(),
                );
            }

            println!(
                "✓ Object_id references verified: {}/{} dual annotations have object_ids",
                orig_dual_with_object_id, orig_dual_annotation_count
            );
        }
    }

    Ok(())
}

#[test]
fn test_version() -> Result<(), Box<dyn std::error::Error>> {
    println!("STUDIO_SERVER: {:?}", env::var("STUDIO_SERVER"));
    println!("STUDIO_TOKEN: {:?}", env::var("STUDIO_TOKEN"));
    println!("STUDIO_USERNAME: {:?}", env::var("STUDIO_USERNAME"));
    println!("STUDIO_PASSWORD: {:?}", env::var("STUDIO_PASSWORD"));

    let mut cmd = edgefirst_cmd();
    cmd.arg("version");
    cmd.assert()
        .success()
        .stdout(predicates::str::contains(env!("CARGO_PKG_VERSION")));
    Ok(())
}

#[test]
fn test_token() -> Result<(), Box<dyn std::error::Error>> {
    let mut cmd = edgefirst_cmd();
    cmd.arg("token");

    let token = cmd.ok()?.stdout;
    assert!(!token.is_empty());

    println!("Token: {}", String::from_utf8_lossy(&token));

    let token = String::from_utf8(token)?;
    let token_parts: Vec<&str> = token.split('.').collect();
    assert_eq!(token_parts.len(), 3);

    let decoded = base64::engine::general_purpose::STANDARD_NO_PAD
        .decode(token_parts[1])
        .unwrap();
    let payload: HashMap<String, serde_json::Value> = serde_json::from_slice(&decoded)?;
    let username = payload.get("username");
    assert!(username.is_some());
    let username = username.unwrap().as_str().unwrap();
    assert!(!username.is_empty());

    if let Ok(studio_username) = env::var("STUDIO_USERNAME") {
        assert_eq!(studio_username, username)
    }

    Ok(())
}

#[test]
fn test_organization() -> Result<(), Box<dyn std::error::Error>> {
    let mut cmd = edgefirst_cmd();
    cmd.arg("organization");
    cmd.assert()
        .success()
        .stdout(predicates::str::contains("Organization:"));
    Ok(())
}

#[test]
fn test_organization_details() -> Result<(), Box<dyn std::error::Error>> {
    let mut cmd = edgefirst_cmd();
    cmd.arg("organization");

    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    // Verify all expected fields are present
    assert!(output_str.contains("Username:"));
    assert!(output_str.contains("Organization:"));
    assert!(output_str.contains("ID:"));
    assert!(output_str.contains("Credits:"));

    println!("Organization output:\n{}", output_str);
    Ok(())
}

// ===== Authentication Tests =====

/// Comprehensive authentication workflow test
///
/// Tests: login -> token validation -> logout -> re-login -> new token issued
/// This consolidates multiple auth tests into one efficient workflow.
#[test]
#[file_serial]
fn test_auth_workflow() -> Result<(), Box<dyn std::error::Error>> {
    use std::{fs, time::SystemTime};

    // Get credentials from environment (required for authentication tests)
    let username =
        env::var("STUDIO_USERNAME").expect("STUDIO_USERNAME must be set for authentication tests");
    let _password =
        env::var("STUDIO_PASSWORD").expect("STUDIO_PASSWORD must be set for authentication tests");

    // Get the token path - must match what the CLI uses (no fallback)
    let token_path = ProjectDirs::from("ai", "EdgeFirst", "EdgeFirst Studio")
        .map(|d| d.config_dir().join("token"))
        .ok_or("ProjectDirs::from returned None - cannot determine token path")?;

    // Clean up any existing token file to ensure a clean test state
    // This prevents interference from other tests or previous runs
    if token_path.exists() {
        println!(
            "Removing existing token file ({} bytes) to ensure clean state",
            fs::metadata(&token_path).map(|m| m.len()).unwrap_or(0)
        );
        fs::remove_file(&token_path)?;
    }

    // Debug: Show environment info to help diagnose path issues
    println!("HOME: {:?}", env::var("HOME"));
    println!("XDG_CONFIG_HOME: {:?}", env::var("XDG_CONFIG_HOME"));
    println!("Token path: {:?}", token_path);
    println!("=== STEP 1: First Login ===");
    let time_before = SystemTime::now();
    std::thread::sleep(std::time::Duration::from_millis(100));

    let mut cmd = edgefirst_cmd();
    cmd.arg("login");

    let output = cmd.output()?;
    let stdout_str = String::from_utf8_lossy(&output.stdout);
    let stderr_str = String::from_utf8_lossy(&output.stderr);
    println!("Login stdout:\n{}", stdout_str);
    println!("Login stderr:\n{}", stderr_str);
    println!("Login exit status: {:?}", output.status);

    assert!(
        output.status.success(),
        "Login command should succeed (exit code: {:?})",
        output.status
    );
    assert!(
        stdout_str.contains("Successfully logged into EdgeFirst Studio"),
        "Should contain success message, got: {}",
        stdout_str
    );
    assert!(
        stdout_str.contains(&username),
        "Should contain username '{}', got: {}",
        username,
        stdout_str
    );
    assert!(token_path.exists(), "Token file should exist after login");

    let metadata = fs::metadata(&token_path)?;
    let modified_time = metadata.modified()?;
    assert!(
        modified_time > time_before,
        "Token file should be updated after login"
    );

    // Validate JWT token format and username
    let first_token = fs::read_to_string(&token_path)?;
    println!(
        "Token file size: {} bytes, path: {:?}",
        first_token.len(),
        token_path
    );
    assert!(
        !first_token.is_empty(),
        "Token file should not be empty (path: {:?})",
        token_path
    );

    let token_parts: Vec<&str> = first_token.trim().split('.').collect();
    assert_eq!(
        token_parts.len(),
        3,
        "Token should be a valid JWT with 3 parts"
    );

    // Debug: Log all token parts for troubleshooting
    println!("Token structure:");
    println!("  Header ({}): {}", token_parts[0].len(), token_parts[0]);
    println!("  Payload ({}): {}", token_parts[1].len(), token_parts[1]);
    println!("  Signature ({}): {}", token_parts[2].len(), token_parts[2]);

    let decoded = base64::engine::general_purpose::STANDARD_NO_PAD
        .decode(token_parts[1])
        .unwrap_or_else(|e| {
            eprintln!(
                "Failed to decode JWT payload: {:?}. Payload part: {}",
                e, token_parts[1]
            );
            panic!("Token payload should be valid base64: {:?}", e)
        });

    // Debug: Log the decoded payload for troubleshooting
    let decoded_str = String::from_utf8_lossy(&decoded);
    println!("Decoded JWT payload ({}): {}", decoded.len(), decoded_str);

    let payload: HashMap<String, serde_json::Value> = serde_json::from_slice(&decoded)
        .unwrap_or_else(|_| {
            panic!(
                "Token payload should be valid JSON. Raw decoded: {}",
                decoded_str
            )
        });

    let token_username = payload
        .get("username")
        .and_then(|v| v.as_str())
        .expect("Token should contain username field");

    assert_eq!(
        token_username, username,
        "Token username should match login username"
    );

    println!("✓ First login successful, token valid");
    let first_modified = fs::metadata(&token_path)?.modified()?;

    println!("\n=== STEP 2: Logout ===");
    let mut cmd = edgefirst_cmd();
    cmd.arg("logout");

    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    assert!(output_str.contains("Successfully logged out of EdgeFirst Studio"));
    assert!(
        !token_path.exists(),
        "Token file should be removed after logout"
    );

    println!("✓ Logout successful, token file removed");

    println!("\n=== STEP 3: Re-login (verify new token issued) ===");
    std::thread::sleep(std::time::Duration::from_secs(2)); // Ensure timestamp difference

    let mut cmd = edgefirst_cmd();
    cmd.arg("login");
    cmd.ok()?;

    let second_token = fs::read_to_string(&token_path)?;
    let second_modified = fs::metadata(&token_path)?.modified()?;

    assert_ne!(
        first_token, second_token,
        "Re-login should create a new token"
    );
    assert!(
        second_modified > first_modified,
        "Token file should be updated on re-login"
    );

    println!("✓ Re-login successful, new token issued");
    println!("\n✅ Authentication workflow completed successfully");

    Ok(())
}

#[test]
#[file_serial]
fn test_corrupted_token_handling() -> Result<(), Box<dyn std::error::Error>> {
    let _username =
        env::var("STUDIO_USERNAME").expect("STUDIO_USERNAME must be set for authentication tests");

    // Use a temporary directory for token isolation from parallel tests.
    // This prevents race conditions where another test's login overwrites
    // our corrupted token file.
    let temp_dir = tempfile::tempdir()?;
    let token_path = temp_dir.path().join("token");

    println!("Token path: {:?}", token_path);

    // Login first to create a valid token in the isolated temp directory
    let mut cmd = edgefirst_cmd();
    cmd.arg("login");
    cmd.env("STUDIO_TOKEN_PATH", &token_path);
    cmd.ok()?;

    assert!(token_path.exists(), "Token file should exist after login");

    // Corrupt the token file with invalid data
    fs::write(&token_path, "this.is.corrupted")?;
    println!("✓ Corrupted token file created at {:?}", token_path);

    // Try to run a command that requires authentication WITHOUT credentials
    // This should gracefully handle the corrupted token
    let mut cmd = edgefirst_cmd();
    cmd.arg("organization");
    // Explicitly unset authentication environment variables FIRST so the command
    // can't auto-login via clap's env feature.
    cmd.env_remove("STUDIO_USERNAME");
    cmd.env_remove("STUDIO_PASSWORD");
    cmd.env_remove("STUDIO_TOKEN");
    // Use the isolated token path (set AFTER env_remove to override any existing)
    // Keep STUDIO_SERVER as it controls which server instance to connect to.
    cmd.env("STUDIO_TOKEN_PATH", &token_path);

    let output = cmd.output()?;
    let stderr = String::from_utf8_lossy(&output.stderr);
    let stdout = String::from_utf8_lossy(&output.stdout);

    println!("Command stderr:\n{}", stderr);
    println!("Command stdout:\n{}", stdout);

    // Should fail with authentication error, not a crash
    assert!(
        !output.status.success(),
        "Command should fail with corrupted token and no credentials"
    );
    assert!(
        stderr.contains("Authentication failed")
            || stderr.contains("Please login again")
            || stderr.contains("Empty token"),
        "Should provide helpful error message about re-authenticating"
    );

    // Corrupted token should be removed
    // (either by with_token_path or by the logout in error handling)
    println!("Token file exists after error: {}", token_path.exists());

    // Should be able to login again
    let mut cmd = edgefirst_cmd();
    cmd.arg("login");
    cmd.env("STUDIO_TOKEN_PATH", &token_path);
    cmd.ok()?;

    assert!(
        token_path.exists(),
        "Should be able to login after corruption"
    );
    let new_token = fs::read_to_string(&token_path)?;
    assert_ne!(new_token, "this.is.corrupted", "New token should be valid");

    println!("✓ Successfully logged in again after corruption");

    Ok(())
}

// ===== Project Tests =====

#[test]
fn test_projects_list() -> Result<(), Box<dyn std::error::Error>> {
    let mut cmd = edgefirst_cmd();
    cmd.arg("projects");
    cmd.assert().success();
    Ok(())
}

#[test]
fn test_projects_filter_by_name() -> Result<(), Box<dyn std::error::Error>> {
    let mut cmd = edgefirst_cmd();
    cmd.arg("projects").arg("--name").arg("Unit Testing");

    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    assert!(output_str.contains("Unit Testing"));
    println!("Filtered projects:\n{}", output_str);
    Ok(())
}

#[test]
fn test_project_by_id() -> Result<(), Box<dyn std::error::Error>> {
    // First get the project list to extract an ID
    let mut cmd = edgefirst_cmd();
    cmd.arg("projects").arg("--name").arg("Unit Testing");

    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    // Extract project ID from output like "[123] Unit Testing: description"
    let project_id = output_str
        .lines()
        .next()
        .and_then(|line| line.split(']').next())
        .and_then(|s| s.trim_start_matches('[').parse::<String>().ok());

    if let Some(id) = project_id {
        let mut cmd = edgefirst_cmd();
        cmd.arg("project").arg(&id);
        cmd.assert()
            .success()
            .stdout(predicates::str::contains("Unit Testing"));
    }

    Ok(())
}

// ===== Dataset Tests =====

#[test]
fn test_datasets_list_all() -> Result<(), Box<dyn std::error::Error>> {
    let mut cmd = edgefirst_cmd();
    cmd.arg("datasets");
    cmd.assert().success();
    Ok(())
}

#[test]
fn test_datasets_by_project() -> Result<(), Box<dyn std::error::Error>> {
    // First get project ID
    let mut cmd = edgefirst_cmd();
    cmd.arg("projects").arg("--name").arg("Unit Testing");

    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    let project_id = output_str
        .lines()
        .next()
        .and_then(|line| line.split(']').next())
        .and_then(|s| s.trim_start_matches('[').parse::<String>().ok());

    if let Some(id) = project_id {
        let mut cmd = edgefirst_cmd();
        cmd.arg("datasets").arg(&id);
        cmd.assert().success();
    }

    Ok(())
}

#[test]
fn test_datasets_with_labels() -> Result<(), Box<dyn std::error::Error>> {
    // Get Unit Testing with COCO dataset
    let mut cmd = edgefirst_cmd();
    cmd.arg("projects").arg("--name").arg("Unit Testing");

    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    let project_id = output_str
        .lines()
        .next()
        .and_then(|line| line.split(']').next())
        .and_then(|s| s.trim_start_matches('[').parse::<String>().ok());

    if let Some(id) = project_id {
        let mut cmd = edgefirst_cmd();
        cmd.arg("datasets").arg(&id).arg("--labels");

        let output = cmd.ok()?.stdout;
        let output_str = String::from_utf8(output)?;

        assert!(output_str.contains("Labels:"));
        println!("Datasets with labels:\n{}", output_str);
    }

    Ok(())
}

#[test]
fn test_datasets_with_annotation_sets() -> Result<(), Box<dyn std::error::Error>> {
    let mut cmd = edgefirst_cmd();
    cmd.arg("projects").arg("--name").arg("Unit Testing");

    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    let project_id = output_str
        .lines()
        .next()
        .and_then(|line| line.split(']').next())
        .and_then(|s| s.trim_start_matches('[').parse::<String>().ok());

    if let Some(id) = project_id {
        let mut cmd = edgefirst_cmd();
        cmd.arg("datasets").arg(&id).arg("--annotation-sets");

        let output = cmd.ok()?.stdout;
        let output_str = String::from_utf8(output)?;

        assert!(output_str.contains("Annotation Sets:"));
        println!("Datasets with annotation sets:\n{}", output_str);
    }

    Ok(())
}

#[test]
fn test_dataset_by_id() -> Result<(), Box<dyn std::error::Error>> {
    // Get a dataset ID from Unit Testing project
    let mut cmd = edgefirst_cmd();
    cmd.arg("projects").arg("--name").arg("Unit Testing");

    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    let project_id = output_str
        .lines()
        .next()
        .and_then(|line| line.split(']').next())
        .and_then(|s| s.trim_start_matches('[').parse::<String>().ok());

    if let Some(proj_id) = project_id {
        let mut cmd = edgefirst_cmd();
        cmd.arg("datasets").arg(&proj_id);

        let output = cmd.ok()?.stdout;
        let output_str = String::from_utf8(output)?;

        // Get first dataset ID from output
        let dataset_id = output_str
            .lines()
            .next()
            .and_then(|line| line.split(']').next())
            .and_then(|s| s.trim_start_matches('[').parse::<String>().ok());

        if let Some(ds_id) = dataset_id {
            let mut cmd = edgefirst_cmd();
            cmd.arg("dataset").arg(&ds_id);
            cmd.assert().success();
        }
    }

    Ok(())
}

#[test]
fn test_download_annotations() -> Result<(), Box<dyn std::error::Error>> {
    let dataset = get_test_dataset();
    let dataset_name_lower = dataset.to_lowercase().replace("ds-", "dataset-");
    let (_, annotation_set_id) = get_dataset_and_first_annotation_set(&dataset)?;

    let test_dir = get_test_data_dir();

    // Test JSON format download
    let json_file = test_dir.join(format!(
        "{}_annotations_{}.json",
        dataset_name_lower,
        std::process::id()
    ));

    let mut cmd = edgefirst_cmd();
    cmd.arg("download-annotations")
        .arg(&annotation_set_id)
        .arg(&json_file);

    cmd.assert().success();

    assert!(json_file.exists(), "JSON annotations file should exist");
    assert!(
        json_file.metadata()?.len() > 0,
        "JSON annotations file should not be empty"
    );
    println!("Downloaded annotations to {:?}", json_file);

    fs::remove_file(&json_file)?;

    // Test Arrow format download
    let arrow_file = test_dir.join(format!(
        "{}_annotations_{}.arrow",
        dataset_name_lower,
        std::process::id()
    ));

    let mut cmd = edgefirst_cmd();
    cmd.arg("download-annotations")
        .arg(&annotation_set_id)
        .arg(&arrow_file);

    cmd.assert().success();

    assert!(arrow_file.exists(), "Arrow annotations file should exist");
    assert!(
        arrow_file.metadata()?.len() > 0,
        "Arrow annotations file should not be empty"
    );
    println!("Downloaded annotations to {:?}", arrow_file);

    fs::remove_file(&arrow_file)?;

    Ok(())
}

#[test]
fn test_upload_dataset_persistent_copy() -> Result<(), Box<dyn std::error::Error>> {
    let dataset = get_test_dataset();
    let (source_dataset_id, source_annotation_set_id) =
        get_dataset_and_first_annotation_set(&dataset)?;

    let images_dir = download_dataset_from_server(&source_dataset_id)?;
    let annotations_path = download_annotations_from_server(&source_annotation_set_id)?;
    validate_dataset_structure(images_dir.as_path())?;

    let project_id = get_project_id_by_name("Unit Testing")?
        .ok_or_else(|| "Project 'Unit Testing' not found".to_string())?;

    let timestamp = Utc::now().format("%Y%m%d-%H%M%S").to_string();
    let new_dataset_name = format!("QA {} Upload {}", dataset, timestamp);

    let mut cmd = edgefirst_cmd();
    cmd.arg("create-dataset")
        .arg(&project_id)
        .arg(&new_dataset_name);

    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;
    let new_dataset_id = output_str
        .lines()
        .find_map(|line| line.strip_prefix("Created dataset with ID: "))
        .map(|s| s.trim().to_string())
        .ok_or_else(|| "Failed to parse dataset ID from create-dataset output".to_string())?;

    let annotation_set_name = format!("{} Annotations", new_dataset_name);
    let mut cmd = edgefirst_cmd();
    cmd.arg("create-annotation-set")
        .arg(&new_dataset_id)
        .arg(&annotation_set_name);

    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;
    let new_annotation_set_id = output_str
        .lines()
        .find_map(|line| line.strip_prefix("Created annotation set with ID: "))
        .map(|s| s.trim().to_string())
        .ok_or_else(|| {
            "Failed to parse annotation set ID from create-annotation-set output".to_string()
        })?;

    let mut cmd = edgefirst_cmd();
    cmd.arg("upload-dataset")
        .arg(&new_dataset_id)
        .arg("--annotations")
        .arg(&annotations_path)
        .arg("--annotation-set-id")
        .arg(&new_annotation_set_id)
        .arg("--images")
        .arg(&images_dir);

    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;
    assert!(
        output_str.contains("Successfully uploaded") || output_str.contains("samples"),
        "Expected upload to report success, got: {}",
        output_str
    );

    println!(
        "✓ Created and uploaded dataset: {} (annotation set {})",
        new_dataset_id, new_annotation_set_id
    );
    println!("  Images uploaded from: {:?}", images_dir);
    println!("  Annotations uploaded from: {:?}", annotations_path);

    // Clean up: delete the created dataset (this also deletes the annotation set)
    println!("\n=== CLEANUP: Deleting created dataset ===");
    let mut cmd = edgefirst_cmd();
    cmd.arg("delete-dataset").arg(&new_dataset_id);

    match cmd.output() {
        Ok(output) if output.status.success() => {
            println!("✓ Deleted dataset: {}", new_dataset_id);
        }
        Ok(output) => {
            let stderr = String::from_utf8_lossy(&output.stderr);
            eprintln!(
                "⚠️  Failed to delete dataset {}: {}",
                new_dataset_id, stderr
            );
        }
        Err(e) => {
            eprintln!("⚠️  Error deleting dataset {}: {}", new_dataset_id, e);
        }
    }

    // Clean up local files
    if let Err(err) = fs::remove_dir_all(&images_dir) {
        eprintln!(
            "⚠️  Failed to remove downloaded images directory {:?}: {}",
            images_dir, err
        );
    }

    if let Err(err) = fs::remove_file(&annotations_path) {
        eprintln!(
            "⚠️  Failed to remove downloaded annotations file {:?}: {}",
            annotations_path, err
        );
    }

    Ok(())
}

/// End-to-end dataset roundtrip test
///
/// Tests complete workflow: Download → Upload → Download → Compare → Cleanup
///
/// Dataset: Configurable via TEST_DATASET env var (default: "Deer")
/// Requirements:
/// - Dataset must exist in "Unit Testing" project
/// - Must have at least one annotation set
/// - Supports mixed sensors, annotation types, and sequences
///
/// **Note**: This test uploads 1600+ samples and takes ~3 minutes to complete.
#[test]
#[file_serial]
#[ignore = "Temporarily disabled due to CI timeout issues - run locally with: cargo test test_dataset_roundtrip -- --ignored"]
fn test_dataset_roundtrip() -> Result<(), Box<dyn std::error::Error>> {
    // Download→Upload→Download→Compare test for configurable dataset
    // This verifies Arrow file format preserves all metadata (sequences, groups,
    // annotations)

    let dataset = get_test_dataset();
    println!("Testing dataset roundtrip for: {}", dataset);

    let types = get_test_dataset_types();
    println!("Testing annotation types: {}", types.join(","));

    // Step 1: Download original dataset
    let (source_dataset_id, source_annotation_set_id) =
        get_dataset_and_first_annotation_set(&dataset)?;

    let original_images = download_dataset_from_server(&source_dataset_id)?;
    let original_annotations = download_annotations_from_server_with_types(
        &source_annotation_set_id,
        &types.iter().map(|s| s.as_str()).collect::<Vec<_>>(),
    )?;

    // Verify downloaded dataset structure is valid
    validate_dataset_structure(original_images.as_path())?;
    println!("✓ Downloaded dataset has valid structure");

    // Step 2: Upload to new dataset
    let project_id = get_project_id_by_name("Unit Testing")?
        .ok_or_else(|| "Project 'Unit Testing' not found".to_string())?;

    let timestamp = Utc::now().format("%Y%m%d-%H%M%S").to_string();
    let new_dataset_name = format!("{} Roundtrip {}", dataset, timestamp);

    let mut cmd = edgefirst_cmd();
    cmd.arg("create-dataset")
        .arg(&project_id)
        .arg(&new_dataset_name);
    let output = cmd.ok()?.stdout;
    let new_dataset_id = String::from_utf8(output)?
        .lines()
        .find_map(|line| line.strip_prefix("Created dataset with ID: "))
        .map(|s| s.trim().to_string())
        .ok_or_else(|| "Failed to parse dataset ID".to_string())?;

    let annotation_set_name = format!("{} Annotations", new_dataset_name);
    let mut cmd = edgefirst_cmd();
    cmd.arg("create-annotation-set")
        .arg(&new_dataset_id)
        .arg(&annotation_set_name);
    let output = cmd.ok()?.stdout;
    let new_annotation_set_id = String::from_utf8(output)?
        .lines()
        .find_map(|line| line.strip_prefix("Created annotation set with ID: "))
        .map(|s| s.trim().to_string())
        .ok_or_else(|| "Failed to parse annotation set ID".to_string())?;

    // Upload with sequence support
    let mut cmd = edgefirst_cmd();
    cmd.arg("upload-dataset")
        .arg(&new_dataset_id)
        .arg("--annotations")
        .arg(&original_annotations)
        .arg("--annotation-set-id")
        .arg(&new_annotation_set_id)
        .arg("--images")
        .arg(&original_images);

    // Capture output to see debug messages
    let output = cmd.ok()?;
    eprintln!("\n=== UPLOAD COMMAND OUTPUT ===");
    eprintln!("{}", String::from_utf8_lossy(&output.stdout));
    eprintln!("{}", String::from_utf8_lossy(&output.stderr));
    eprintln!("=== END UPLOAD OUTPUT ===\n");

    // Step 3: Download the uploaded dataset
    let redownloaded_images = download_dataset_from_server(&new_dataset_id)?;
    let redownloaded_annotations = download_annotations_from_server_with_types(
        &new_annotation_set_id,
        &types.iter().map(|s| s.as_str()).collect::<Vec<_>>(),
    )?;

    // Step 4: Compare image counts and directory structure
    // Note: Server may rename files, so we compare counts and structure, not exact
    // names
    let original_files = collect_relative_file_paths(&original_images)?;
    let redownloaded_files = collect_relative_file_paths(&redownloaded_images)?;

    // Count root images and sequence images
    let original_root_count = original_files.iter().filter(|p| !p.contains('/')).count();
    let original_seq_count = original_files.iter().filter(|p| p.contains('/')).count();
    let redownloaded_root_count = redownloaded_files
        .iter()
        .filter(|p| !p.contains('/'))
        .count();
    let redownloaded_seq_count = redownloaded_files
        .iter()
        .filter(|p| p.contains('/'))
        .count();

    println!("\n=== File Distribution ===");
    println!(
        "Original: {} root images, {} sequence images",
        original_root_count, original_seq_count
    );
    println!(
        "Redownloaded: {} root images, {} sequence images",
        redownloaded_root_count, redownloaded_seq_count
    );

    // Verify total file count matches
    assert_eq!(
        original_files.len(),
        redownloaded_files.len(),
        "File count mismatch: original {} vs redownloaded {}",
        original_files.len(),
        redownloaded_files.len()
    );

    // Verify root vs sequence distribution matches
    assert_eq!(
        original_root_count, redownloaded_root_count,
        "Root image count mismatch: {} vs {}",
        original_root_count, redownloaded_root_count
    );

    assert_eq!(
        original_seq_count, redownloaded_seq_count,
        "Sequence image count mismatch: {} vs {}",
        original_seq_count, redownloaded_seq_count
    );

    // Count sequence subdirectories (if any sequences exist)
    if original_seq_count > 0 {
        let original_sequences: BTreeSet<String> = original_files
            .iter()
            .filter_map(|p| p.split('/').next().map(|s| s.to_string()))
            .collect();
        let redownloaded_sequences: BTreeSet<String> = redownloaded_files
            .iter()
            .filter_map(|p| p.split('/').next().map(|s| s.to_string()))
            .collect();

        assert_eq!(
            original_sequences.len(),
            redownloaded_sequences.len(),
            "Sequence count mismatch: {} vs {}",
            original_sequences.len(),
            redownloaded_sequences.len()
        );
        println!("  Sequences: {} preserved", original_sequences.len());
    }

    // Step 5: Compare Arrow file sample counts AND verify groups/annotations are
    // preserved File names may differ, but sample count and metadata structure
    // should match
    let original_arrow_bytes = fs::read(&original_annotations)?;
    let redownloaded_arrow_bytes = fs::read(&redownloaded_annotations)?;

    println!("\n=== Arrow File Comparison ===");
    println!(
        "Arrow files: original {} bytes, redownloaded {} bytes",
        original_arrow_bytes.len(),
        redownloaded_arrow_bytes.len()
    );

    // Comprehensive verification of groups and annotations
    #[cfg(feature = "polars")]
    {
        println!("\n=== COMPREHENSIVE VERIFICATION ===");
        match compare_arrow_files(&original_annotations, &redownloaded_annotations) {
            Ok(()) => println!("✓ Groups and annotations verified successfully"),
            Err(e) => {
                return Err(format!("Arrow file verification failed: {}", e).into());
            }
        }
    }

    println!(
        "{} dataset roundtrip successful: {} ({} annotation set {})",
        dataset, new_dataset_name, new_dataset_id, new_annotation_set_id
    );
    println!(
        "  Files: {} original, {} redownloaded",
        original_files.len(),
        redownloaded_files.len()
    );
    println!(
        "  Arrow file sizes: original {} bytes, redownloaded {} bytes",
        original_arrow_bytes.len(),
        redownloaded_arrow_bytes.len()
    );

    // Cleanup local files
    fs::remove_dir_all(&original_images).ok();
    fs::remove_file(&original_annotations).ok();
    fs::remove_dir_all(&redownloaded_images).ok();
    fs::remove_file(&redownloaded_annotations).ok();

    // Cleanup: Delete the created dataset from the server
    println!("\n=== CLEANUP: Deleting created dataset ===");
    let mut cmd = edgefirst_cmd();
    cmd.arg("delete-dataset").arg(&new_dataset_id);

    match cmd.output() {
        Ok(output) if output.status.success() => {
            println!("✓ Deleted dataset: {}", new_dataset_id);
        }
        Ok(output) => {
            let stderr = String::from_utf8_lossy(&output.stderr);
            eprintln!(
                "⚠️  Failed to delete dataset {}: {}",
                new_dataset_id, stderr
            );
        }
        Err(e) => {
            eprintln!("⚠️  Error deleting dataset {}: {}", new_dataset_id, e);
        }
    }

    println!("\n✅ Dataset roundtrip test completed successfully");

    Ok(())
}

// ===== Experiment and Training Session Tests =====

#[test]
fn test_experiments_list() -> Result<(), Box<dyn std::error::Error>> {
    let mut cmd = edgefirst_cmd();
    cmd.arg("projects").arg("--name").arg("Unit Testing");

    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    let project_id = output_str
        .lines()
        .next()
        .and_then(|line| line.split(']').next())
        .and_then(|s| s.trim_start_matches('[').parse::<String>().ok());

    if let Some(id) = project_id {
        let mut cmd = edgefirst_cmd();
        cmd.arg("experiments").arg(&id);
        cmd.assert().success();
    }

    Ok(())
}

#[test]
fn test_experiments_filter_by_name() -> Result<(), Box<dyn std::error::Error>> {
    let mut cmd = edgefirst_cmd();
    cmd.arg("projects").arg("--name").arg("Unit Testing");

    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    let project_id = output_str
        .lines()
        .next()
        .and_then(|line| line.split(']').next())
        .and_then(|s| s.trim_start_matches('[').parse::<String>().ok());

    if let Some(id) = project_id {
        let mut cmd = edgefirst_cmd();
        cmd.arg("experiments")
            .arg(&id)
            .arg("--name")
            .arg("Unit Testing");

        let output = cmd.ok()?.stdout;
        let output_str = String::from_utf8(output)?;

        assert!(output_str.contains("Unit Testing"));
        println!("Filtered experiments:\n{}", output_str);
    }

    Ok(())
}

#[test]
fn test_experiment_by_id() -> Result<(), Box<dyn std::error::Error>> {
    let mut cmd = edgefirst_cmd();
    cmd.arg("projects").arg("--name").arg("Unit Testing");

    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    let project_id = output_str
        .lines()
        .next()
        .and_then(|line| line.split(']').next())
        .and_then(|s| s.trim_start_matches('[').parse::<String>().ok());

    if let Some(proj_id) = project_id {
        let mut cmd = edgefirst_cmd();
        cmd.arg("experiments")
            .arg(&proj_id)
            .arg("--name")
            .arg("Unit Testing");

        let output = cmd.ok()?.stdout;
        let output_str = String::from_utf8(output)?;

        // Extract experiment ID (format: [exp-XXX])
        let exp_id = output_str
            .lines()
            .find(|line| line.contains("Unit Testing") && line.contains('['))
            .and_then(|line| {
                line.split('[')
                    .nth(1)
                    .and_then(|s| s.split(']').next())
                    .map(|s| s.trim().to_string())
            });

        if let Some(id) = exp_id {
            let mut cmd = edgefirst_cmd();
            cmd.arg("experiment").arg(&id);
            cmd.assert()
                .success()
                .stdout(predicates::str::contains("Unit Testing"));
        }
    }

    Ok(())
}

#[test]
fn test_training_sessions_list() -> Result<(), Box<dyn std::error::Error>> {
    let mut cmd = edgefirst_cmd();
    cmd.arg("projects").arg("--name").arg("Unit Testing");

    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    let project_id = output_str
        .lines()
        .next()
        .and_then(|line| line.split(']').next())
        .and_then(|s| s.trim_start_matches('[').parse::<String>().ok());

    if let Some(proj_id) = project_id {
        let mut cmd = edgefirst_cmd();
        cmd.arg("experiments")
            .arg(&proj_id)
            .arg("--name")
            .arg("Unit Testing");

        let output = cmd.ok()?.stdout;
        let output_str = String::from_utf8(output)?;

        // Extract experiment ID (format: [exp-XXX])
        let exp_id = output_str
            .lines()
            .find(|line| line.contains("Unit Testing") && line.contains('['))
            .and_then(|line| {
                line.split('[')
                    .nth(1)
                    .and_then(|s| s.split(']').next())
                    .map(|s| s.trim().to_string())
            });

        if let Some(id) = exp_id {
            let mut cmd = edgefirst_cmd();
            cmd.arg("training-sessions").arg(&id);
            cmd.assert().success();
        }
    }

    Ok(())
}

#[test]
fn test_training_sessions_filter_by_name() -> Result<(), Box<dyn std::error::Error>> {
    let mut cmd = edgefirst_cmd();
    cmd.arg("projects").arg("--name").arg("Unit Testing");

    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    let project_id = output_str
        .lines()
        .next()
        .and_then(|line| line.split(']').next())
        .and_then(|s| s.trim_start_matches('[').parse::<String>().ok());

    if let Some(proj_id) = project_id {
        let mut cmd = edgefirst_cmd();
        cmd.arg("experiments")
            .arg(&proj_id)
            .arg("--name")
            .arg("Unit Testing");

        let output = cmd.ok()?.stdout;
        let output_str = String::from_utf8(output)?;

        let exp_id = output_str
            .lines()
            .find(|line| line.contains("Unit Testing") && line.contains('['))
            .and_then(|line| {
                line.split('[')
                    .nth(1)
                    .and_then(|s| s.split(']').next())
                    .map(|s| s.trim().to_string())
            });

        if let Some(id) = exp_id {
            let mut cmd = edgefirst_cmd();
            cmd.arg("training-sessions")
                .arg(&id)
                .arg("--name")
                .arg("modelpack-usermanaged");

            let output = cmd.ok()?.stdout;
            let output_str = String::from_utf8(output)?;

            assert!(output_str.contains("modelpack-usermanaged"));
            println!("Filtered training sessions:\n{}", output_str);
        }
    }

    Ok(())
}

#[test]
fn test_training_session_by_id() -> Result<(), Box<dyn std::error::Error>> {
    let mut cmd = edgefirst_cmd();
    cmd.arg("projects").arg("--name").arg("Unit Testing");

    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    let project_id = output_str
        .lines()
        .next()
        .and_then(|line| line.split(']').next())
        .and_then(|s| s.trim_start_matches('[').parse::<String>().ok());

    if let Some(proj_id) = project_id {
        let mut cmd = edgefirst_cmd();
        cmd.arg("experiments")
            .arg(&proj_id)
            .arg("--name")
            .arg("Unit Testing");

        let output = cmd.ok()?.stdout;
        let output_str = String::from_utf8(output)?;

        let exp_id = output_str
            .lines()
            .find(|line| line.contains("Unit Testing") && line.contains('['))
            .and_then(|line| {
                line.split('[')
                    .nth(1)
                    .and_then(|s| s.split(']').next())
                    .map(|s| s.trim().to_string())
            });

        if let Some(id) = exp_id {
            let mut cmd = edgefirst_cmd();
            cmd.arg("training-sessions")
                .arg(&id)
                .arg("--name")
                .arg("modelpack-usermanaged");

            let output = cmd.ok()?.stdout;
            let output_str = String::from_utf8(output)?;

            // Extract session ID (format: t-xxx)
            let session_id = output_str
                .lines()
                .find(|line| line.contains("modelpack-usermanaged"))
                .and_then(|line| line.split_whitespace().next())
                .map(|s| s.to_string());

            if let Some(sid) = session_id {
                let mut cmd = edgefirst_cmd();
                cmd.arg("training-session").arg(&sid);
                cmd.assert()
                    .success()
                    .stdout(predicates::str::contains("modelpack-usermanaged"));
            }
        }
    }

    Ok(())
}

#[test]
fn test_training_session_with_model_params() -> Result<(), Box<dyn std::error::Error>> {
    let mut cmd = edgefirst_cmd();
    cmd.arg("projects").arg("--name").arg("Unit Testing");

    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    let project_id = output_str
        .lines()
        .next()
        .and_then(|line| line.split(']').next())
        .and_then(|s| s.trim_start_matches('[').parse::<String>().ok());

    if let Some(proj_id) = project_id {
        let mut cmd = edgefirst_cmd();
        cmd.arg("experiments")
            .arg(&proj_id)
            .arg("--name")
            .arg("Unit Testing");

        let output = cmd.ok()?.stdout;
        let output_str = String::from_utf8(output)?;

        let exp_id = output_str
            .lines()
            .find(|line| line.contains("Unit Testing") && line.contains('['))
            .and_then(|line| {
                line.split('[')
                    .nth(1)
                    .and_then(|s| s.split(']').next())
                    .map(|s| s.trim().to_string())
            });

        if let Some(id) = exp_id {
            let mut cmd = edgefirst_cmd();
            cmd.arg("training-sessions")
                .arg(&id)
                .arg("--name")
                .arg("modelpack-usermanaged");

            let output = cmd.ok()?.stdout;
            let output_str = String::from_utf8(output)?;

            let session_id = output_str
                .lines()
                .find(|line| line.contains("modelpack-usermanaged"))
                .and_then(|line| line.split_whitespace().next())
                .map(|s| s.to_string());

            if let Some(sid) = session_id {
                let mut cmd = edgefirst_cmd();
                cmd.arg("training-session").arg(&sid).arg("--model");

                let output = cmd.ok()?.stdout;
                let output_str = String::from_utf8(output)?;

                assert!(output_str.contains("Model Parameters:"));
                println!("Training session with model params:\n{}", output_str);
            }
        }
    }

    Ok(())
}

#[test]
fn test_training_session_with_dataset_params() -> Result<(), Box<dyn std::error::Error>> {
    let mut cmd = edgefirst_cmd();
    cmd.arg("projects").arg("--name").arg("Unit Testing");

    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    let project_id = output_str
        .lines()
        .next()
        .and_then(|line| line.split(']').next())
        .and_then(|s| s.trim_start_matches('[').parse::<String>().ok());

    if let Some(proj_id) = project_id {
        let mut cmd = edgefirst_cmd();
        cmd.arg("experiments")
            .arg(&proj_id)
            .arg("--name")
            .arg("Unit Testing");

        let output = cmd.ok()?.stdout;
        let output_str = String::from_utf8(output)?;

        let exp_id = output_str
            .lines()
            .find(|line| line.contains("Unit Testing") && line.contains('['))
            .and_then(|line| {
                line.split('[')
                    .nth(1)
                    .and_then(|s| s.split(']').next())
                    .map(|s| s.trim().to_string())
            });

        if let Some(id) = exp_id {
            let mut cmd = edgefirst_cmd();
            cmd.arg("training-sessions")
                .arg(&id)
                .arg("--name")
                .arg("modelpack-usermanaged");

            let output = cmd.ok()?.stdout;
            let output_str = String::from_utf8(output)?;

            let session_id = output_str
                .lines()
                .find(|line| line.contains("modelpack-usermanaged"))
                .and_then(|line| line.split_whitespace().next())
                .map(|s| s.to_string());

            if let Some(sid) = session_id {
                let mut cmd = edgefirst_cmd();
                cmd.arg("training-session").arg(&sid).arg("--dataset");

                let output = cmd.ok()?.stdout;
                let output_str = String::from_utf8(output)?;

                assert!(output_str.contains("Dataset Parameters:"));
                println!("Training session with dataset params:\n{}", output_str);
            }
        }
    }

    Ok(())
}

#[test]
fn test_training_session_with_artifacts() -> Result<(), Box<dyn std::error::Error>> {
    let mut cmd = edgefirst_cmd();
    cmd.arg("projects").arg("--name").arg("Unit Testing");

    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    let project_id = output_str
        .lines()
        .next()
        .and_then(|line| line.split(']').next())
        .and_then(|s| s.trim_start_matches('[').parse::<String>().ok());

    if let Some(proj_id) = project_id {
        let mut cmd = edgefirst_cmd();
        cmd.arg("experiments")
            .arg(&proj_id)
            .arg("--name")
            .arg("Unit Testing");

        let output = cmd.ok()?.stdout;
        let output_str = String::from_utf8(output)?;

        let exp_id = output_str
            .lines()
            .find(|line| line.contains("Unit Testing") && line.contains('['))
            .and_then(|line| {
                line.split('[')
                    .nth(1)
                    .and_then(|s| s.split(']').next())
                    .map(|s| s.trim().to_string())
            });

        if let Some(id) = exp_id {
            let mut cmd = edgefirst_cmd();
            cmd.arg("training-sessions")
                .arg(&id)
                .arg("--name")
                .arg("modelpack-960x540");

            let output = cmd.ok()?.stdout;
            let output_str = String::from_utf8(output)?;

            let session_id = output_str
                .lines()
                .find(|line| line.contains("modelpack-960x540"))
                .and_then(|line| line.split_whitespace().next())
                .map(|s| s.to_string());

            if let Some(sid) = session_id {
                let mut cmd = edgefirst_cmd();
                cmd.arg("training-session").arg(&sid).arg("--artifacts");

                let output = cmd.ok()?.stdout;
                let output_str = String::from_utf8(output)?;

                assert!(output_str.contains("Artifacts:"));
                println!("Training session with artifacts:\n{}", output_str);
            }
        }
    }

    Ok(())
}

// ===== Artifact Tests =====

/// Generic helper to extract values from CLI output using different strategies
fn extract_from_output<F>(output: &str, extractor: F) -> Option<String>
where
    F: Fn(&str) -> Option<String>,
{
    extractor(output)
}

/// Extracts the first ID in brackets from the first line (e.g., "[123] Name")
fn extract_first_id(output: &str) -> Option<String> {
    extract_from_output(output, |o| {
        o.lines()
            .next()
            .and_then(|line| line.split(']').next())
            .and_then(|s| s.trim_start_matches('[').parse::<String>().ok())
    })
}

/// Finds experiment ID for "Unit Testing" project
fn find_experiment_id(output: &str) -> Option<String> {
    extract_from_output(output, |o| {
        o.lines()
            .find(|line| line.contains("Unit Testing") && line.contains('['))
            .and_then(|line| {
                line.split('[')
                    .nth(1)
                    .and_then(|s| s.split(']').next())
                    .map(|s| s.trim().to_string())
            })
    })
}

/// Finds training session ID by matching session name
fn find_training_session_id(output: &str, name: &str) -> Option<String> {
    extract_from_output(output, |o| {
        o.lines()
            .find(|line| line.contains(name))
            .and_then(|line| line.split_whitespace().next())
            .map(|s| s.to_string())
    })
}

/// Extracts artifact name from bulleted list (e.g., "- artifact.tar.gz")
fn extract_artifact_name(output: &str) -> Option<String> {
    extract_from_output(output, |o| {
        o.lines()
            .find(|line| line.trim().starts_with("- "))
            .map(|line| line.trim().trim_start_matches("- ").to_string())
    })
}

#[test]
#[file_serial]
fn test_download_artifact() -> Result<(), Box<dyn std::error::Error>> {
    use std::fs;

    let mut cmd = edgefirst_cmd();
    cmd.arg("projects").arg("--name").arg("Unit Testing");
    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    let proj_id = extract_first_id(&output_str).ok_or("Failed to extract project ID")?;

    let mut cmd = edgefirst_cmd();
    cmd.arg("experiments")
        .arg(&proj_id)
        .arg("--name")
        .arg("Unit Testing");
    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    let exp_id = find_experiment_id(&output_str).ok_or("Failed to find experiment ID")?;

    let mut cmd = edgefirst_cmd();
    cmd.arg("training-sessions")
        .arg(&exp_id)
        .arg("--name")
        .arg("modelpack-960x540");
    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    let session_id = find_training_session_id(&output_str, "modelpack-960x540")
        .ok_or("Failed to find training session")?;

    let mut cmd = edgefirst_cmd();
    cmd.arg("training-session")
        .arg(&session_id)
        .arg("--artifacts");
    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    let artifact_name = extract_artifact_name(&output_str).ok_or("Failed to find artifact name")?;

    // Use target/testdata directory for downloads
    let test_dir = get_test_data_dir();
    let output_file = test_dir.join(format!("artifact_{}_{}", std::process::id(), artifact_name));

    // Clean up any existing file
    if output_file.exists() {
        fs::remove_file(&output_file)?;
    }

    let mut cmd = edgefirst_cmd();
    cmd.arg("download-artifact")
        .arg(&session_id)
        .arg(&artifact_name)
        .arg("--output")
        .arg(&output_file);

    cmd.assert().success();

    // Verify file was downloaded
    assert!(output_file.exists());
    println!("Downloaded artifact to {:?}", output_file);

    // Clean up
    fs::remove_file(&output_file)?;

    Ok(())
}

#[test]
#[file_serial]
fn test_upload_artifact() -> Result<(), Box<dyn std::error::Error>> {
    use std::{fs::File, io::Write};

    let mut cmd = edgefirst_cmd();
    cmd.arg("projects").arg("--name").arg("Unit Testing");

    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    let project_id = output_str
        .lines()
        .next()
        .and_then(|line| line.split(']').next())
        .and_then(|s| s.trim_start_matches('[').parse::<String>().ok());

    if let Some(proj_id) = project_id {
        let mut cmd = edgefirst_cmd();
        cmd.arg("experiments")
            .arg(&proj_id)
            .arg("--name")
            .arg("Unit Testing");

        let output = cmd.ok()?.stdout;
        let output_str = String::from_utf8(output)?;

        let exp_id = output_str
            .lines()
            .find(|line| line.contains("Unit Testing") && line.contains('['))
            .and_then(|line| {
                line.split('[')
                    .nth(1)
                    .and_then(|s| s.split(']').next())
                    .map(|s| s.trim().to_string())
            });

        if let Some(id) = exp_id {
            let mut cmd = edgefirst_cmd();
            cmd.arg("training-sessions")
                .arg(&id)
                .arg("--name")
                .arg("modelpack-usermanaged");

            let output = cmd.ok()?.stdout;
            let output_str = String::from_utf8(output)?;

            let session_id = output_str
                .lines()
                .find(|line| line.contains("modelpack-usermanaged"))
                .and_then(|line| line.split_whitespace().next())
                .map(|s| s.to_string());

            if let Some(sid) = session_id {
                // Create a test file to upload
                let test_file = "test_checkpoint_cli.txt";
                let mut file = File::create(test_file)?;
                writeln!(file, "Checkpoint from CLI test")?;

                let mut cmd = edgefirst_cmd();
                cmd.arg("upload-artifact")
                    .arg(&sid)
                    .arg(test_file)
                    .arg("--name")
                    .arg("checkpoint_cli.txt");

                cmd.assert().success();
                println!("Uploaded artifact checkpoint_cli.txt to session {}", sid);

                // Clean up
                fs::remove_file(test_file)?;
            }
        }
    }

    Ok(())
}

// ===== Task Tests =====

#[test]
fn test_tasks_list() -> Result<(), Box<dyn std::error::Error>> {
    let mut cmd = edgefirst_cmd();
    cmd.arg("tasks");
    cmd.assert().success();
    Ok(())
}

#[test]
fn test_tasks_with_name_filter() -> Result<(), Box<dyn std::error::Error>> {
    let mut cmd = edgefirst_cmd();
    cmd.arg("tasks").arg("--name").arg("modelpack-usermanaged");

    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    println!("Tasks with name filter:\n{}", output_str);
    Ok(())
}

#[test]
fn test_tasks_with_stages() -> Result<(), Box<dyn std::error::Error>> {
    let mut cmd = edgefirst_cmd();
    cmd.arg("tasks")
        .arg("--name")
        .arg("modelpack-usermanaged")
        .arg("--stages");

    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    println!("Tasks with stages:\n{}", output_str);
    Ok(())
}

#[test]
fn test_task_by_id() -> Result<(), Box<dyn std::error::Error>> {
    let mut cmd = edgefirst_cmd();
    cmd.arg("tasks").arg("--name").arg("modelpack-usermanaged");

    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    // Extract task ID from first line (format: "task-XXXX [...]  name => status")
    let task_id = output_str
        .lines()
        .next()
        .and_then(|line| line.split_whitespace().next())
        .map(|s| s.trim().to_string());

    if let Some(id) = task_id {
        let mut cmd = edgefirst_cmd();
        cmd.arg("task").arg(&id);
        cmd.assert().success();
        println!("Retrieved task details for ID: {}", id);
    }

    Ok(())
}

// ===== Validation Session Tests =====

#[test]
fn test_validation_sessions_list() -> Result<(), Box<dyn std::error::Error>> {
    // First get the "Unit Testing" project ID
    let mut cmd = edgefirst_cmd();
    cmd.arg("projects").arg("--name").arg("Unit Testing");

    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    // Extract project ID from first line (format: "[p-XXXX] name: description")
    let project_id = output_str
        .lines()
        .next()
        .and_then(|line| {
            line.split(']')
                .next()
                .and_then(|s| s.strip_prefix('['))
                .map(|s| s.trim().to_string())
        })
        .expect("Could not find Unit Testing project");

    println!("Found project ID: {}", project_id);

    // Now list validation sessions for this project
    let mut cmd = edgefirst_cmd();
    cmd.arg("validation-sessions").arg(&project_id);

    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    println!("Validation sessions:\n{}", output_str);

    // Should contain at least the "modelpack-usermanaged" session
    assert!(output_str.contains("modelpack-usermanaged"));

    Ok(())
}

#[test]
fn test_validation_session_details() -> Result<(), Box<dyn std::error::Error>> {
    // First get the "Unit Testing" project ID
    let mut cmd = edgefirst_cmd();
    cmd.arg("projects").arg("--name").arg("Unit Testing");

    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    let project_id = output_str
        .lines()
        .next()
        .and_then(|line| {
            line.split(']')
                .next()
                .and_then(|s| s.strip_prefix('['))
                .map(|s| s.trim().to_string())
        })
        .expect("Could not find Unit Testing project");

    // Get validation sessions
    let mut cmd = edgefirst_cmd();
    cmd.arg("validation-sessions").arg(&project_id);

    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    // Extract validation session ID from first line (format: "[v-XXXX] name:
    // description")
    let session_id = output_str.lines().next().and_then(|line| {
        line.split(']')
            .next()
            .and_then(|s| s.strip_prefix('['))
            .map(|s| s.trim().to_string())
    });

    if let Some(id) = session_id {
        println!("Found validation session ID: {}", id);

        // Get validation session details
        let mut cmd = edgefirst_cmd();
        cmd.arg("validation-session").arg(&id);

        let output = cmd.ok()?.stdout;
        let output_str = String::from_utf8(output)?;

        println!("Validation session details:\n{}", output_str);

        // Should contain the session ID
        assert!(output_str.contains(&id));
    }

    Ok(())
}

// ============================================================================
// Upload Dataset Tests
// ============================================================================

/// Helper function to get "Test Labels" dataset for write operations
fn get_test_labels_dataset() -> Result<(String, String), Box<dyn std::error::Error>> {
    // Get Unit Testing project
    let mut cmd = edgefirst_cmd();
    cmd.arg("projects").arg("--name").arg("Unit Testing");
    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;
    let project_id = output_str
        .lines()
        .next()
        .and_then(|line| {
            line.split(']')
                .next()
                .and_then(|s| s.strip_prefix('['))
                .map(|s| s.trim().to_string())
        })
        .expect("Could not find Unit Testing project");

    // Get datasets and find "Test Labels" dataset
    let mut cmd = edgefirst_cmd();
    cmd.arg("datasets").arg(&project_id);
    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    // Find the Test Labels dataset
    let test_labels_dataset = output_str
        .lines()
        .find(|line| line.contains("Test Labels"))
        .and_then(|line| {
            line.split(']')
                .next()
                .and_then(|s| s.strip_prefix('['))
                .map(|s| s.trim().to_string())
        })
        .expect("Could not find Test Labels dataset");

    println!("Found Test Labels dataset: {}", test_labels_dataset);

    // Get annotation sets for the dataset
    let mut cmd = edgefirst_cmd();
    cmd.arg("dataset")
        .arg(&test_labels_dataset)
        .arg("--annotation-sets");
    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    println!("Annotation sets output:\n{}", output_str);

    // Extract first annotation set ID (format: "[as-XXXX] name")
    // Skip the dataset info line and find annotation set lines
    let annotation_set_id = output_str
        .lines()
        .skip_while(|line| !line.contains("Annotation Sets:"))
        .skip(1) // Skip the "Annotation Sets:" header
        .find(|line| line.trim().starts_with('[') && line.contains("as-"))
        .and_then(|line| {
            line.split(']')
                .next()
                .and_then(|s| s.strip_prefix('['))
                .map(|s| s.trim().to_string())
        })
        .expect("Could not find annotation set for Test Labels dataset");

    println!("Found annotation set: {}", annotation_set_id);

    Ok((test_labels_dataset, annotation_set_id))
}

#[test]
#[file_serial]
fn test_upload_dataset_full_mode() -> Result<(), Box<dyn std::error::Error>> {
    // Get Test Labels dataset for write operations
    let (dataset_id, annotation_set_id) = get_test_labels_dataset()?;

    // Get test data paths
    let dataset = get_test_dataset();
    let test_data_dir = get_test_dataset_path();
    let dataset_lower = dataset.to_lowercase().replace("ds-", "dataset-");
    let annotations_path = test_data_dir.join(format!("{}-stage.arrow", dataset_lower));
    let images_path = test_data_dir.join(&dataset_lower);

    // Verify test data exists
    if !annotations_path.exists() {
        eprintln!("⚠️  Test data not found: {}", annotations_path.display());
        eprintln!("    Skipping test - run download tests first to populate test data");
        return Ok(());
    }

    // Run upload-dataset with all parameters (full mode)
    let mut cmd = edgefirst_cmd();
    cmd.arg("upload-dataset")
        .arg(&dataset_id)
        .arg("--annotations")
        .arg(&annotations_path)
        .arg("--annotation-set-id")
        .arg(&annotation_set_id)
        .arg("--images")
        .arg(&images_path);

    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    println!("Upload output:\n{}", output_str);

    // Verify success message or samples message
    assert!(
        output_str.contains("Successfully uploaded") || output_str.contains("samples"),
        "Expected success or samples message"
    );

    Ok(())
}

#[test]
#[file_serial]
fn test_upload_dataset_auto_discovery() -> Result<(), Box<dyn std::error::Error>> {
    // Get Test Labels dataset
    let (dataset_id, annotation_set_id) = get_test_labels_dataset()?;

    // Get test data paths
    let dataset = get_test_dataset();
    let test_data_dir = get_test_dataset_path();
    let dataset_lower = dataset.to_lowercase().replace("ds-", "dataset-");
    let annotations_path = test_data_dir.join(format!("{}-stage.arrow", dataset_lower));

    // Verify test data exists
    if !annotations_path.exists() {
        eprintln!("⚠️  Test data not found");
        eprintln!("    Skipping test - run download tests first to populate test data");
        return Ok(());
    }

    // Test auto-discovery: For {dataset}-stage.arrow, try to find folder/zip
    // Since we have {dataset}/ (not {dataset}-stage/), auto-discovery should fail
    // gracefully Run upload-dataset WITHOUT --images parameter
    let mut cmd = edgefirst_cmd();
    cmd.arg("upload-dataset")
        .arg(&dataset_id)
        .arg("--annotations")
        .arg(&annotations_path)
        .arg("--annotation-set-id")
        .arg(&annotation_set_id);

    let result = cmd.output()?;
    let stderr_str = String::from_utf8(result.stderr)?;

    println!("Upload stderr:\n{}", stderr_str);

    // Should fail with message about not finding images (deer-stage/ doesn't exist)
    assert!(
        !result.status.success(),
        "Auto-discovery should fail when deer-stage/ folder doesn't exist"
    );
    assert!(
        stderr_str.contains("Could not find images"),
        "Expected error about missing images directory"
    );

    Ok(())
}

#[test]
#[file_serial]
fn test_upload_dataset_images_only() -> Result<(), Box<dyn std::error::Error>> {
    // Get Test Labels dataset
    let (dataset_id, _annotation_set_id) = get_test_labels_dataset()?;

    // Get test data paths
    let dataset = get_test_dataset();
    let test_data_dir = get_test_dataset_path();
    let dataset_lower = dataset.to_lowercase().replace("ds-", "dataset-");
    let images_path = test_data_dir.join(&dataset_lower);

    // Verify test data exists
    if !images_path.exists() {
        eprintln!("⚠️  Test data not found: {}", images_path.display());
        eprintln!("    Skipping test - run download tests first to populate test data");
        return Ok(());
    }

    // Run upload-dataset in images-only mode (no annotations)
    let mut cmd = edgefirst_cmd();
    cmd.arg("upload-dataset")
        .arg(&dataset_id)
        .arg("--images")
        .arg(&images_path);

    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    println!("Upload output:\n{}", output_str);

    // Verify success message or samples message
    assert!(
        output_str.contains("Successfully uploaded") || output_str.contains("samples"),
        "Expected success or samples message"
    );

    Ok(())
}

#[test]
#[file_serial]
fn test_upload_dataset_warning_no_annotation_set_id() -> Result<(), Box<dyn std::error::Error>> {
    // Get Test Labels dataset
    let (dataset_id, _annotation_set_id) = get_test_labels_dataset()?;

    // Get test data paths
    let dataset = get_test_dataset();
    let test_data_dir = get_test_dataset_path();
    let dataset_lower = dataset.to_lowercase().replace("ds-", "dataset-");
    let annotations_path = test_data_dir.join(format!("{}-stage.arrow", dataset_lower));
    let images_path = test_data_dir.join(&dataset_lower);

    // Verify test data exists
    if !annotations_path.exists() {
        eprintln!("⚠️  Test data not found: {}", annotations_path.display());
        eprintln!("    Skipping test - run download tests first to populate test data");
        return Ok(());
    }

    // Run upload-dataset with annotations but NO annotation_set_id (should warn)
    let mut cmd = edgefirst_cmd();
    cmd.arg("upload-dataset")
        .arg(&dataset_id)
        .arg("--annotations")
        .arg(&annotations_path)
        .arg("--images")
        .arg(&images_path);

    let result = cmd.output()?;
    let stdout_str = String::from_utf8(result.stdout)?;
    let stderr_str = String::from_utf8(result.stderr)?;

    println!("Upload stdout:\n{}", stdout_str);
    println!("Upload stderr:\n{}", stderr_str);

    // Verify warning message is present in stderr
    assert!(
        stderr_str.contains("⚠️") || stderr_str.contains("Warning"),
        "Expected warning message about missing annotation_set_id in stderr"
    );
    assert!(
        stderr_str.contains("annotation-set-id"),
        "Expected warning to mention annotation-set-id parameter"
    );

    // Should still succeed (uploading images only)
    assert!(
        result.status.success(),
        "Command should succeed when uploading images only"
    );
    assert!(
        stdout_str.contains("Successfully uploaded") || stdout_str.contains("samples"),
        "Expected success or samples message for images"
    );

    Ok(())
}

#[test]
#[file_serial]
fn test_upload_dataset_batching() -> Result<(), Box<dyn std::error::Error>> {
    // Get Test Labels dataset
    let (dataset_id, annotation_set_id) = get_test_labels_dataset()?;

    // Get test data paths (test dataset may have many images, which will trigger
    // batching)
    let dataset = get_test_dataset();
    let test_data_dir = get_test_dataset_path();
    let dataset_lower = dataset.to_lowercase().replace("ds-", "dataset-");
    let annotations_path = test_data_dir.join(format!("{}-stage.arrow", dataset_lower));
    let images_path = test_data_dir.join(&dataset_lower);

    // Verify test data exists
    if !annotations_path.exists() {
        eprintln!("⚠️  Test data not found: {}", annotations_path.display());
        eprintln!("    Skipping test - run download tests first to populate test data");
        return Ok(());
    }

    // Run upload-dataset with full dataset (should trigger batching at 500 samples)
    let mut cmd = edgefirst_cmd();
    cmd.arg("upload-dataset")
        .arg(&dataset_id)
        .arg("--annotations")
        .arg(&annotations_path)
        .arg("--annotation-set-id")
        .arg(&annotation_set_id)
        .arg("--images")
        .arg(&images_path);

    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    println!("Upload output:\n{}", output_str);

    // With 1646 samples, should see batching messages if uploading new data
    // Expected: "Uploading batch 1/4", "Uploading batch 2/4", etc.
    // Note: May not see batching if samples already exist

    // Verify success
    assert!(
        output_str.contains("Successfully uploaded") || output_str.contains("samples"),
        "Expected success or samples message"
    );

    Ok(())
}

#[test]
#[file_serial]
fn test_upload_dataset_missing_parameters() -> Result<(), Box<dyn std::error::Error>> {
    // Get Test Labels dataset
    let (dataset_id, _annotation_set_id) = get_test_labels_dataset()?;

    // Try to run upload-dataset with NEITHER annotations NOR images (should fail)
    let mut cmd = edgefirst_cmd();
    cmd.arg("upload-dataset").arg(&dataset_id);

    let result = cmd.output()?;
    let output_str = String::from_utf8(result.stderr)?;

    println!("Error output:\n{}", output_str);

    // Should fail with error about missing parameters
    assert!(
        !result.status.success(),
        "Command should fail when both annotations and images are missing"
    );
    assert!(
        output_str.contains("annotations")
            || output_str.contains("images")
            || output_str.contains("Must provide"),
        "Error message should mention missing parameters"
    );

    Ok(())
}

#[test]
#[file_serial]
fn test_upload_dataset_invalid_path() -> Result<(), Box<dyn std::error::Error>> {
    // Get Test Labels dataset
    let (dataset_id, _annotation_set_id) = get_test_labels_dataset()?;

    // Try to upload with non-existent path
    let mut cmd = edgefirst_cmd();
    cmd.arg("upload-dataset")
        .arg(&dataset_id)
        .arg("--images")
        .arg("/nonexistent/path/to/images");

    let result = cmd.output()?;

    // Should fail
    assert!(
        !result.status.success(),
        "Command should fail with invalid path"
    );

    Ok(())
}

// ===== Dataset Management Tests =====

#[test]
#[file_serial]
fn test_dataset_crud() -> Result<(), Box<dyn std::error::Error>> {
    // Get Unit Testing project
    let mut cmd = edgefirst_cmd();
    cmd.arg("projects").arg("--name").arg("Unit Testing");
    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;
    let project_id = output_str
        .lines()
        .next()
        .and_then(|line| {
            line.split(']')
                .next()
                .and_then(|s| s.strip_prefix('['))
                .map(|s| s.trim().to_string())
        })
        .expect("Could not find Unit Testing project");

    // 1. Create a test dataset
    let dataset_name = format!("CLI CRUD Test {}", chrono::Utc::now().timestamp());
    let mut cmd = edgefirst_cmd();
    cmd.arg("create-dataset")
        .arg(&project_id)
        .arg(&dataset_name)
        .arg("--description")
        .arg("Dataset for CLI CRUD test");

    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    // Verify dataset was created
    assert!(output_str.contains("Created dataset with ID:"));
    assert!(output_str.contains("ds-"));

    // Extract dataset ID
    let dataset_id = output_str
        .trim()
        .strip_prefix("Created dataset with ID: ")
        .expect("Could not extract dataset ID");

    println!(
        "✓ Step 1: Created dataset {} ({})",
        dataset_name, dataset_id
    );

    // 2. Create an annotation set for the dataset
    let annotation_set_name = format!("CLI CRUD AnnotationSet {}", chrono::Utc::now().timestamp());
    let mut cmd = edgefirst_cmd();
    cmd.arg("create-annotation-set")
        .arg(dataset_id)
        .arg(&annotation_set_name)
        .arg("--description")
        .arg("Annotation set for CLI CRUD test");

    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    // Verify annotation set was created
    assert!(output_str.contains("Created annotation set with ID:"));
    assert!(output_str.contains("as-"));

    // Extract annotation set ID
    let annotation_set_id = output_str
        .trim()
        .strip_prefix("Created annotation set with ID: ")
        .expect("Could not extract annotation set ID");

    println!(
        "✓ Step 2: Created annotation set {} ({})",
        annotation_set_name, annotation_set_id
    );

    // 3. (Skipped for now) Upload dataset with samples
    println!("✓ Step 3: Skipped - Upload samples (future enhancement)");

    // 4. Delete the annotation set
    let mut cmd = edgefirst_cmd();
    cmd.arg("delete-annotation-set").arg(annotation_set_id);

    let result = cmd.output()?;

    // Note: Server may not support annset.delete yet, so we tolerate failure
    if result.status.success() {
        let output_str = String::from_utf8(result.stdout)?;
        assert!(output_str.contains("marked as deleted"));
        assert!(output_str.contains(annotation_set_id));
        println!("✓ Step 4: Deleted annotation set {}", annotation_set_id);
    } else {
        let stderr = String::from_utf8(result.stderr)?;
        println!(
            "✓ Step 4: Annotation set deletion not supported by server (expected): {}",
            stderr.lines().next().unwrap_or("")
        );
    }

    // 5. Delete the dataset (this will also delete associated annotation sets)
    let mut cmd = edgefirst_cmd();
    cmd.arg("delete-dataset").arg(dataset_id);

    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    // Verify dataset deletion message
    assert!(output_str.contains("marked as deleted"));
    assert!(output_str.contains(dataset_id));

    println!("✓ Step 5: Deleted dataset {}", dataset_id);
    println!("✅ Dataset CRUD workflow completed successfully");

    Ok(())
}

#[test]
#[file_serial]
fn test_download_dataset_flatten() -> Result<(), Box<dyn std::error::Error>> {
    // Test the --flatten option to download sequences without subdirectories
    let dataset = get_test_dataset();
    let (dataset_id, _) = get_dataset_and_first_annotation_set(&dataset)?;

    let downloads_root = get_test_data_dir().join("downloads");
    fs::create_dir_all(&downloads_root)?;

    let timestamp = SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis();

    // Download with normal structure (sequences in subdirectories)
    let normal_dir = downloads_root.join(format!("normal_{}_{}", std::process::id(), timestamp));
    fs::create_dir_all(&normal_dir)?;

    println!("Downloading dataset with normal structure...");
    let mut cmd = edgefirst_cmd();
    cmd.arg("download-dataset")
        .arg(&dataset_id)
        .arg("--output")
        .arg(&normal_dir);
    cmd.assert().success();

    // Download with flattened structure
    let flatten_dir = downloads_root.join(format!("flatten_{}_{}", std::process::id(), timestamp));
    fs::create_dir_all(&flatten_dir)?;

    println!("Downloading dataset with --flatten option...");
    let mut cmd = edgefirst_cmd();
    cmd.arg("download-dataset")
        .arg(&dataset_id)
        .arg("--output")
        .arg(&flatten_dir)
        .arg("--flatten");
    cmd.assert().success();

    // Verify normal structure has subdirectories for sequences
    let normal_entries: Vec<_> = fs::read_dir(&normal_dir)?.filter_map(|e| e.ok()).collect();

    println!("Normal download structure:");
    let has_subdirs = normal_entries.iter().any(|e| e.path().is_dir());
    for entry in &normal_entries {
        let path = entry.path();
        let entry_type = if path.is_dir() { "DIR " } else { "FILE" };
        println!(
            "  {} {}",
            entry_type,
            path.file_name().unwrap().to_string_lossy()
        );
    }

    // Verify flattened structure has no subdirectories (all files in root)
    let flatten_entries: Vec<_> = fs::read_dir(&flatten_dir)?
        .filter_map(|e| e.ok())
        .filter(|e| !e.file_name().to_string_lossy().starts_with('.'))
        .collect();

    println!("\nFlattened download structure:");
    let flatten_has_subdirs = flatten_entries.iter().any(|e| e.path().is_dir());
    for entry in &flatten_entries {
        let path = entry.path();
        let entry_type = if path.is_dir() { "DIR " } else { "FILE" };
        println!(
            "  {} {}",
            entry_type,
            path.file_name().unwrap().to_string_lossy()
        );
    }

    // Assert flatten has no subdirectories
    assert!(
        !flatten_has_subdirs,
        "Flattened download should not have subdirectories"
    );

    // Count total files in both structures
    let count_files = |dir: &Path| -> Result<usize, Box<dyn std::error::Error>> {
        let mut count = 0;
        for entry in walkdir::WalkDir::new(dir).min_depth(1).max_depth(10) {
            let entry = entry?;
            if entry.file_type().is_file() {
                count += 1;
            }
        }
        Ok(count)
    };

    let normal_file_count = count_files(&normal_dir)?;
    let flatten_file_count = count_files(&flatten_dir)?;

    println!("\nFile counts:");
    println!("  Normal structure: {} files", normal_file_count);
    println!("  Flattened structure: {} files", flatten_file_count);

    // Both should have the same number of files
    assert_eq!(
        normal_file_count, flatten_file_count,
        "Normal and flattened downloads should have same number of files"
    );

    // If dataset has sequences, verify normal has subdirectories
    if has_subdirs {
        println!("\n✓ Dataset contains sequences - normal download has subdirectories");

        // For flattened structure, verify filenames contain sequence prefixes
        let flatten_files: Vec<String> = flatten_entries
            .iter()
            .filter(|e| e.path().is_file())
            .map(|e| e.file_name().to_string_lossy().to_string())
            .collect();

        // At least some files should have underscore-separated sequence prefixes
        // (format: sequence_name_frame_rest.ext or sequence_name_rest.ext)
        let has_prefixed_files = flatten_files
            .iter()
            .any(|name| name.matches('_').count() >= 1);

        if has_prefixed_files {
            println!("✓ Flattened files contain sequence prefixes");
            println!("  Sample filenames:");
            for filename in flatten_files.iter().take(3) {
                println!("    - {}", filename);
            }
        }
    } else {
        println!("\n✓ Dataset contains no sequences - both structures are flat");
    }

    // Cleanup downloaded directories
    fs::remove_dir_all(&normal_dir).ok();
    fs::remove_dir_all(&flatten_dir).ok();

    println!("\n✅ Flatten option test completed successfully");
    Ok(())
}

// ============================================================================
// SNAPSHOT TESTS
// ============================================================================

#[test]
#[file_serial]
fn test_snapshots_list() -> Result<(), Box<dyn std::error::Error>> {
    let mut cmd = edgefirst_cmd();
    cmd.arg("snapshots");
    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    println!("Snapshots list output:\n{}", output_str);

    // Should have header or at least complete without error
    assert!(
        output_str.contains("ss-") || output_str.is_empty() || output_str.contains("No snapshots"),
        "Expected snapshot list with ss- IDs or empty/no snapshots message"
    );

    Ok(())
}

#[test]
#[file_serial]
fn test_snapshot_get() -> Result<(), Box<dyn std::error::Error>> {
    // First, list snapshots to get a valid ID
    let mut cmd = edgefirst_cmd();
    cmd.arg("snapshots");
    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    // Extract first snapshot ID (format: [ss-XXXX] where XXXX is hexadecimal)
    let snapshot_id = output_str.lines().find_map(|line| {
        line.split(']')
            .next()
            .and_then(|s| s.strip_prefix('['))
            .filter(|id| {
                id.starts_with("ss-")
                    && id.len() > 3
                    && id.chars().skip(3).all(|c| c.is_ascii_hexdigit())
            })
            .map(|s| s.trim().to_string())
    });

    if let Some(id) = snapshot_id {
        println!("Testing with snapshot ID: {}", id);

        // Get snapshot details - allow failure if snapshot was deleted
        let mut cmd = edgefirst_cmd();
        cmd.arg("snapshot").arg(&id);

        match cmd.ok() {
            Ok(result) => {
                let output_str = String::from_utf8(result.stdout)?;
                println!("Snapshot details:\n{}", output_str);

                // Should contain the ID and basic info
                assert!(
                    output_str.contains(&id),
                    "Expected snapshot details to contain ID"
                );
            }
            Err(_) => {
                // Snapshot may have been deleted between list and get - this is acceptable
                println!(
                    "Note: Snapshot {} may have been deleted - skipping verification",
                    id
                );
            }
        }
    } else {
        return Err("No snapshots found - test server should have at least one snapshot".into());
    }

    Ok(())
}

#[test]
#[file_serial]
fn test_snapshot_create_download_delete_workflow() -> Result<(), Box<dyn std::error::Error>> {
    // This test covers create, download, and delete in a single workflow

    // Create a test file to snapshot
    let test_data_dir = get_test_data_dir();
    let test_file = test_data_dir.join("test_snapshot_workflow.txt");
    fs::write(&test_file, b"Test snapshot workflow data")?;

    println!("=== STEP 1: Create Snapshot ===");
    // Create snapshot (no dataset ID needed - snapshots are project-agnostic)
    let mut cmd = edgefirst_cmd();
    cmd.arg("create-snapshot").arg(&test_file);
    let create_output = cmd.ok()?.stdout;
    let create_output_str = String::from_utf8(create_output)?;

    println!("Create snapshot output:\n{}", create_output_str);

    // Extract snapshot ID from creation output (format: [ss-XXX] name)
    let snapshot_id = create_output_str
        .lines()
        .find_map(|line| {
            // Look for pattern like "[ss-e0e]"
            if let Some(start) = line.find('[')
                && let Some(end) = line[start..].find(']')
            {
                let id_with_brackets = &line[start..start + end + 1];
                let id = id_with_brackets
                    .trim_start_matches('[')
                    .trim_end_matches(']');
                if id.starts_with("ss-") {
                    return Some(id.to_string());
                }
            }
            None
        })
        .expect("Could not extract snapshot ID from creation output");

    println!("✓ Created snapshot: {}", snapshot_id);

    println!("\n=== STEP 2: Wait for Snapshot Processing ===");
    // Wait for snapshot to be completed (snapshots need processing time)
    // Use the API directly to check status
    use edgefirst_client::{Client as EdgFirstClient, SnapshotID};
    let api_client = EdgFirstClient::new()?.with_token_path(None)?;
    let snap_id = SnapshotID::try_from(snapshot_id.as_str())?;

    let rt = tokio::runtime::Runtime::new()?;
    let mut attempts = 0;
    let max_attempts = 30; // 30 seconds max wait
    loop {
        let snapshot = rt.block_on(api_client.snapshot(snap_id))?;
        let status = snapshot.status();

        // Snapshot is ready when status is "available" or "completed"
        if status == "available" || status == "completed" {
            println!("✓ Snapshot ready (status: {})", status);
            break;
        }

        attempts += 1;
        if attempts >= max_attempts {
            panic!(
                "Snapshot did not become available within {} seconds. Last status: {}",
                max_attempts, status
            );
        }

        std::thread::sleep(std::time::Duration::from_secs(1));
    }

    println!("\n=== STEP 3: Download Snapshot ===");
    // Create download directory
    let downloads_root = get_test_data_dir().join("downloads");
    let timestamp = SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis();
    let download_dir =
        downloads_root.join(format!("snapshot_{}_{}", std::process::id(), timestamp));
    fs::create_dir_all(&download_dir)?;

    // Download snapshot (signature: snapshot_id --output path)
    let mut cmd = edgefirst_cmd();
    cmd.arg("download-snapshot")
        .arg(&snapshot_id)
        .arg("--output")
        .arg(&download_dir);
    let download_output = cmd.ok()?.stdout;
    let download_output_str = String::from_utf8(download_output)?;

    println!("Download snapshot output:\n{}", download_output_str);

    // Verify download directory has content
    let entries: Vec<_> = fs::read_dir(&download_dir)?
        .filter_map(|e| e.ok())
        .collect();

    assert!(
        !entries.is_empty(),
        "Expected downloaded snapshot to contain files"
    );

    println!("✓ Downloaded {} items", entries.len());

    println!("\n=== STEP 4: Delete Snapshot ===");
    // Delete the snapshot
    let mut cmd = edgefirst_cmd();
    cmd.arg("delete-snapshot").arg(&snapshot_id);
    let delete_output = cmd.ok()?.stdout;
    let delete_output_str = String::from_utf8(delete_output)?;

    println!("Delete snapshot output:\n{}", delete_output_str);

    println!("✓ Deleted snapshot: {}", snapshot_id);

    // Clean up test file and download directory
    let _ = fs::remove_file(&test_file);
    let _ = fs::remove_dir_all(&download_dir);

    println!("\n✅ Snapshot workflow test completed successfully");
    Ok(())
}

/// Compute SHA256 checksum of a file
#[allow(dead_code)]
fn compute_file_checksum(path: &Path) -> Result<String, Box<dyn std::error::Error>> {
    use sha2::{Digest, Sha256};
    use std::io::Read;

    let mut file = fs::File::open(path)?;
    let mut hasher = Sha256::new();
    let mut buffer = [0u8; 8192];

    loop {
        let bytes_read = file.read(&mut buffer)?;
        if bytes_read == 0 {
            break;
        }
        hasher.update(&buffer[..bytes_read]);
    }

    Ok(format!("{:x}", hasher.finalize()))
}

#[test]
#[file_serial]
#[ignore = "Backend S3 path format bug: restore uploading stage generates 's3:' instead of 's3://' causing 'Invalid S3 path format' error. See task.get response for task-40ae."]
fn test_snapshot_restore() -> Result<(), Box<dyn std::error::Error>> {
    // =========================================================================
    // SNAPSHOT RESTORE TEST
    //
    // Tests that restoring a snapshot produces a dataset identical to the
    // snapshot's contents. Validates group information is preserved.
    //
    // Flow (leveraging server-side async processing):
    // 1. Start restore (returns task ID for async monitoring)
    // 2. Download snapshot locally (while restore runs on server)
    // 3. Use task --monitor to wait for restore completion
    // 4. Download restored dataset and compare with snapshot
    // =========================================================================

    println!("╔════════════════════════════════════════════════════════════════╗");
    println!("║  SNAPSHOT RESTORE TEST                                         ║");
    println!("╚════════════════════════════════════════════════════════════════╝");

    // =========================================================================
    // STEP 1: Find the snapshot and project
    // =========================================================================
    println!("\n┌─────────────────────────────────────────────────────────────────┐");
    println!("│ STEP 1: Find Snapshot and Project                               │");
    println!("└─────────────────────────────────────────────────────────────────┘");

    // Find Unit Testing project
    let mut cmd = edgefirst_cmd();
    cmd.arg("projects").arg("--name").arg("Unit Testing");
    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    let project_id = output_str
        .lines()
        .find_map(|line| {
            let id_part = line.split(']').next()?;
            let id = id_part.strip_prefix('[')?.trim();
            if id.starts_with("p-") {
                Some(id.to_string())
            } else {
                None
            }
        })
        .expect("Could not find Unit Testing project");
    println!("✓ Project: {}", project_id);

    // List all snapshots and find "Unit Testing - Deer Dataset"
    let mut cmd = edgefirst_cmd();
    cmd.arg("snapshots");
    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    // Parse snapshots - format: [ss-xxx] Description (status)
    let snapshot_id = output_str
        .lines()
        .find_map(|line| {
            if line.contains("Unit Testing - Deer Dataset") {
                let id_part = line.split(']').next()?;
                let id = id_part.strip_prefix('[')?.trim();
                if id.starts_with("ss-") {
                    return Some(id.to_string());
                }
            }
            None
        })
        .expect("Could not find 'Unit Testing - Deer Dataset' snapshot");
    println!("✓ Snapshot: {}", snapshot_id);

    // =========================================================================
    // STEP 2: Start restore (returns task ID for async monitoring)
    // =========================================================================
    println!("\n┌─────────────────────────────────────────────────────────────────┐");
    println!("│ STEP 2: Start Restore (async - returns task ID)                 │");
    println!("└─────────────────────────────────────────────────────────────────┘");

    let mut restore_cmd = edgefirst_cmd();
    restore_cmd
        .arg("restore-snapshot")
        .arg(&project_id)
        .arg(&snapshot_id);
    restore_cmd.timeout(std::time::Duration::from_secs(60));

    let restore_output = restore_cmd.ok()?.stdout;
    let restore_output_str = String::from_utf8(restore_output)?;
    println!("Restore output:\n{}", restore_output_str);

    // Extract dataset ID from restore output
    let restored_dataset_id = restore_output_str
        .lines()
        .find_map(|line| {
            if let Some(start) = line.find("[ds-") {
                let rest = &line[start + 1..];
                if let Some(end) = rest.find(']') {
                    return Some(rest[..end].to_string());
                }
            }
            None
        })
        .expect("Could not extract dataset ID from restore output");
    println!("✓ Restored dataset: {}", restored_dataset_id);

    // Extract task ID from restore output (format: "Task: [task-xxx]")
    let task_id = restore_output_str.lines().find_map(|line| {
        if let Some(start) = line.find("[task-") {
            let rest = &line[start + 1..];
            if let Some(end) = rest.find(']') {
                return Some(rest[..end].to_string());
            }
        }
        None
    });

    if let Some(ref tid) = task_id {
        println!("✓ Task ID: {}", tid);
    } else {
        println!("⚠️  No task ID returned - restore may be synchronous");
    }

    // =========================================================================
    // STEP 3: Download snapshot locally (while restore runs on server)
    // =========================================================================
    println!("\n┌─────────────────────────────────────────────────────────────────┐");
    println!("│ STEP 3: Download Snapshot Locally                               │");
    println!("└─────────────────────────────────────────────────────────────────┘");

    // Setup download directory
    let test_root = get_test_data_dir().join("snapshot_restore_test");
    let timestamp = SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis();
    let test_dir = test_root.join(format!("test_{}_{}", std::process::id(), timestamp));
    let snapshot_download_dir = test_dir.join("snapshot");
    fs::create_dir_all(&snapshot_download_dir)?;

    println!(
        "Downloading snapshot to {}...",
        snapshot_download_dir.display()
    );
    let mut download_cmd = edgefirst_cmd();
    download_cmd
        .arg("download-snapshot")
        .arg(&snapshot_id)
        .arg("--output")
        .arg(&snapshot_download_dir);
    download_cmd.timeout(std::time::Duration::from_secs(300));
    download_cmd.ok()?;

    // Find downloaded files (always dataset.arrow and dataset.zip)
    let snapshot_arrow = snapshot_download_dir.join("dataset.arrow");
    let snapshot_zip = snapshot_download_dir.join("dataset.zip");

    assert!(
        snapshot_arrow.exists(),
        "Expected dataset.arrow in snapshot download"
    );
    println!(
        "✓ Downloaded snapshot arrow: {} ({} bytes)",
        snapshot_arrow.display(),
        fs::metadata(&snapshot_arrow)?.len()
    );
    if snapshot_zip.exists() {
        println!(
            "✓ Downloaded snapshot zip: {} ({} bytes)",
            snapshot_zip.display(),
            fs::metadata(&snapshot_zip)?.len()
        );
    }

    // =========================================================================
    // STEP 4: Wait for restore to complete using task --monitor
    // =========================================================================
    println!("\n┌─────────────────────────────────────────────────────────────────┐");
    println!("│ STEP 4: Wait for Restore to Complete                            │");
    println!("└─────────────────────────────────────────────────────────────────┘");

    if let Some(tid) = task_id {
        println!("Monitoring task {} for completion...", tid);
        let mut task_cmd = edgefirst_cmd();
        task_cmd.arg("task").arg(&tid).arg("--monitor");
        task_cmd.timeout(std::time::Duration::from_secs(600));
        task_cmd.ok()?;
        println!("✓ Restore task completed");
    } else {
        // No task ID - wait a bit for synchronous restore to settle
        println!("No task ID - waiting 5 seconds for restore to settle...");
        std::thread::sleep(std::time::Duration::from_secs(5));
    }

    // =========================================================================
    // STEP 5: Get Restored Dataset's Annotation Set
    // =========================================================================
    println!("\n┌─────────────────────────────────────────────────────────────────┐");
    println!("│ STEP 5: Get Restored Dataset Annotation Set                     │");
    println!("└─────────────────────────────────────────────────────────────────┘");

    // Get annotation set from restored dataset
    let mut cmd = edgefirst_cmd();
    cmd.arg("dataset")
        .arg(&restored_dataset_id)
        .arg("--annotation-sets");
    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    let restored_annotation_set_id = output_str
        .lines()
        .skip_while(|line| !line.contains("Annotation Sets:"))
        .skip(1)
        .find_map(|line| {
            line.split(']')
                .next()
                .and_then(|s| s.strip_prefix('['))
                .map(|s| s.trim().to_string())
                .filter(|id| id.starts_with("as-"))
        })
        .expect("No annotation set found in restored dataset");
    println!("✓ Restored annotation set: {}", restored_annotation_set_id);

    // =========================================================================
    // STEP 6: Validate Snapshot Arrow Baseline
    // =========================================================================
    println!("\n┌─────────────────────────────────────────────────────────────────┐");
    println!("│ STEP 6: Validate Snapshot Arrow Baseline                        │");
    println!("└─────────────────────────────────────────────────────────────────┘");

    // Extract image→group mapping from snapshot arrow as the source of truth
    // An IMAGE is uniquely identified by (name, frame) - name is sequence, frame is
    // frame number CRITICAL: All rows must have group values (no nulls allowed
    // in baseline)
    #[cfg(feature = "polars")]
    let snap_image_groups: HashMap<(String, Option<i32>), String> = {
        use polars::prelude::*;

        let mut snap_file = fs::File::open(&snapshot_arrow)?;
        let snap_df = IpcReader::new(&mut snap_file).finish()?;

        println!(
            "Snapshot arrow: {} rows, {} columns",
            snap_df.height(),
            snap_df.width()
        );
        println!("Snapshot columns: {:?}", snap_df.get_column_names());

        // Check group column exists
        let snap_groups = snap_df
            .column("group")
            .expect("Snapshot arrow missing 'group' column!");
        let snap_name_col = snap_df.column("name")?;
        let snap_frame_col = snap_df.column("frame")?;

        // BASELINE VALIDATION: No nulls allowed in snapshot group column
        let snap_null_count = snap_groups.null_count();
        assert_eq!(
            snap_null_count, 0,
            "SNAPSHOT BASELINE INVALID: {} rows have null group values! All rows must have group.",
            snap_null_count
        );
        println!(
            "✓ Snapshot baseline valid: all {} rows have group values",
            snap_df.height()
        );

        // Build (name, frame)→group mapping
        // All rows for same (name, frame) should have consistent group
        let snap_groups_cast = snap_groups.cast(&DataType::String)?;
        let snap_groups_str = snap_groups_cast.str()?;
        let snap_names_cast = snap_name_col.cast(&DataType::String)?;
        let snap_names = snap_names_cast.str()?;
        let snap_frames = snap_frame_col.i32()?;

        let mut image_groups: HashMap<(String, Option<i32>), String> = HashMap::new();
        let mut inconsistent_groups: Vec<(String, Option<i32>, String, String)> = Vec::new();

        for idx in 0..snap_df.height() {
            if let (Some(name), Some(group)) = (snap_names.get(idx), snap_groups_str.get(idx)) {
                let name = name.to_string();
                let frame = snap_frames.get(idx);
                let group = group.to_string();
                let key = (name.clone(), frame);

                if let Some(existing) = image_groups.get(&key) {
                    if existing != &group {
                        inconsistent_groups.push((name, frame, existing.clone(), group));
                    }
                } else {
                    image_groups.insert(key, group);
                }
            }
        }

        assert!(
            inconsistent_groups.is_empty(),
            "SNAPSHOT BASELINE INVALID: {} images have inconsistent groups!\nFirst few: {:?}",
            inconsistent_groups.len(),
            inconsistent_groups.iter().take(5).collect::<Vec<_>>()
        );

        // Count unique sequences and images
        let unique_sequences: std::collections::HashSet<_> =
            image_groups.keys().map(|(n, _)| n.clone()).collect();
        println!(
            "✓ Snapshot baseline valid: {} unique images across {} sequences",
            image_groups.len(),
            unique_sequences.len()
        );

        // Show group distribution
        let mut group_counts: HashMap<&str, usize> = HashMap::new();
        for group in image_groups.values() {
            *group_counts.entry(group.as_str()).or_default() += 1;
        }
        println!("  Group distribution: {:?}", group_counts);

        image_groups
    };

    #[cfg(not(feature = "polars"))]
    let snap_image_groups: HashMap<(String, Option<i32>), String> = {
        panic!("This test requires the 'polars' feature");
    };

    // =========================================================================
    // STEP 7: Get Samples via Library API (bypassing CLI)
    // =========================================================================
    println!("\n┌─────────────────────────────────────────────────────────────────┐");
    println!("│ STEP 7: Fetch Restored Samples via Library API                  │");
    println!("└─────────────────────────────────────────────────────────────────┘");

    use edgefirst_client::{AnnotationSetID, AnnotationType, Client as EdgeFirstClient, DatasetID};

    let api_client = EdgeFirstClient::new()?.with_token_path(None)?;
    let rt = tokio::runtime::Runtime::new()?;

    // Parse dataset and annotation set IDs
    let dataset_id = DatasetID::try_from(restored_dataset_id.as_str())?;
    let annotation_set_id = AnnotationSetID::try_from(restored_annotation_set_id.as_str())?;

    println!("Fetching samples from restored dataset via API...");
    println!("  Dataset: {}", restored_dataset_id);
    println!("  Annotation Set: {}", restored_annotation_set_id);

    // Fetch all samples using the library API directly
    let samples = rt.block_on(api_client.samples(
        dataset_id,
        Some(annotation_set_id),
        &[
            AnnotationType::Box2d,
            AnnotationType::Box3d,
            AnnotationType::Polygon,
        ],
        &[], // All groups
        &[], // No file type filter
        None,
    ))?;

    println!("✓ Fetched {} samples from API", samples.len());

    // Build (sequence_name, frame_number)→group mapping from API response
    // NOTE: sample.name() returns extracted name (e.g., "seq_123" from
    // "seq_123.jpg")       sample.sequence_name() returns the actual sequence
    // name for sequences For the comparison, we use sequence_name +
    // frame_number to match snapshot's (name, frame)
    let mut api_image_groups: HashMap<(String, Option<u32>), Option<String>> = HashMap::new();
    let mut api_inconsistent_groups: Vec<(String, Option<u32>, String, String)> = Vec::new();

    for sample in &samples {
        // Use sequence_name for sequences, fall back to name for standalone images
        let seq_name = sample.sequence_name().cloned().or_else(|| sample.name());
        let Some(seq_name) = seq_name else {
            continue; // Skip samples without any name
        };
        let frame = sample.frame_number();
        let group = sample.group().cloned();
        let key = (seq_name.clone(), frame);

        if let Some(existing) = api_image_groups.get(&key) {
            // Check consistency
            if existing != &group {
                api_inconsistent_groups.push((
                    seq_name,
                    frame,
                    existing.clone().unwrap_or_else(|| "null".to_string()),
                    group.clone().unwrap_or_else(|| "null".to_string()),
                ));
            }
        } else {
            api_image_groups.insert(key, group);
        }
    }

    // Report any inconsistencies in API response
    if !api_inconsistent_groups.is_empty() {
        println!(
            "⚠️  {} images have inconsistent groups in API response:",
            api_inconsistent_groups.len()
        );
        for (name, frame, g1, g2) in api_inconsistent_groups.iter().take(5) {
            println!("    ({}, {:?}) ({} vs {})", name, frame, g1, g2);
        }
    }

    // Count unique sequences
    let unique_sequences: std::collections::HashSet<_> =
        api_image_groups.keys().map(|(n, _)| n.clone()).collect();
    println!(
        "✓ API response has {} unique images across {} sequences",
        api_image_groups.len(),
        unique_sequences.len()
    );

    // Show API group distribution
    let mut api_group_counts: HashMap<String, usize> = HashMap::new();
    for group in api_image_groups.values() {
        let key = group.clone().unwrap_or_else(|| "null".to_string());
        *api_group_counts.entry(key).or_default() += 1;
    }
    println!("  API group distribution: {:?}", api_group_counts);

    // =========================================================================
    // STEP 8: Compare Snapshot Baseline vs API Response
    // =========================================================================
    println!("\n┌─────────────────────────────────────────────────────────────────┐");
    println!("│ STEP 8: Compare Snapshot Baseline vs API Response               │");
    println!("└─────────────────────────────────────────────────────────────────┘");

    // Helper to format image key for display
    fn fmt_img(key: &(String, Option<i32>)) -> String {
        match key.1 {
            Some(f) => format!("({}, frame={})", key.0, f),
            None => format!("({}, frame=None)", key.0),
        }
    }

    let mut lost_groups: Vec<((String, Option<i32>), String)> = Vec::new();
    let mut changed_groups: Vec<((String, Option<i32>), String, String)> = Vec::new();
    let mut missing_images: Vec<((String, Option<i32>), String)> = Vec::new();

    for (img, snap_group) in &snap_image_groups {
        // Convert i32 frame to u32 for API lookup
        let api_key = (img.0.clone(), img.1.map(|f| f as u32));
        if let Some(api_group) = api_image_groups.get(&api_key) {
            match api_group {
                None => lost_groups.push((img.clone(), snap_group.clone())),
                Some(rg) if rg != snap_group => {
                    changed_groups.push((img.clone(), snap_group.clone(), rg.clone()))
                }
                _ => {} // Matches - good!
            }
        } else {
            missing_images.push((img.clone(), snap_group.clone()));
        }
    }

    // Count images in API but not in snapshot
    // NOTE: This indicates a SERVER BUG in snapshot creation - unannotated images
    // should still be included in the Arrow file with their group assignment.
    // The snapshot Arrow should have ALL images, not just annotated ones.
    let snap_keys: std::collections::HashSet<_> = snap_image_groups
        .keys()
        .map(|(n, f)| (n.clone(), f.map(|x| x as u32)))
        .collect();
    let api_only: Vec<_> = api_image_groups
        .keys()
        .filter(|k| !snap_keys.contains(*k))
        .collect();

    if !api_only.is_empty() {
        println!(
            "⚠️  {} images in API but NOT in snapshot (SERVER BUG: unannotated images missing from snapshot Arrow)",
            api_only.len()
        );
        println!("   These images exist in the dataset but were not included in the snapshot.");
        println!(
            "   The server should include ALL images in the Arrow file, even unannotated ones."
        );
    }

    // Report findings
    if !missing_images.is_empty() {
        println!(
            "\n⚠️  {} images from snapshot NOT FOUND in API response:",
            missing_images.len()
        );
        for (img, group) in missing_images.iter().take(5) {
            println!("    {} (was: {})", fmt_img(img), group);
        }
        if missing_images.len() > 5 {
            println!("    ... and {} more", missing_images.len() - 5);
        }
    }

    if !lost_groups.is_empty() {
        println!(
            "\n⚠️  {} images LOST their group (now null) in API:",
            lost_groups.len()
        );
        for (img, group) in lost_groups.iter().take(5) {
            println!("    {} (was: {})", fmt_img(img), group);
        }
        if lost_groups.len() > 5 {
            println!("    ... and {} more", lost_groups.len() - 5);
        }
    }

    if !changed_groups.is_empty() {
        println!(
            "\n⚠️  {} images CHANGED group in API:",
            changed_groups.len()
        );
        for (img, old, new) in changed_groups.iter().take(10) {
            println!("    {} ({} -> {})", fmt_img(img), old, new);
        }
        if changed_groups.len() > 10 {
            println!("    ... and {} more", changed_groups.len() - 10);
        }
    }

    // The critical assertions:

    // 1. All snapshot images should be in API response
    assert!(
        missing_images.is_empty(),
        "MISSING IMAGES: {} images from snapshot not found in API!\nFirst few: {:?}",
        missing_images.len(),
        missing_images.iter().take(3).collect::<Vec<_>>()
    );
    println!(
        "✓ All {} snapshot images found in API response",
        snap_image_groups.len()
    );

    // 2. No images should lose their group
    assert!(
        lost_groups.is_empty(),
        "GROUP DATA LOSS: {} images lost their group in API!\nFirst few: {:?}",
        lost_groups.len(),
        lost_groups.iter().take(3).collect::<Vec<_>>()
    );
    println!("✓ No images lost their group");

    // 3. No images should change their group assignment
    assert!(
        changed_groups.is_empty(),
        "GROUP CHANGED: {} images had their group changed!\nFirst few: {:?}",
        changed_groups.len(),
        changed_groups.iter().take(3).collect::<Vec<_>>()
    );
    println!("✓ No images changed their group");

    // =========================================================================
    // CLEANUP
    // =========================================================================
    println!("\n┌─────────────────────────────────────────────────────────────────┐");
    println!("│ CLEANUP                                                         │");
    println!("└─────────────────────────────────────────────────────────────────┘");

    // Delete restored dataset
    let mut cmd = edgefirst_cmd();
    cmd.arg("delete-dataset").arg(&restored_dataset_id);
    match cmd.output() {
        Ok(output) if output.status.success() => {
            println!("✓ Deleted restored dataset: {}", restored_dataset_id);
        }
        _ => {
            println!(
                "⚠️  Could not delete restored dataset: {}",
                restored_dataset_id
            );
        }
    }

    // Clean up local files
    fs::remove_dir_all(&test_dir).ok();
    println!("✓ Cleaned up test directory");

    println!("\n╔════════════════════════════════════════════════════════════════╗");
    println!("║  ✅ SNAPSHOT RESTORE TEST PASSED                                ║");
    println!("╚════════════════════════════════════════════════════════════════╝");

    Ok(())
}

/// Test that exporting a dataset to a snapshot preserves all data.
///
/// This is the mirror of `test_snapshot_restore` - it tests the inverse
/// operation:
/// 1. Get the Deer dataset and download its annotations (original Arrow)
/// 2. Export the dataset to a snapshot on the server (using export-snapshot)
/// 3. Wait for export to complete
/// 4. Download the created snapshot
/// 5. Compare the original Arrow with the snapshot's Arrow
///
/// Test the create-snapshot command with a server-side dataset.
///
/// This validates that server-side snapshot creation from a dataset produces
/// an Arrow file that matches the dataset's annotations, including groups.
#[test]
#[file_serial]
fn test_create_snapshot_from_dataset() -> Result<(), Box<dyn std::error::Error>> {
    println!("╔════════════════════════════════════════════════════════════════╗");
    println!("║  CREATE SNAPSHOT FROM DATASET TEST                             ║");
    println!("╚════════════════════════════════════════════════════════════════╝");

    // =========================================================================
    // STEP 1: Get the Deer dataset and its annotation set
    // =========================================================================
    println!("\n┌─────────────────────────────────────────────────────────────────┐");
    println!("│ STEP 1: Get Deer Dataset                                        │");
    println!("└─────────────────────────────────────────────────────────────────┘");

    let (dataset_id, annotation_set_id) = get_dataset_and_first_annotation_set("Deer")?;
    println!("✓ Dataset: {}", dataset_id);
    println!("✓ Annotation Set: {}", annotation_set_id);

    // =========================================================================
    // STEP 2: Download annotations from dataset (original Arrow baseline)
    // =========================================================================
    println!("\n┌─────────────────────────────────────────────────────────────────┐");
    println!("│ STEP 2: Download Original Annotations (Baseline)                │");
    println!("└─────────────────────────────────────────────────────────────────┘");

    // Setup test directory
    let test_root = get_test_data_dir().join("snapshot_export_test");
    let timestamp = SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis();
    let test_dir = test_root.join(format!("test_{}_{}", std::process::id(), timestamp));
    fs::create_dir_all(&test_dir)?;

    let original_arrow = test_dir.join("original.arrow");

    let mut cmd = edgefirst_cmd();
    cmd.arg("download-annotations")
        .arg(&annotation_set_id)
        .arg("--types")
        .arg("box2d,mask")
        .arg(&original_arrow);
    cmd.timeout(std::time::Duration::from_secs(120));
    cmd.assert().success();

    println!(
        "✓ Downloaded original annotations: {} ({} bytes)",
        original_arrow.display(),
        fs::metadata(&original_arrow)?.len()
    );

    // =========================================================================
    // STEP 3: Export dataset to snapshot (triggers server-side creation)
    // =========================================================================
    println!("\n┌─────────────────────────────────────────────────────────────────┐");
    println!("│ STEP 3: Create Snapshot from Dataset                            │");
    println!("└─────────────────────────────────────────────────────────────────┘");

    let snapshot_name = format!("QA Export Test {}", timestamp);

    let mut export_cmd = edgefirst_cmd();
    export_cmd
        .arg("create-snapshot")
        .arg(&dataset_id)
        .arg("--description")
        .arg(&snapshot_name);
    export_cmd.timeout(std::time::Duration::from_secs(120));

    let export_output = export_cmd.ok()?.stdout;
    let export_output_str = String::from_utf8(export_output)?;
    println!("Export output:\n{}", export_output_str);

    // Extract snapshot ID from export output
    let snapshot_id = export_output_str
        .lines()
        .find_map(|line| {
            if let Some(start) = line.find("[ss-") {
                let rest = &line[start + 1..];
                if let Some(end) = rest.find(']') {
                    return Some(rest[..end].to_string());
                }
            }
            None
        })
        .expect("Could not extract snapshot ID from export output");
    println!("✓ Created snapshot: {}", snapshot_id);

    // Extract task ID from export output (format: "Task: [task-xxx]")
    let task_id = export_output_str.lines().find_map(|line| {
        if let Some(start) = line.find("[task-") {
            let rest = &line[start + 1..];
            if let Some(end) = rest.find(']') {
                return Some(rest[..end].to_string());
            }
        }
        None
    });

    if let Some(ref tid) = task_id {
        println!("✓ Task ID: {}", tid);
    } else {
        println!("⚠️  No task ID returned - export may be synchronous");
    }

    // =========================================================================
    // STEP 4: Wait for export to complete
    // =========================================================================
    println!("\n┌─────────────────────────────────────────────────────────────────┐");
    println!("│ STEP 4: Wait for Export to Complete                             │");
    println!("└─────────────────────────────────────────────────────────────────┘");

    if let Some(tid) = task_id {
        println!("Monitoring task {} for completion...", tid);
        let mut task_cmd = edgefirst_cmd();
        task_cmd.arg("task").arg(&tid).arg("--monitor");
        task_cmd.timeout(std::time::Duration::from_secs(600));
        task_cmd.ok()?;
        println!("✓ Export task completed");
    } else {
        // No task ID - poll snapshot status directly
        println!("No task ID - polling snapshot status...");
        use edgefirst_client::{Client as EdgeFirstClient, SnapshotID};
        let api_client = EdgeFirstClient::new()?.with_token_path(None)?;
        let snap_id = SnapshotID::try_from(snapshot_id.as_str())?;

        let rt = tokio::runtime::Runtime::new()?;
        let mut attempts = 0;
        let max_attempts = 120; // 2 minutes max wait
        loop {
            let snapshot = rt.block_on(api_client.snapshot(snap_id))?;
            let status = snapshot.status();
            if status == "available" || status == "completed" {
                println!("✓ Snapshot ready (status: {})", status);
                break;
            }
            if status == "failed" || status == "error" {
                panic!("Snapshot export failed (status: {})", status);
            }
            attempts += 1;
            if attempts >= max_attempts {
                panic!(
                    "Snapshot did not become available within {} seconds. Last status: {}",
                    max_attempts, status
                );
            }
            std::thread::sleep(std::time::Duration::from_secs(1));
        }
    }

    // =========================================================================
    // STEP 5: Download the created snapshot
    // =========================================================================
    println!("\n┌─────────────────────────────────────────────────────────────────┐");
    println!("│ STEP 5: Download Created Snapshot                               │");
    println!("└─────────────────────────────────────────────────────────────────┘");

    let snapshot_download_dir = test_dir.join("snapshot");
    fs::create_dir_all(&snapshot_download_dir)?;

    println!(
        "Downloading snapshot to {}...",
        snapshot_download_dir.display()
    );
    let mut download_cmd = edgefirst_cmd();
    download_cmd
        .arg("download-snapshot")
        .arg(&snapshot_id)
        .arg("--output")
        .arg(&snapshot_download_dir);
    download_cmd.timeout(std::time::Duration::from_secs(300));
    download_cmd.ok()?;

    let snapshot_arrow = snapshot_download_dir.join("dataset.arrow");
    assert!(
        snapshot_arrow.exists(),
        "Expected dataset.arrow in snapshot download"
    );
    println!(
        "✓ Downloaded snapshot arrow: {} ({} bytes)",
        snapshot_arrow.display(),
        fs::metadata(&snapshot_arrow)?.len()
    );

    // =========================================================================
    // STEP 6: Compare Original Arrow vs Snapshot Arrow
    // =========================================================================
    println!("\n┌─────────────────────────────────────────────────────────────────┐");
    println!("│ STEP 6: Compare Original vs Snapshot Arrow                      │");
    println!("└─────────────────────────────────────────────────────────────────┘");

    #[cfg(feature = "polars")]
    {
        use polars::prelude::*;

        // Read both Arrow files
        let mut original_file = fs::File::open(&original_arrow)?;
        let original_df = IpcReader::new(&mut original_file).finish()?;

        let mut snapshot_file = fs::File::open(&snapshot_arrow)?;
        let snapshot_df = IpcReader::new(&mut snapshot_file).finish()?;

        println!(
            "Original Arrow: {} rows, {} columns",
            original_df.height(),
            original_df.width()
        );
        println!(
            "Snapshot Arrow: {} rows, {} columns",
            snapshot_df.height(),
            snapshot_df.width()
        );
        println!("Original columns: {:?}", original_df.get_column_names());
        println!("Snapshot columns: {:?}", snapshot_df.get_column_names());

        // Build (name, frame) -> group mapping for both
        #[allow(clippy::type_complexity)]
        fn build_image_groups(
            df: &DataFrame,
        ) -> Result<HashMap<(String, Option<i32>), Option<String>>, Box<dyn std::error::Error>>
        {
            let name_col = df.column("name")?;
            let frame_col = df.column("frame")?;
            let group_col = df.column("group").ok();

            let names_cast = name_col.cast(&DataType::String)?;
            let names = names_cast.str()?;
            // Cast frame to i32 to handle both i32 and u32 sources
            let frames_cast = frame_col.cast(&DataType::Int32)?;
            let frames = frames_cast.i32()?;

            let groups = group_col.and_then(|g| g.cast(&DataType::String).ok());

            let mut map: HashMap<(String, Option<i32>), Option<String>> = HashMap::new();

            for idx in 0..df.height() {
                if let Some(name) = names.get(idx) {
                    let frame = frames.get(idx);
                    let group = groups
                        .as_ref()
                        .and_then(|g| g.str().ok())
                        .and_then(|g| g.get(idx))
                        .map(|s| s.to_string());
                    let key = (name.to_string(), frame);
                    // Only insert if not already present (first row wins for group)
                    map.entry(key).or_insert(group);
                }
            }

            Ok(map)
        }

        let original_groups = build_image_groups(&original_df)?;
        let snapshot_groups = build_image_groups(&snapshot_df)?;

        // Count unique images in each
        println!("Original: {} unique images", original_groups.len());
        println!("Snapshot: {} unique images", snapshot_groups.len());

        // Show group distributions
        fn count_groups(
            groups: &HashMap<(String, Option<i32>), Option<String>>,
        ) -> HashMap<String, usize> {
            let mut counts: HashMap<String, usize> = HashMap::new();
            for group in groups.values() {
                let key = group.clone().unwrap_or_else(|| "null".to_string());
                *counts.entry(key).or_default() += 1;
            }
            counts
        }

        println!(
            "Original group distribution: {:?}",
            count_groups(&original_groups)
        );
        println!(
            "Snapshot group distribution: {:?}",
            count_groups(&snapshot_groups)
        );

        // Compare: All original images should be in snapshot with same group
        let mut missing_in_snapshot: Vec<(String, Option<i32>)> = Vec::new();
        #[allow(clippy::type_complexity)]
        let mut group_mismatches: Vec<(
            (String, Option<i32>),
            Option<String>,
            Option<String>,
        )> = Vec::new();

        for (key, orig_group) in &original_groups {
            if let Some(snap_group) = snapshot_groups.get(key) {
                if orig_group != snap_group {
                    group_mismatches.push((key.clone(), orig_group.clone(), snap_group.clone()));
                }
            } else {
                missing_in_snapshot.push(key.clone());
            }
        }

        // Report findings
        if !missing_in_snapshot.is_empty() {
            println!(
                "\n⚠️  {} images from original NOT FOUND in snapshot:",
                missing_in_snapshot.len()
            );
            for key in missing_in_snapshot.iter().take(10) {
                println!("    ({}, frame={:?})", key.0, key.1);
            }
            if missing_in_snapshot.len() > 10 {
                println!("    ... and {} more", missing_in_snapshot.len() - 10);
            }
        }

        if !group_mismatches.is_empty() {
            println!(
                "\n⚠️  {} images have GROUP MISMATCH:",
                group_mismatches.len()
            );
            for (key, orig, snap) in group_mismatches.iter().take(10) {
                println!(
                    "    ({}, frame={:?}): original={:?} vs snapshot={:?}",
                    key.0, key.1, orig, snap
                );
            }
            if group_mismatches.len() > 10 {
                println!("    ... and {} more", group_mismatches.len() - 10);
            }
        }

        // Extra images in snapshot (not an error, but interesting)
        let extra_in_snapshot: Vec<_> = snapshot_groups
            .keys()
            .filter(|k| !original_groups.contains_key(*k))
            .collect();
        if !extra_in_snapshot.is_empty() {
            println!(
                "\nℹ️  {} images in snapshot but not in original download:",
                extra_in_snapshot.len()
            );
            println!("   (This may be due to download-annotations filtering)");
        }

        // Critical assertions
        assert!(
            missing_in_snapshot.is_empty(),
            "MISSING IMAGES: {} images from original not found in snapshot!\nFirst few: {:?}",
            missing_in_snapshot.len(),
            missing_in_snapshot.iter().take(5).collect::<Vec<_>>()
        );
        println!(
            "✓ All {} original images found in snapshot",
            original_groups.len()
        );

        assert!(
            group_mismatches.is_empty(),
            "GROUP MISMATCH: {} images have different groups!\nFirst few: {:?}",
            group_mismatches.len(),
            group_mismatches.iter().take(5).collect::<Vec<_>>()
        );
        println!("✓ All groups match between original and snapshot");
    }

    #[cfg(not(feature = "polars"))]
    {
        println!("⚠️  Polars feature not enabled - skipping detailed Arrow comparison");
        println!("   Build with --all-features to enable full verification");
    }

    // =========================================================================
    // CLEANUP
    // =========================================================================
    println!("\n┌─────────────────────────────────────────────────────────────────┐");
    println!("│ CLEANUP                                                         │");
    println!("└─────────────────────────────────────────────────────────────────┘");

    // Delete the created snapshot
    let mut cmd = edgefirst_cmd();
    cmd.arg("delete-snapshot").arg(&snapshot_id);
    match cmd.output() {
        Ok(output) if output.status.success() => {
            println!("✓ Deleted snapshot: {}", snapshot_id);
        }
        _ => {
            println!("⚠️  Could not delete snapshot: {}", snapshot_id);
        }
    }

    // Clean up local files
    fs::remove_dir_all(&test_dir).ok();
    println!("✓ Cleaned up test directory");

    println!("\n╔════════════════════════════════════════════════════════════════╗");
    println!("║  ✅ CREATE SNAPSHOT FROM DATASET TEST PASSED                    ║");
    println!("╚════════════════════════════════════════════════════════════════╝");

    Ok(())
}

#[test]
#[file_serial]
#[ignore = "Requires MCAP test data (4GB+). Set TEST_MCAP_SNAPSHOT_ID to run."]
fn test_snapshot_restore_with_mcap_processing() -> Result<(), Box<dyn std::error::Error>> {
    // This test requires an MCAP file to test autodepth and autolabel features.
    // These features only work with MCAP snapshots, not image-based snapshots.
    //
    // Prerequisites:
    // 1. Upload an MCAP file as a snapshot
    // 2. Set TEST_MCAP_SNAPSHOT_ID environment variable to the snapshot ID
    //
    // The --autolabel and --autodepth flags:
    // - --autolabel <labels>: Runs AGTG auto-annotation with specified labels
    //   (requires MCAP)
    // - --autodepth: Generates depth maps (requires Maivin/Raivin camera data in
    //   MCAP)

    let snapshot_id = env::var("TEST_MCAP_SNAPSHOT_ID")
        .expect("TEST_MCAP_SNAPSHOT_ID must be set to run this test");

    let project_id =
        get_project_id_by_name("Unit Testing")?.expect("Unit Testing project not found");

    let mut datasets_to_cleanup = Vec::new();

    // Test 1: Restore with autolabel
    println!("=== STEP 1: Restore with autolabel ===");
    let mut cmd = edgefirst_cmd();
    cmd.arg("restore-snapshot")
        .arg(&project_id)
        .arg(&snapshot_id)
        .arg("--autolabel")
        .arg("car,person,deer");

    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;
    println!("Autolabel restore output:\n{}", output_str);

    if let Some(dataset_id) = output_str.lines().find_map(|line| {
        if line.contains("ds-")
            && let Some(start) = line.find("[ds-")
        {
            let rest = &line[start + 1..];
            rest.find(']').map(|end| rest[..end].to_string())
        } else {
            None
        }
    }) {
        datasets_to_cleanup.push(dataset_id.clone());
        println!("✓ Created dataset with autolabel: {}", dataset_id);
    }

    // Test 2: Restore with autodepth (requires Maivin/Raivin camera)
    println!("\n=== STEP 2: Restore with autodepth ===");
    let mut cmd = edgefirst_cmd();
    cmd.arg("restore-snapshot")
        .arg(&project_id)
        .arg(&snapshot_id)
        .arg("--autodepth");

    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;
    println!("Autodepth restore output:\n{}", output_str);

    if let Some(dataset_id) = output_str.lines().find_map(|line| {
        if line.contains("ds-")
            && let Some(start) = line.find("[ds-")
        {
            let rest = &line[start + 1..];
            rest.find(']').map(|end| rest[..end].to_string())
        } else {
            None
        }
    }) {
        datasets_to_cleanup.push(dataset_id.clone());
        println!("✓ Created dataset with autodepth: {}", dataset_id);
    }

    // Test 3: Restore with both autolabel and autodepth
    println!("\n=== STEP 3: Restore with autolabel + autodepth ===");
    let mut cmd = edgefirst_cmd();
    cmd.arg("restore-snapshot")
        .arg(&project_id)
        .arg(&snapshot_id)
        .arg("--autolabel")
        .arg("car,person")
        .arg("--autodepth");

    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;
    println!("Combined restore output:\n{}", output_str);

    if let Some(dataset_id) = output_str.lines().find_map(|line| {
        if line.contains("ds-")
            && let Some(start) = line.find("[ds-")
        {
            let rest = &line[start + 1..];
            rest.find(']').map(|end| rest[..end].to_string())
        } else {
            None
        }
    }) {
        datasets_to_cleanup.push(dataset_id.clone());
        println!(
            "✓ Created dataset with autolabel + autodepth: {}",
            dataset_id
        );
    }

    // Cleanup
    println!(
        "\n=== CLEANUP: Deleting {} datasets ===",
        datasets_to_cleanup.len()
    );
    for dataset_id in datasets_to_cleanup {
        let mut cmd = edgefirst_cmd();
        cmd.arg("delete-dataset").arg(&dataset_id);
        match cmd.output() {
            Ok(output) if output.status.success() => {
                println!("✓ Deleted dataset: {}", dataset_id);
            }
            Ok(output) => {
                let stderr = String::from_utf8_lossy(&output.stderr);
                println!("⚠ Failed to delete {}: {}", dataset_id, stderr);
            }
            Err(e) => {
                println!("⚠ Error deleting {}: {}", dataset_id, e);
            }
        }
    }

    println!("\n✅ MCAP processing test completed");
    Ok(())
}

/// Test that the server rejects snapshots with inconsistent group values.
///
/// This test creates a malformed snapshot where the same image has two
/// annotation rows with conflicting group values (train vs val). The server
/// MUST reject this during restore as it violates the data integrity
/// constraint that all rows for a given image must have identical group values.
#[test]
#[file_serial]
#[ignore = "Server-side validation for inconsistent groups not yet implemented. This test verifies the expected behavior when it is."]
fn test_server_rejects_inconsistent_group_snapshot() -> Result<(), Box<dyn std::error::Error>> {
    use polars::prelude::*;
    use std::io::Write;

    println!("╔════════════════════════════════════════════════════════════════╗");
    println!("║  SERVER VALIDATION: Inconsistent Group Rejection Test          ║");
    println!("╚════════════════════════════════════════════════════════════════╝");

    // =========================================================================
    // STEP 1: Create test directory structure (EdgeFirst Dataset Format)
    // =========================================================================
    println!("\n┌─────────────────────────────────────────────────────────────────┐");
    println!("│ STEP 1: Create Malformed Snapshot Data                          │");
    println!("└─────────────────────────────────────────────────────────────────┘");

    let test_data_dir = get_test_data_dir();
    let timestamp = SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis();
    let dataset_name = format!("test_{}_{timestamp}", std::process::id());

    // EdgeFirst Dataset Format structure:
    // dataset_root/                  <- Root directory (passed to create-snapshot)
    // ├── dataset_root.arrow         <- Arrow file with SAME name as root directory
    // └── dataset_root/              <- Sensor container with SAME name as root
    //     └── test_image.png         <- Image files in sensor container

    let dataset_root = test_data_dir
        .join("inconsistent_group_test")
        .join(&dataset_name);
    let sensor_container = dataset_root.join(&dataset_name);
    fs::create_dir_all(&sensor_container)?;

    // Create a simple 1x1 red PNG image (minimal valid PNG)
    let png_data: [u8; 70] = [
        0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, // PNG signature (8 bytes)
        0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, // IHDR length + type (8 bytes)
        0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, // 1x1 pixels (8 bytes)
        0x08, 0x02, 0x00, 0x00, 0x00, 0x90, 0x77, 0x53, 0xDE, // depth, color, CRC (9 bytes)
        0x00, 0x00, 0x00, 0x0C, 0x49, 0x44, 0x41, 0x54, // IDAT length + type (8 bytes)
        0x08, 0xD7, 0x63, 0xF8, 0xCF, 0xC0, 0x00, 0x00, // compressed data (8 bytes)
        0x00, 0x03, 0x00, 0x01, 0x00, 0x18, 0xDD, 0x8D, 0xB4, // more data + CRC (9 bytes)
        0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, // IEND length + type (8 bytes)
        0xAE, 0x42, 0x60, 0x82, // IEND CRC (4 bytes)
    ]; // Total: 70 bytes

    // Create image in sensor container
    let image_path = sensor_container.join("test_image.png");
    let mut image_file = fs::File::create(&image_path)?;
    image_file.write_all(&png_data)?;
    println!("✓ Created sensor container with test_image.png");

    // Create {dataset_name}.arrow in dataset_root with CONFLICTING group values
    // Row 1: test_image, group=train, label=cat
    // Row 2: test_image, group=val, label=dog   <-- CONFLICT! Same image, different
    // group
    let arrow_path = dataset_root.join(format!("{}.arrow", dataset_name));

    let names = Series::new("name".into(), vec!["test_image", "test_image"]);
    let frames: Series = Series::new("frame".into(), vec![None::<u32>, None::<u32>]);
    let groups = Series::new("group".into(), vec![Some("train"), Some("val")]); // CONFLICT!
    let labels = Series::new("label".into(), vec![Some("cat"), Some("dog")]);

    // Create box2d data as array columns
    let box2d_data: Vec<Option<[f32; 4]>> = vec![
        Some([0.5, 0.5, 0.2, 0.2]), // cx, cy, w, h
        Some([0.3, 0.3, 0.1, 0.1]),
    ];
    let box2d_series: Vec<Option<Series>> = box2d_data
        .into_iter()
        .map(|opt| opt.map(|arr| Series::new("box2d".into(), arr.to_vec())))
        .collect();
    let box2d = Series::new("box2d".into(), box2d_series)
        .cast(&DataType::Array(Box::new(DataType::Float32), 4))?;

    let mut df = DataFrame::new_infer_height(vec![
        names.into_column(),
        frames.into_column(),
        groups.into_column(),
        labels.into_column(),
        box2d.into_column(),
    ])?;

    let mut arrow_file = fs::File::create(&arrow_path)?;
    IpcWriter::new(&mut arrow_file).finish(&mut df)?;
    println!("✓ Created {}.arrow with CONFLICTING groups:", dataset_name);
    println!("    Row 1: test_image, group=train");
    println!("    Row 2: test_image, group=val   <-- CONFLICT!");

    // =========================================================================
    // STEP 2: Upload snapshot
    // =========================================================================
    println!("\n┌─────────────────────────────────────────────────────────────────┐");
    println!("│ STEP 2: Upload Malformed Snapshot                               │");
    println!("└─────────────────────────────────────────────────────────────────┘");

    let mut cmd = edgefirst_cmd();
    // Pass the dataset_root - EdgeFirst Dataset Format expects {name}.arrow inside
    // root
    cmd.arg("create-snapshot").arg(&dataset_root);
    cmd.timeout(std::time::Duration::from_secs(120));
    let create_output = cmd.ok()?.stdout;
    let create_output_str = String::from_utf8(create_output)?;
    println!("Create snapshot output:\n{}", create_output_str);

    let snapshot_id = create_output_str
        .lines()
        .find_map(|line| {
            if let Some(start) = line.find('[')
                && let Some(end) = line[start..].find(']')
            {
                let id = &line[start + 1..start + end];
                if id.starts_with("ss-") {
                    return Some(id.to_string());
                }
            }
            None
        })
        .expect("Could not extract snapshot ID from creation output");
    println!("✓ Uploaded snapshot: {}", snapshot_id);

    // Wait for snapshot to be processed
    println!("Waiting for snapshot processing...");
    use edgefirst_client::{Client as EdgeFirstClient, SnapshotID};
    let api_client = EdgeFirstClient::new()?.with_token_path(None)?;
    let snap_id = SnapshotID::try_from(snapshot_id.as_str())?;

    let rt = tokio::runtime::Runtime::new()?;
    let mut attempts = 0;
    let max_attempts = 60;
    loop {
        let snapshot = rt.block_on(api_client.snapshot(snap_id))?;
        let status = snapshot.status();
        if status == "available" || status == "completed" {
            println!("✓ Snapshot ready (status: {})", status);
            break;
        }
        if status == "failed" || status == "error" {
            println!("⚠ Snapshot processing failed (status: {})", status);
            println!("  This may indicate server-side validation caught the issue early");
            // Clean up the dataset_root directory (contains both Arrow file and sensor
            // container)
            fs::remove_dir_all(&dataset_root).ok();
            return Ok(());
        }
        attempts += 1;
        if attempts >= max_attempts {
            panic!(
                "Snapshot did not become available within {} seconds",
                max_attempts
            );
        }
        std::thread::sleep(std::time::Duration::from_secs(1));
    }

    // =========================================================================
    // STEP 3: Get project ID for restore
    // =========================================================================
    println!("\n┌─────────────────────────────────────────────────────────────────┐");
    println!("│ STEP 3: Get Project for Restore                                 │");
    println!("└─────────────────────────────────────────────────────────────────┘");

    let mut cmd = edgefirst_cmd();
    cmd.arg("projects").arg("--name").arg("Unit Testing");
    let output = cmd.ok()?.stdout;
    let output_str = String::from_utf8(output)?;

    let project_id = output_str
        .lines()
        .find_map(|line| {
            line.split(']')
                .next()
                .and_then(|s| s.strip_prefix('['))
                .map(|s| s.trim().to_string())
                .filter(|id| id.starts_with("p-"))
        })
        .expect("No project found matching 'Unit Testing'");
    println!("✓ Project: {}", project_id);

    // =========================================================================
    // STEP 4: Attempt to restore - Server SHOULD reject this
    // =========================================================================
    println!("\n┌─────────────────────────────────────────────────────────────────┐");
    println!("│ STEP 4: Attempt Restore (Should FAIL)                           │");
    println!("└─────────────────────────────────────────────────────────────────┘");

    let mut cmd = edgefirst_cmd();
    cmd.arg("restore-snapshot")
        .arg(&project_id)
        .arg(&snapshot_id)
        .arg("--monitor"); // Wait for completion to see the error
    cmd.timeout(std::time::Duration::from_secs(300));

    let result = cmd.output();

    // Clean up the entire dataset_root directory regardless of outcome
    fs::remove_dir_all(&dataset_root).ok();

    match result {
        Ok(output) => {
            let stdout = String::from_utf8_lossy(&output.stdout);
            let stderr = String::from_utf8_lossy(&output.stderr);

            println!("Restore stdout:\n{}", stdout);
            println!("Restore stderr:\n{}", stderr);

            if output.status.success() {
                // If restore succeeded, we need to check if a dataset was created
                // and if so, try to clean it up and FAIL the test
                if let Some(dataset_id) = stdout.lines().chain(stderr.lines()).find_map(|line| {
                    if let Some(start) = line.find("[ds-") {
                        let rest = &line[start + 1..];
                        rest.find(']').map(|end| rest[..end].to_string())
                    } else {
                        None
                    }
                }) {
                    println!("⚠ Cleaning up erroneously created dataset: {}", dataset_id);
                    let mut cleanup_cmd = edgefirst_cmd();
                    cleanup_cmd.arg("delete-dataset").arg(&dataset_id);
                    cleanup_cmd.output().ok();
                }

                // Check if the task failed even though command returned success
                let task_failed = stdout.contains("failed")
                    || stderr.contains("failed")
                    || stdout.contains("error")
                    || stderr.contains("Inconsistent group");

                if task_failed {
                    // Verify we got a meaningful error message
                    let combined = format!("{}\n{}", stdout, stderr);
                    assert!(
                        combined.contains("Inconsistent group"),
                        "Expected meaningful error message mentioning 'Inconsistent group', got:\n{}",
                        combined
                    );

                    println!(
                        "\n╔════════════════════════════════════════════════════════════════╗"
                    );
                    println!("║  ✅ SERVER CORRECTLY REJECTED INCONSISTENT GROUPS              ║");
                    println!("║  ✅ Error message is meaningful and actionable                 ║");
                    println!("╚════════════════════════════════════════════════════════════════╝");
                    return Ok(());
                }

                panic!(
                    "SERVER BUG: Restore SUCCEEDED with inconsistent groups!\n\
                     The server should have rejected the snapshot with conflicting\n\
                     group values (train vs val) for the same image.\n\
                     This indicates the server-side validation is not working."
                );
            } else {
                // Command failed - this is expected!
                let error_output = format!("{}\n{}", stdout, stderr);

                // Verify it failed for the RIGHT reason with a meaningful message
                assert!(
                    error_output.contains("Inconsistent group"),
                    "Expected meaningful error message mentioning 'Inconsistent group', got:\n{}",
                    error_output
                );

                println!("\n╔════════════════════════════════════════════════════════════════╗");
                println!("║  ✅ SERVER CORRECTLY REJECTED INCONSISTENT GROUPS              ║");
                println!("║  ✅ Error message is meaningful and actionable                 ║");
                println!("╚════════════════════════════════════════════════════════════════╝");
                return Ok(());
            }
        }
        Err(e) => {
            // Command execution failed - could be timeout or other issue
            println!("Restore command error: {}", e);
            println!("\n⚠ Could not determine if server rejected the invalid data");
            return Ok(());
        }
    }
}

// ============================================================================
// COCO Format Tests
// ============================================================================

#[test]
fn test_coco_to_arrow_basic() {
    let temp_dir = tempfile::TempDir::new().unwrap();

    let coco_json = r#"{
        "images": [{"id": 1, "width": 640, "height": 480, "file_name": "test.jpg"}],
        "annotations": [{"id": 1, "image_id": 1, "category_id": 1, "bbox": [10, 20, 100, 80], "area": 8000, "iscrowd": 0}],
        "categories": [{"id": 1, "name": "person", "supercategory": "human"}]
    }"#;

    let input = temp_dir.path().join("test.json");
    std::fs::write(&input, coco_json).unwrap();

    let output = temp_dir.path().join("output.arrow");

    edgefirst_cmd()
        .args([
            "coco-to-arrow",
            input.to_str().unwrap(),
            "-o",
            output.to_str().unwrap(),
        ])
        .assert()
        .success()
        .stdout(predicates::str::contains("Converted 1"));

    assert!(output.exists(), "Arrow output file should exist");
}

#[test]
fn test_coco_to_arrow_with_group() {
    let temp_dir = tempfile::TempDir::new().unwrap();

    let coco_json = r#"{
        "images": [{"id": 1, "width": 640, "height": 480, "file_name": "test.jpg"}],
        "annotations": [{"id": 1, "image_id": 1, "category_id": 1, "bbox": [10, 20, 100, 80], "area": 8000, "iscrowd": 0}],
        "categories": [{"id": 1, "name": "person", "supercategory": "human"}]
    }"#;

    let input = temp_dir.path().join("test.json");
    std::fs::write(&input, coco_json).unwrap();

    let output = temp_dir.path().join("output.arrow");

    edgefirst_cmd()
        .args([
            "coco-to-arrow",
            input.to_str().unwrap(),
            "-o",
            output.to_str().unwrap(),
            "--group",
            "train",
        ])
        .assert()
        .success();

    assert!(output.exists(), "Arrow output file should exist");
}

#[test]
fn test_coco_roundtrip_cli() {
    let temp_dir = tempfile::TempDir::new().unwrap();

    let coco_json = r#"{
        "images": [{"id": 1, "width": 640, "height": 480, "file_name": "test.jpg"}],
        "annotations": [
            {"id": 1, "image_id": 1, "category_id": 1, "bbox": [10, 20, 100, 80], "area": 8000, "iscrowd": 0,
             "segmentation": [[10, 20, 110, 20, 110, 100, 10, 100]]}
        ],
        "categories": [{"id": 1, "name": "person", "supercategory": "human"}]
    }"#;

    let input = temp_dir.path().join("original.json");
    std::fs::write(&input, coco_json).unwrap();

    let arrow = temp_dir.path().join("converted.arrow");
    let restored = temp_dir.path().join("restored.json");

    // COCO -> Arrow
    edgefirst_cmd()
        .args([
            "coco-to-arrow",
            input.to_str().unwrap(),
            "-o",
            arrow.to_str().unwrap(),
        ])
        .assert()
        .success();

    assert!(arrow.exists(), "Arrow file should exist after conversion");

    // Arrow -> COCO
    edgefirst_cmd()
        .args([
            "arrow-to-coco",
            arrow.to_str().unwrap(),
            "-o",
            restored.to_str().unwrap(),
            "--pretty",
        ])
        .assert()
        .success();

    assert!(restored.exists(), "Restored COCO file should exist");

    // Verify restored file content
    let contents = std::fs::read_to_string(&restored).unwrap();
    let restored_data: serde_json::Value = serde_json::from_str(&contents).unwrap();

    assert_eq!(
        restored_data["annotations"].as_array().unwrap().len(),
        1,
        "Should have 1 annotation"
    );
    assert_eq!(
        restored_data["categories"].as_array().unwrap().len(),
        1,
        "Should have 1 category"
    );
}

#[test]
fn test_coco_to_arrow_multiple_annotations() {
    let temp_dir = tempfile::TempDir::new().unwrap();

    let coco_json = r#"{
        "images": [
            {"id": 1, "width": 640, "height": 480, "file_name": "image1.jpg"},
            {"id": 2, "width": 800, "height": 600, "file_name": "image2.jpg"}
        ],
        "annotations": [
            {"id": 1, "image_id": 1, "category_id": 1, "bbox": [10, 20, 100, 80], "area": 8000, "iscrowd": 0},
            {"id": 2, "image_id": 1, "category_id": 2, "bbox": [200, 150, 50, 60], "area": 3000, "iscrowd": 0},
            {"id": 3, "image_id": 2, "category_id": 1, "bbox": [50, 50, 200, 150], "area": 30000, "iscrowd": 0}
        ],
        "categories": [
            {"id": 1, "name": "person", "supercategory": "human"},
            {"id": 2, "name": "car", "supercategory": "vehicle"}
        ]
    }"#;

    let input = temp_dir.path().join("multi.json");
    std::fs::write(&input, coco_json).unwrap();

    let output = temp_dir.path().join("multi.arrow");

    edgefirst_cmd()
        .args([
            "coco-to-arrow",
            input.to_str().unwrap(),
            "-o",
            output.to_str().unwrap(),
        ])
        .assert()
        .success()
        .stdout(predicates::str::contains("Converted 3"));

    assert!(output.exists());
}

#[test]
fn test_coco_to_arrow_with_masks() {
    let temp_dir = tempfile::TempDir::new().unwrap();

    let coco_json = r#"{
        "images": [{"id": 1, "width": 640, "height": 480, "file_name": "test.jpg"}],
        "annotations": [
            {"id": 1, "image_id": 1, "category_id": 1, "bbox": [10, 20, 100, 80], "area": 8000, "iscrowd": 0,
             "segmentation": [[10, 20, 110, 20, 110, 100, 10, 100]]}
        ],
        "categories": [{"id": 1, "name": "person", "supercategory": "human"}]
    }"#;

    let input = temp_dir.path().join("masks.json");
    std::fs::write(&input, coco_json).unwrap();

    let output = temp_dir.path().join("masks.arrow");

    // --masks defaults to true, so we don't need to specify it
    edgefirst_cmd()
        .args([
            "coco-to-arrow",
            input.to_str().unwrap(),
            "-o",
            output.to_str().unwrap(),
        ])
        .assert()
        .success();

    assert!(output.exists());
}

#[test]
fn test_arrow_to_coco_with_groups() {
    let temp_dir = tempfile::TempDir::new().unwrap();

    // Create COCO with group
    let coco_json = r#"{
        "images": [{"id": 1, "width": 640, "height": 480, "file_name": "test.jpg"}],
        "annotations": [{"id": 1, "image_id": 1, "category_id": 1, "bbox": [10, 20, 100, 80], "area": 8000, "iscrowd": 0}],
        "categories": [{"id": 1, "name": "person", "supercategory": "human"}]
    }"#;

    let input = temp_dir.path().join("test.json");
    std::fs::write(&input, coco_json).unwrap();

    let arrow = temp_dir.path().join("test.arrow");
    let output = temp_dir.path().join("filtered.json");

    // COCO -> Arrow with group
    edgefirst_cmd()
        .args([
            "coco-to-arrow",
            input.to_str().unwrap(),
            "-o",
            arrow.to_str().unwrap(),
            "--group",
            "train",
        ])
        .assert()
        .success();

    // Arrow -> COCO with group filter
    edgefirst_cmd()
        .args([
            "arrow-to-coco",
            arrow.to_str().unwrap(),
            "-o",
            output.to_str().unwrap(),
            "--groups",
            "train",
        ])
        .assert()
        .success();

    assert!(output.exists());

    // Verify content
    let contents = std::fs::read_to_string(&output).unwrap();
    let restored_data: serde_json::Value = serde_json::from_str(&contents).unwrap();
    assert_eq!(
        restored_data["annotations"].as_array().unwrap().len(),
        1,
        "Should have 1 annotation in filtered output"
    );
}

// ============================================================================
// Migrate Command Tests
// ============================================================================

#[test]
fn test_migrate_command_help() {
    edgefirst_cmd()
        .args(["migrate", "--help"])
        .assert()
        .success()
        .stdout(predicates::str::contains("Migrate an Arrow file"));
}

#[test]
fn test_migrate_command_missing_input() {
    edgefirst_cmd()
        .args(["migrate", "/nonexistent/file.arrow"])
        .assert()
        .failure()
        .stderr(predicates::str::contains("does not exist"));
}

#[test]
fn test_migrate_command_with_mask_column() {
    use polars::prelude::*;

    let temp_dir = tempfile::TempDir::new().unwrap();
    let input = temp_dir.path().join("legacy.arrow");
    let output = temp_dir.path().join("migrated.arrow");

    // Create a 2025.10-style Arrow file with a NaN-separated mask column
    // mask: List(Float32) with NaN separating polygon rings
    // Two rows: one with a polygon (two rings), one null
    {
        let names = Series::new("name".into(), vec!["img1.jpg", "img2.jpg"]);
        let labels = Series::new("label".into(), vec![Some("cat"), None]);

        // Row 0: polygon with 2 rings separated by NaN
        //   Ring 1: (10,20), (30,40)  -> [10, 20, 30, 40]
        //   Ring 2: (50,60)           -> [50, 60]
        //   Flat:   [10, 20, 30, 40, NaN, 50, 60]
        let ring1_and_2: Vec<f32> = vec![10.0, 20.0, 30.0, 40.0, f32::NAN, 50.0, 60.0];
        let row0 = Some(Series::new(PlSmallStr::from(""), ring1_and_2));

        // Row 1: null mask
        let row1: Option<Series> = None;

        let mask = Series::new("mask".into(), vec![row0, row1]);

        let mut df =
            DataFrame::new_infer_height(vec![names.into(), labels.into(), mask.into()]).unwrap();

        let mut file = std::fs::File::create(&input).unwrap();
        IpcWriter::new(&mut file).finish(&mut df).unwrap();
    }

    // Run the migrate command
    edgefirst_cmd()
        .args([
            "migrate",
            input.to_str().unwrap(),
            "--output",
            output.to_str().unwrap(),
        ])
        .assert()
        .success()
        .stdout(predicates::str::contains(
            "Converted 'mask' column -> 'polygon' column",
        ))
        .stdout(predicates::str::contains(
            "Migrated to schema version 2026.04",
        ));

    assert!(output.exists(), "Migrated Arrow output file should exist");

    // Read back and verify the migrated file
    {
        let mut file = std::fs::File::open(&output).unwrap();

        // Verify schema_version metadata
        let mut reader = IpcReader::new(&mut file);
        let custom_meta = reader.custom_metadata().unwrap();
        assert!(custom_meta.is_some(), "custom metadata should be present");
        let meta = custom_meta.unwrap();
        assert_eq!(
            meta.get(&PlSmallStr::from("schema_version")),
            Some(&PlSmallStr::from("2026.04")),
            "schema_version should be 2026.04"
        );

        // Re-open to read DataFrame
        let mut file = std::fs::File::open(&output).unwrap();
        let df = IpcReader::new(&mut file).finish().unwrap();

        // Verify mask column is gone
        assert!(
            df.column("mask").is_err(),
            "mask column should have been removed"
        );

        // Verify polygon column exists
        let polygon_col = df
            .column("polygon")
            .expect("polygon column should exist after migration");

        assert_eq!(polygon_col.len(), 2, "Should have 2 rows");

        // Should have 1 null row (row 1 had null mask) out of 2 total
        assert_eq!(
            polygon_col.null_count(),
            1,
            "Should have exactly 1 null polygon row (from null mask)"
        );

        // Verify the other columns are preserved
        assert!(df.column("name").is_ok(), "name column should be preserved");
        assert!(
            df.column("label").is_ok(),
            "label column should be preserved"
        );
    }
}

#[test]
fn test_migrate_command_already_migrated() {
    use polars::prelude::*;
    use std::sync::Arc;

    let temp_dir = tempfile::TempDir::new().unwrap();
    let input = temp_dir.path().join("already_migrated.arrow");

    // Create an Arrow file that already has schema_version = "2026.04"
    {
        let names = Series::new("name".into(), vec!["img1.jpg"]);
        let mut df = DataFrame::new_infer_height(vec![names.into()]).unwrap();

        let mut metadata: std::collections::BTreeMap<PlSmallStr, PlSmallStr> =
            std::collections::BTreeMap::new();
        metadata.insert(
            PlSmallStr::from("schema_version"),
            PlSmallStr::from("2026.04"),
        );

        let mut file = std::fs::File::create(&input).unwrap();
        let mut writer = IpcWriter::new(&mut file);
        writer.set_custom_schema_metadata(Arc::new(metadata));
        writer.finish(&mut df).unwrap();
    }

    // Run the migrate command — should detect already-migrated and succeed
    edgefirst_cmd()
        .args(["migrate", input.to_str().unwrap()])
        .assert()
        .success()
        .stdout(predicates::str::contains("no migration needed"));
}

#[test]
fn test_migrate_command_no_mask_column() {
    use polars::prelude::*;

    let temp_dir = tempfile::TempDir::new().unwrap();
    let input = temp_dir.path().join("no_mask.arrow");
    let output = temp_dir.path().join("migrated_no_mask.arrow");

    // Create an Arrow file without a mask column (e.g., box2d only)
    {
        let names = Series::new("name".into(), vec!["img1.jpg"]);
        let mut df = DataFrame::new_infer_height(vec![names.into()]).unwrap();

        let mut file = std::fs::File::create(&input).unwrap();
        IpcWriter::new(&mut file).finish(&mut df).unwrap();
    }

    // Run the migrate command — should just update metadata
    edgefirst_cmd()
        .args([
            "migrate",
            input.to_str().unwrap(),
            "--output",
            output.to_str().unwrap(),
        ])
        .assert()
        .success()
        .stdout(predicates::str::contains("No 'mask' column found"))
        .stdout(predicates::str::contains(
            "Migrated to schema version 2026.04",
        ));

    assert!(output.exists());

    // Verify schema_version was set
    {
        let mut file = std::fs::File::open(&output).unwrap();
        let mut reader = IpcReader::new(&mut file);
        let custom_meta = reader.custom_metadata().unwrap();
        assert!(custom_meta.is_some());
        let meta = custom_meta.unwrap();
        assert_eq!(
            meta.get(&PlSmallStr::from("schema_version")),
            Some(&PlSmallStr::from("2026.04")),
        );
    }
}

#[test]
fn test_migrate_command_inplace() {
    use polars::prelude::*;

    let temp_dir = tempfile::TempDir::new().unwrap();
    let input = temp_dir.path().join("inplace.arrow");

    // Create a simple Arrow file without mask column
    {
        let names = Series::new("name".into(), vec!["img1.jpg"]);
        let mut df = DataFrame::new_infer_height(vec![names.into()]).unwrap();

        let mut file = std::fs::File::create(&input).unwrap();
        IpcWriter::new(&mut file).finish(&mut df).unwrap();
    }

    // Run migrate without --output (in-place)
    edgefirst_cmd()
        .args(["migrate", input.to_str().unwrap()])
        .assert()
        .success()
        .stdout(predicates::str::contains(
            "Migrated to schema version 2026.04",
        ));

    // Verify the file was updated in place
    {
        let mut file = std::fs::File::open(&input).unwrap();
        let mut reader = IpcReader::new(&mut file);
        let custom_meta = reader.custom_metadata().unwrap();
        assert!(custom_meta.is_some());
        let meta = custom_meta.unwrap();
        assert_eq!(
            meta.get(&PlSmallStr::from("schema_version")),
            Some(&PlSmallStr::from("2026.04")),
        );
    }
}

#[test]
fn test_migrate_coco_to_arrow_roundtrip() {
    let temp_dir = tempfile::TempDir::new().unwrap();

    // Create a COCO file with polygon segmentation
    let coco_json = r#"{
        "images": [{"id": 1, "width": 640, "height": 480, "file_name": "test.jpg"}],
        "annotations": [{
            "id": 1, "image_id": 1, "category_id": 1,
            "bbox": [10, 20, 100, 80], "area": 8000, "iscrowd": 0,
            "segmentation": [[10, 20, 110, 20, 110, 100, 10, 100]]
        }],
        "categories": [{"id": 1, "name": "person", "supercategory": "human"}]
    }"#;

    let coco_path = temp_dir.path().join("coco.json");
    std::fs::write(&coco_path, coco_json).unwrap();

    let arrow_path = temp_dir.path().join("dataset.arrow");

    // Convert COCO to Arrow (produces 2026.04 schema with polygon column)
    edgefirst_cmd()
        .args([
            "coco-to-arrow",
            coco_path.to_str().unwrap(),
            "-o",
            arrow_path.to_str().unwrap(),
        ])
        .assert()
        .success();

    // Running migrate on a 2026.04 file should be a no-op
    edgefirst_cmd()
        .args(["migrate", arrow_path.to_str().unwrap()])
        .assert()
        .success()
        .stdout(predicates::str::contains("no migration needed"));
}