servicenow-cli 0.6.3

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

use clap::{ArgGroup, CommandFactory, Parser, Subcommand};
use clap_complete::Shell;
use dialoguer::{Confirm, Editor, Input, Password, Select};
use serde_json::{Map, Value};
use servicenow_cli::api::{ApiError, DisplayValue, ListOptions, ServiceNowClient};
use servicenow_cli::attachment;
use servicenow_cli::catalog::{self, CatalogItem};
use servicenow_cli::commands::{
    INCIDENT_HUMAN_FIELDS, INCIDENT_LIST_FIELDS, build_body, parse_fields, print_record,
    print_records, print_records_or, record_sys_id,
};
use servicenow_cli::config::{
    AuthType, Config, ProfileConfig, active_profile_name, config_path, delete_stored_credential,
    init_document, profile_defaults, profile_summaries, remove_profile, save_profile, use_profile,
};
use servicenow_cli::credentials::{self, StoredCredential};
use servicenow_cli::incident;
use servicenow_cli::metadata::{self, ReferenceKind};
use servicenow_cli::output::{self, OutputConfig, OutputFormat, exit_code, print_error};
use servicenow_cli::record;
use servicenow_cli::{out, outln};

#[derive(Parser)]
#[command(
    name = "servicenow",
    version,
    about = "Fast, safe, human-friendly ServiceNow operations from the terminal",
    arg_required_else_help = true,
    after_help = "Get started:\n  servicenow init                    Configure and sign in\n  servicenow doctor                  Check configuration and instance access\n  servicenow incidents mine          See what needs your attention\n  servicenow schema --command 'incidents list'\n                                      Inspect one command for automation"
)]
struct Cli {
    /// Instance name, hostname, or URL
    #[arg(long, env = "SERVICENOW_INSTANCE")]
    instance: Option<String>,

    /// Username for Basic authentication
    #[arg(long, env = "SERVICENOW_USERNAME")]
    username: Option<String>,

    /// Config profile
    #[arg(long, env = "SERVICENOW_PROFILE", global = true)]
    profile: Option<String>,

    /// Output format: auto, table, text, json, jsonl, yaml, or csv
    #[arg(short, long, global = true, default_value = "auto")]
    output: String,

    /// Output JSON (alias for --output json)
    #[arg(long, global = true, hide = true)]
    json: bool,

    /// Suppress non-data messages
    #[arg(long, global = true)]
    quiet: bool,

    /// Show secret-free browser sign-in progress on stderr
    #[arg(
        short,
        long,
        global = true,
        env = "SERVICENOW_VERBOSE",
        conflicts_with = "quiet"
    )]
    verbose: bool,

    /// Disable ANSI color even when stdout is a terminal
    #[arg(long, global = true)]
    no_color: bool,

    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Connect an instance with guided, secure setup
    #[command(alias = "setup")]
    Init {
        /// Legacy positional profile name; prefer the global --profile option
        #[arg(value_name = "PROFILE", hide = true)]
        legacy_profile: Option<String>,

        /// Instance name, hostname, or URL
        #[arg(long)]
        instance: Option<String>,

        /// Authentication method (auto-detected when omitted)
        #[arg(long, value_enum)]
        method: Option<AuthType>,

        /// Username for Basic authentication
        #[arg(long)]
        username: Option<String>,

        /// OAuth application client ID
        #[arg(long)]
        client_id: Option<String>,

        /// Space-separated OAuth scopes
        #[arg(long)]
        scope: Option<String>,

        /// Registered loopback OAuth redirect URI
        #[arg(long)]
        redirect_uri: Option<String>,

        /// Read the password/token/client secret from stdin
        #[arg(long)]
        secret_stdin: bool,

        /// Store the credential in the protected config file instead of the OS keychain
        #[arg(long)]
        insecure_storage: bool,

        /// Do not open a browser automatically (OAuth only)
        #[arg(long)]
        no_browser: bool,

        /// Block all writes when this profile is active
        #[arg(long)]
        read_only: bool,
    },

    /// Sign in securely and inspect authentication
    #[command(subcommand)]
    Auth(AuthCommand),

    /// Manage named instance profiles
    #[command(subcommand, visible_alias = "profiles")]
    Profile(ProfileCommand),

    /// Operate incidents and browse ServiceNow tables interactively
    Tui {
        /// Table to open first
        #[arg(default_value = "incident")]
        table: String,

        /// ServiceNow encoded query to apply instead of the default incident view
        #[arg(short, long)]
        query: Option<String>,

        /// Records loaded per page
        #[arg(long, default_value = "25", value_parser = parse_tui_page_size)]
        page_size: usize,
    },

    /// Work with incidents
    #[command(subcommand, visible_alias = "incident")]
    Incidents(IncidentsCommand),

    /// List, upload, download, and delete record attachments
    #[command(subcommand, visible_alias = "attachment")]
    Attachments(AttachmentsCommand),

    /// Search, inspect, and order Service Catalog items
    #[command(subcommand, visible_alias = "cat")]
    Catalog(CatalogCommand),

    /// Perform generic CRUD operations through the Table API
    #[command(subcommand, visible_alias = "table")]
    Tables(TablesCommand),

    /// Inspect configuration
    #[command(subcommand)]
    Config(ConfigCommand),

    /// Verify configuration, authentication, and Table API access
    Doctor {
        /// Check local configuration without contacting ServiceNow
        #[arg(long)]
        offline: bool,
    },

    /// Inspect the command tree or an instance table schema
    Schema {
        /// Table whose dictionary metadata should be shown
        table: Option<String>,

        /// Return only one command and its arguments, such as "incidents list"
        #[arg(long, conflicts_with = "table")]
        command: Option<String>,

        /// Refresh metadata from the instance
        #[arg(long)]
        refresh: bool,
    },

    /// List the configured choices for a table field
    Choices {
        table: String,
        field: String,

        /// Refresh metadata from the instance
        #[arg(long)]
        refresh: bool,
    },

    /// Resolve a human user/group identifier to a ServiceNow record
    Resolve {
        #[arg(value_enum)]
        kind: ReferenceKind,
        value: String,
    },

    /// Generate shell completions
    Completions {
        /// Shell whose completion script to generate
        shell: Shell,
    },
}

#[derive(Subcommand)]
enum AuthCommand {
    /// Sign in and store the credential securely when possible
    Login {
        /// Legacy positional profile name; prefer the global --profile option
        #[arg(value_name = "PROFILE", hide = true)]
        legacy_profile: Option<String>,

        /// Instance name, hostname, or URL
        #[arg(long)]
        instance: Option<String>,

        /// Authentication method (auto-detected when omitted)
        #[arg(long, value_enum)]
        method: Option<AuthType>,

        /// Username for Basic authentication
        #[arg(long)]
        username: Option<String>,

        /// OAuth application client ID
        #[arg(long)]
        client_id: Option<String>,

        /// Space-separated OAuth scopes
        #[arg(long)]
        scope: Option<String>,

        /// Registered loopback OAuth redirect URI
        #[arg(long)]
        redirect_uri: Option<String>,

        /// Read the password/token/client secret from stdin
        #[arg(long)]
        secret_stdin: bool,

        /// Store the credential in the protected config file instead of the OS keychain
        #[arg(long)]
        insecure_storage: bool,

        /// Do not open a browser automatically (OAuth only)
        #[arg(long)]
        no_browser: bool,

        /// Block all writes when this profile is active
        #[arg(long)]
        read_only: bool,
    },

    /// Remove the stored credential but keep profile settings
    Logout {
        /// Legacy positional profile name; prefer the global --profile option
        #[arg(value_name = "PROFILE", hide = true)]
        legacy_profile: Option<String>,
    },

    /// Show the active identity and credential health
    Status {
        /// Inspect local credential state without contacting ServiceNow
        #[arg(long)]
        offline: bool,
    },
}

#[derive(Subcommand)]
enum ProfileCommand {
    /// List configured profiles
    List,

    /// Select the default profile for future commands
    Use { name: String },

    /// Remove a profile and its stored credential
    Remove {
        name: String,

        /// Confirm removal without prompting
        #[arg(long)]
        yes: bool,
    },
}

#[derive(Subcommand)]
enum IncidentsCommand {
    /// List incidents
    List {
        /// ServiceNow encoded query
        #[arg(short, long)]
        query: Option<String>,

        /// Return only active incidents
        #[arg(long)]
        active: bool,

        /// Maximum records to return
        #[arg(short = 'n', long, default_value = "50")]
        limit: usize,

        /// Skip the first N records
        #[arg(long, default_value = "0")]
        offset: usize,

        /// Fetch all pages
        #[arg(long)]
        all: bool,

        /// Comma-separated fields to return
        #[arg(long)]
        fields: Option<String>,

        /// Return raw values, display values, or both
        #[arg(long, value_enum)]
        display_value: Option<DisplayValue>,
    },

    /// List incidents assigned to the authenticated user
    Mine {
        /// Additional ServiceNow encoded query
        #[arg(short, long)]
        query: Option<String>,

        /// Maximum records to return
        #[arg(short = 'n', long, default_value = "50")]
        limit: usize,

        /// Fetch all pages
        #[arg(long)]
        all: bool,

        /// Return raw values, display values, or both
        #[arg(long, value_enum)]
        display_value: Option<DisplayValue>,
    },

    /// Show an incident by number or sys_id
    Show {
        /// Incident number (for example INC0010001) or a 32-character sys_id
        identifier: String,

        /// Comma-separated fields to return
        #[arg(long)]
        fields: Option<String>,

        /// Return raw values, display values, or both
        #[arg(long, value_enum, default_value = "all")]
        display_value: DisplayValue,
    },

    /// Create an incident
    Create {
        /// Short description
        #[arg(short, long)]
        short_description: String,

        /// Full description
        #[arg(short, long)]
        description: Option<String>,

        /// Category value
        #[arg(long)]
        category: Option<String>,

        /// Impact value
        #[arg(long)]
        impact: Option<String>,

        /// Urgency value
        #[arg(long)]
        urgency: Option<String>,

        /// Assignment group sys_id or accepted display value
        #[arg(long)]
        assignment_group: Option<String>,

        /// Assignee sys_id or accepted display value
        #[arg(long)]
        assignee: Option<String>,

        /// Additional field as name=value; repeatable
        #[arg(long = "field")]
        fields: Vec<String>,
    },

    /// Update an incident
    Update {
        /// Incident number or sys_id
        identifier: String,

        /// New short description
        #[arg(long)]
        short_description: Option<String>,

        /// New description
        #[arg(long)]
        description: Option<String>,

        /// State value
        #[arg(long)]
        state: Option<String>,

        /// Assignee sys_id or accepted display value
        #[arg(long)]
        assignee: Option<String>,

        /// Work note to append
        #[arg(long)]
        work_notes: Option<String>,

        /// Additional field as name=value; repeatable
        #[arg(long = "field")]
        fields: Vec<String>,
    },

    /// Resolve an incident with its required resolution details
    #[command(group(
        ArgGroup::new("resolution_notes")
            .required(true)
            .multiple(false)
            .args(["notes", "notes_file"])
    ))]
    Resolve {
        /// Incident number or sys_id
        identifier: String,

        /// Resolution code value or configured label
        #[arg(long)]
        code: String,

        /// Resolution notes
        #[arg(long)]
        notes: Option<String>,

        /// Read resolution notes from a file, or - for stdin
        #[arg(long, value_name = "PATH")]
        notes_file: Option<std::path::PathBuf>,

        /// Resolved-state value or configured label; inferred from metadata when omitted
        #[arg(long)]
        state: Option<String>,

        /// Additional field as name=value; repeatable
        #[arg(long = "field")]
        fields: Vec<String>,

        /// Refresh incident choices before resolving
        #[arg(long)]
        refresh: bool,

        /// Preview the update without sending it
        #[arg(long)]
        dry_run: bool,
    },

    /// Edit an incident safely in your preferred editor
    Edit {
        /// Incident number or sys_id
        identifier: String,

        /// Read edited YAML from a file instead of opening an editor
        #[arg(long)]
        file: Option<std::path::PathBuf>,

        /// Preview the semantic patch without updating ServiceNow
        #[arg(long)]
        dry_run: bool,

        /// Apply without an interactive confirmation
        #[arg(long)]
        yes: bool,
    },

    /// Append a work note to an incident
    Note {
        /// Incident number or sys_id
        identifier: String,

        /// Work note text
        text: Option<String>,

        /// Read the work note from a file, or - for stdin
        #[arg(long)]
        file: Option<std::path::PathBuf>,

        /// Preview the update without sending it
        #[arg(long)]
        dry_run: bool,
    },

    /// Assign an incident using a user name, email, group name, or sys_id
    Assign {
        /// Incident number or sys_id
        identifier: String,

        /// User name, email, display name, @me, or sys_id
        #[arg(long = "to")]
        assignee: Option<String>,

        /// Assignment group name or sys_id
        #[arg(long)]
        group: Option<String>,

        /// Preview the update without sending it
        #[arg(long)]
        dry_run: bool,
    },

    /// Open an incident in the ServiceNow web interface
    Open {
        /// Incident number or sys_id
        identifier: String,

        /// Print the URL instead of opening a browser
        #[arg(long)]
        print: bool,
    },

    /// Watch an incident and stream field changes
    Watch {
        /// Incident number or sys_id
        identifier: String,

        /// Polling interval in seconds
        #[arg(long, default_value = "5")]
        interval: u64,

        /// Stop after this many polls; omit to watch until Ctrl-C
        #[arg(long)]
        count: Option<usize>,

        /// Comma-separated fields to watch
        #[arg(long)]
        fields: Option<String>,
    },
}

#[derive(Subcommand)]
enum AttachmentsCommand {
    /// List attachments on a record
    List {
        /// Table containing the record, such as incident or change_request
        table: String,

        /// Record number, sys_id, or same-instance form URL
        record: String,

        /// Maximum attachments to return
        #[arg(short = 'n', long, default_value = "100")]
        limit: usize,

        /// Fetch every attachment
        #[arg(long)]
        all: bool,
    },

    /// Upload a file to a record
    Upload {
        /// Table containing the record, such as incident or change_request
        table: String,

        /// Record number, sys_id, or same-instance form URL
        record: String,

        /// Local file to upload
        file: std::path::PathBuf,

        /// Attachment name; defaults to the local file name
        #[arg(long)]
        name: Option<String>,

        /// MIME type; inferred from the file name when omitted
        #[arg(long)]
        content_type: Option<String>,

        /// Preview the upload without sending file contents
        #[arg(long)]
        dry_run: bool,
    },

    /// Download an attachment by sys_id or same-instance Attachment API URL
    Download {
        /// Attachment sys_id or Attachment API URL
        attachment: String,

        /// File path, directory, or - for stdout; defaults to the attachment name
        destination: Option<std::path::PathBuf>,

        /// Replace an existing local file
        #[arg(long)]
        force: bool,
    },

    /// Permanently delete an attachment
    Delete {
        /// Attachment sys_id or same-instance Attachment API URL
        attachment: String,

        /// Confirm deletion without prompting
        #[arg(long)]
        yes: bool,

        /// Preview the deletion without changing ServiceNow
        #[arg(long)]
        dry_run: bool,
    },
}

#[derive(Subcommand)]
enum CatalogCommand {
    /// Search catalog items, including record producers and order guides
    Search {
        /// Text to search for; omit to list the catalog
        text: Option<String>,

        /// Maximum items to return
        #[arg(short = 'n', long, default_value = "20")]
        limit: usize,

        /// Skip the first N items
        #[arg(long, default_value = "0")]
        offset: usize,
    },

    /// Show a catalog item and the variables its form accepts
    Show {
        /// Item sys_id, exact name, or a search term matching one item
        item: String,
    },

    /// Order a catalog item ("order now") after validating its variables
    #[command(
        after_help = "The instance accepts invalid choices, references to the wrong table, and unknown\nvariable names without complaint, so the CLI validates every value first.\nSensitive values belong in --vars-file, not --var. --vars-file - reads them from\nstandard input, which then cannot answer the confirmation prompt: add --yes."
    )]
    Order {
        /// Item sys_id or exact name
        item: String,

        /// Variable value as name=value (repeatable; overrides --vars-file)
        #[arg(long = "var", value_name = "NAME=VALUE")]
        vars: Vec<String>,

        /// JSON or YAML object of variable values, or - for stdin
        #[arg(long, value_name = "PATH")]
        vars_file: Option<std::path::PathBuf>,

        /// Quantity to order
        #[arg(long, default_value = "1")]
        quantity: u32,

        /// User the request is for (user name, email, name, sys_id, or @me)
        #[arg(long)]
        requested_for: Option<String>,

        /// Warn about, and do not send, variables the item does not define
        #[arg(long)]
        allow_unknown_vars: bool,

        /// Order even when your date and time formats cannot be read, so date
        /// variables may be mis-read
        #[arg(long)]
        allow_unverified_formats: bool,

        /// Order through your cart: add the item, then submit the cart. For
        /// instances that answer a plain order with a cart; needs an empty cart
        #[arg(long)]
        checkout: bool,

        /// Validate and show the order without submitting it
        #[arg(long)]
        dry_run: bool,

        /// Submit without prompting
        #[arg(long)]
        yes: bool,
    },

    /// Show, order, or empty your cart (the one the portal shows)
    #[command(subcommand)]
    Cart(CatalogCartCommand),

    /// Track requested items
    #[command(subcommand, visible_alias = "request")]
    Requests(CatalogRequestsCommand),
}

#[derive(Subcommand)]
enum CatalogCartCommand {
    /// List the items in your cart
    #[command(
        after_help = "Reading the cart makes the instance create an empty one when you have none."
    )]
    Show,

    /// Order everything in your cart
    #[command(
        after_help = "The cart is submitted as it is when the instance receives the request, so\nitems added in the portal after the confirmation are ordered too."
    )]
    Submit {
        /// Submit without prompting
        #[arg(long)]
        yes: bool,
    },

    /// Remove one item from your cart
    Remove {
        /// Cart item id, as `catalog cart show` lists it
        cart_item_id: String,

        /// Remove without prompting
        #[arg(long)]
        yes: bool,
    },

    /// Remove every item from your cart
    Clear {
        /// Clear without prompting
        #[arg(long)]
        yes: bool,
    },
}

#[derive(Subcommand)]
enum CatalogRequestsCommand {
    /// List requested items you requested or opened, newest first
    Mine {
        /// Maximum records to return
        #[arg(short = 'n', long, default_value = "20")]
        limit: usize,

        /// Return only items that are still open
        #[arg(long)]
        open: bool,

        /// Return raw values, display values, or both
        #[arg(long, value_enum)]
        display_value: Option<DisplayValue>,
    },

    /// Print a requested item's variables in the form `catalog order --vars-file` accepts
    Vars {
        /// RITM number or sys_id
        identifier: String,

        /// Include variables without a value
        #[arg(long)]
        include_empty: bool,
    },
}

#[derive(Subcommand)]
enum TablesCommand {
    /// List records from a table
    List {
        /// Table name, such as incident or cmdb_ci
        table: String,

        /// ServiceNow encoded query
        #[arg(short, long)]
        query: Option<String>,

        /// Comma-separated fields to return
        #[arg(long)]
        fields: Option<String>,

        /// Maximum records to return
        #[arg(short = 'n', long, default_value = "50")]
        limit: usize,

        /// Skip the first N records
        #[arg(long, default_value = "0")]
        offset: usize,

        /// Fetch all pages
        #[arg(long)]
        all: bool,

        /// Return raw values, display values, or both
        #[arg(long, value_enum, default_value = "false")]
        display_value: DisplayValue,
    },

    /// Get one record by sys_id
    Get {
        table: String,
        sys_id: String,

        /// Comma-separated fields to return
        #[arg(long)]
        fields: Option<String>,

        /// Return raw values, display values, or both
        #[arg(long, value_enum, default_value = "all")]
        display_value: DisplayValue,
    },

    /// Create a record
    Create {
        table: String,

        /// JSON object, or - to read one from stdin
        #[arg(long)]
        data: Option<String>,

        /// Field as name=value; repeatable and overrides --data
        #[arg(long = "field")]
        fields: Vec<String>,
    },

    /// Update a record by sys_id
    Update {
        table: String,
        sys_id: String,

        /// JSON object, or - to read one from stdin
        #[arg(long)]
        data: Option<String>,

        /// Field as name=value; repeatable and overrides --data
        #[arg(long = "field")]
        fields: Vec<String>,
    },

    /// Delete a record by sys_id
    Delete {
        table: String,
        sys_id: String,

        /// Confirm permanent deletion
        #[arg(long)]
        yes: bool,
    },
}

#[derive(Subcommand)]
enum ConfigCommand {
    /// Show resolved configuration with the secret masked
    Show,

    /// Print the config path and an example configuration
    Init,

    /// Print the config file path
    Path,
}

fn parse_tui_page_size(value: &str) -> Result<usize, String> {
    let page_size = value
        .parse::<usize>()
        .map_err(|_| "page size must be a whole number".to_string())?;
    if (5..=200).contains(&page_size) {
        Ok(page_size)
    } else {
        Err("page size must be between 5 and 200".into())
    }
}

/// Decides whether errors are rendered as the machine-readable JSON envelope. Explicit
/// machine formats always are, `text` and `table` never are, and `auto` (or a value that
/// is not a known format) follows `--json` and whether stdout is a terminal, matching
/// `OutputConfig`.
fn machine_readable_errors(output: &str, json_alias: bool) -> bool {
    match output {
        "json" | "jsonl" | "ndjson" | "yaml" | "yml" | "csv" => true,
        "text" | "table" => false,
        _ => json_alias || !std::io::stdout().is_terminal(),
    }
}

/// Recovers `--output` and `--json` from raw arguments when parsing failed and there is no
/// parsed `Cli` to consult, possibly because the `--output` value itself was invalid.
/// Scanning stops at `--`, after which everything is positional.
fn raw_output_flags(args: &[std::ffi::OsString]) -> (String, bool) {
    let mut output = String::from("auto");
    let mut json_alias = false;
    let mut iter = args.iter().skip(1).map(|arg| arg.to_string_lossy());
    while let Some(arg) = iter.next() {
        if arg == "--" {
            break;
        } else if arg == "--json" {
            json_alias = true;
        } else if arg == "--output" || arg == "-o" {
            if let Some(value) = iter.next() {
                output = value.into_owned();
            }
        } else if let Some(value) = arg.strip_prefix("--output=") {
            output = value.to_string();
        } else if let Some(value) = arg.strip_prefix("-o") {
            output = value.strip_prefix('=').unwrap_or(value).to_string();
        }
    }
    (output, json_alias)
}

#[tokio::main]
async fn main() {
    let args: Vec<std::ffi::OsString> = std::env::args_os().collect();
    let cli = match Cli::try_parse_from(&args) {
        Ok(cli) => cli,
        Err(error) => {
            let (output, json_alias) = raw_output_flags(&args);
            // --help and --version render to stdout with exit 0 whatever the format, and
            // human output keeps clap's own colored usage text.
            if !error.use_stderr() || !machine_readable_errors(&output, json_alias) {
                error.exit();
            }
            let parse_error = ApiError::InvalidInput(error.to_string().trim_end().to_string());
            print_error(&parse_error, true);
            std::process::exit(exit_code(&parse_error));
        }
    };
    let machine_errors = machine_readable_errors(&cli.output, cli.json);
    if let Err(error) = run(cli).await {
        print_error(&error, machine_errors);
        std::process::exit(exit_code(&error));
    }
}

async fn run(cli: Cli) -> Result<(), ApiError> {
    let output = OutputConfig::new(&cli.output, cli.json, cli.quiet, cli.no_color)?;
    let verbose = cli.verbose;
    let profile_override = cli.profile.clone();

    match cli.command {
        Command::Init {
            legacy_profile,
            instance,
            method,
            username,
            client_id,
            scope,
            redirect_uri,
            secret_stdin,
            insecure_storage,
            no_browser,
            read_only,
        } => {
            let profile = selected_profile(profile_override.as_deref(), legacy_profile)?
                .unwrap_or_else(|| "default".into());
            let authenticated = run_auth_login(
                &output,
                profile,
                instance,
                method,
                username,
                client_id,
                scope,
                redirect_uri,
                secret_stdin,
                insecure_storage,
                no_browser,
                read_only,
                verbose,
            )
            .await?;
            if authenticated && !output.json {
                outln!("\nNext\n  servicenow doctor\n  servicenow incidents mine");
            }
            return Ok(());
        }
        Command::Auth(AuthCommand::Login {
            legacy_profile,
            instance,
            method,
            username,
            client_id,
            scope,
            redirect_uri,
            secret_stdin,
            insecure_storage,
            no_browser,
            read_only,
        }) => {
            let profile = selected_profile(profile_override.as_deref(), legacy_profile)?
                .unwrap_or_else(|| "default".into());
            run_auth_login(
                &output,
                profile,
                instance,
                method,
                username,
                client_id,
                scope,
                redirect_uri,
                secret_stdin,
                insecure_storage,
                no_browser,
                read_only,
                verbose,
            )
            .await?;
            return Ok(());
        }
        Command::Auth(AuthCommand::Logout { legacy_profile }) => {
            let profile = match selected_profile(profile_override.as_deref(), legacy_profile)? {
                Some(profile) => profile,
                None => active_profile_name()?,
            };
            let removed = delete_stored_credential(&profile)?;
            let value = serde_json::json!({
                "profile": profile,
                "loggedOut": removed,
            });
            if output.json {
                output.value(&value);
            } else if removed {
                outln!("Logged out of profile {profile}.");
            } else {
                outln!("Profile {profile} had no stored credential.");
            }
            return Ok(());
        }
        Command::Profile(ProfileCommand::List) => {
            let profiles = profile_summaries()?;
            if output.json {
                output.value(&serde_json::json!({"result": profiles}));
            } else {
                let records = profiles
                    .into_iter()
                    .map(serde_json::to_value)
                    .collect::<Result<Vec<_>, _>>()
                    .map_err(|error| ApiError::Other(error.to_string()))?;
                print_records_or(
                    &records,
                    None,
                    output.color,
                    "No profiles yet. Start here: `servicenow init`.",
                );
            }
            return Ok(());
        }
        Command::Profile(ProfileCommand::Use { name }) => {
            use_profile(&name)?;
            if output.json {
                output.value(&serde_json::json!({"activeProfile": name}));
            } else {
                outln!("Now using profile {name}.");
            }
            return Ok(());
        }
        Command::Profile(ProfileCommand::Remove { name, yes }) => {
            confirm_destructive(
                yes,
                format!("Remove profile '{name}' and its stored credential?"),
                "profile removal cancelled; use --yes for non-interactive removal",
            )?;
            let credential_removed = delete_stored_credential(&name)?;
            let removed = remove_profile(&name)?;
            if !removed && !credential_removed {
                return Err(ApiError::NotFound(format!("config profile '{name}'")));
            }
            if output.json {
                output.value(&serde_json::json!({"removed": true, "profile": name}));
            } else {
                outln!("Removed profile {name}.");
            }
            return Ok(());
        }
        Command::Schema {
            table: None,
            command,
            ..
        } => {
            let root = Cli::command();
            let schema = if let Some(path) = command {
                let selected = find_command(&root, &path)?;
                command_document(selected, Some(&path))
            } else {
                command_document(&root, None)
            };
            output.value(&schema);
            return Ok(());
        }
        Command::Completions { shell } => {
            let mut command = Cli::command();
            clap_complete::generate(shell, &mut command, "servicenow", &mut output::Stdout);
            return Ok(());
        }
        Command::Tui {
            table,
            query,
            page_size,
        } => {
            if !std::io::stdin().is_terminal() || !std::io::stdout().is_terminal() {
                return Err(ApiError::InvalidInput(
                    "the TUI requires an interactive terminal on stdin and stdout".into(),
                ));
            }
            return run_tui_command(
                &output,
                cli.instance,
                cli.username,
                cli.profile,
                table,
                query,
                page_size,
                verbose,
            )
            .await;
        }
        Command::Config(ConfigCommand::Init) => {
            if output.json {
                output.value(&init_document());
            } else {
                let document = init_document();
                outln!(
                    "Config path: {}",
                    document["configPath"].as_str().unwrap_or("")
                );
                outln!(
                    "\n{}",
                    toml::to_string_pretty(&document["example"])
                        .unwrap_or_else(|_| "[default]\ninstance = \"dev12345\"".into())
                );
                outln!("Next: {}", document["initCommand"].as_str().unwrap_or(""));
            }
            return Ok(());
        }
        Command::Config(ConfigCommand::Path) => {
            if output.json {
                output.value(&serde_json::json!({ "configPath": config_path() }));
            } else {
                outln!("{}", config_path().display());
            }
            return Ok(());
        }
        Command::Auth(AuthCommand::Status { offline: true }) => {
            let config = Config::load(cli.instance, cli.username, cli.profile)?;
            render_offline_auth_status(&config, &output);
            return Ok(());
        }
        Command::Doctor { offline: true } => {
            let config = Config::load(cli.instance, cli.username, cli.profile)?;
            render_offline_doctor(&config, &output);
            return Ok(());
        }
        _ => {}
    }

    let mut config = Config::load(cli.instance, cli.username, cli.profile)?;
    if servicenow_cli::auth::refresh_if_needed(&mut config).await? {
        output.message("OAuth access token refreshed.");
    }
    if matches!(cli.command, Command::Config(ConfigCommand::Show)) {
        let masked = if matches!(config.auth_type, AuthType::Browser) {
            "****".into()
        } else {
            mask_secret(&config.secret)
        };
        let value = serde_json::json!({
            "configPath": config_path(),
            "profile": config.profile,
            "instance": config.instance,
            "username": config.username,
            "authType": config.auth_type.as_str(),
            "secretMasked": masked,
            "readOnly": config.read_only,
        });
        if output.json {
            output.value(&value);
        } else {
            print_record(&value, output.color);
        }
        return Ok(());
    }

    let client = ServiceNowClient::new_with_user_token(
        &config.instance,
        config.username.as_deref(),
        &config.secret,
        config.auth_type,
        config.browser_user_token.as_deref(),
    )?;

    let command_result = match cli.command {
        Command::Tui { .. } => unreachable!("TUI commands return before shared client setup"),
        Command::Incidents(command) => run_incidents(command, &client, &config, &output).await,
        Command::Attachments(command) => run_attachments(command, &client, &config, &output).await,
        Command::Catalog(command) => run_catalog(command, &client, &config, &output).await,
        Command::Tables(command) => run_tables(command, &client, &config, &output).await,
        Command::Schema {
            table: Some(table),
            refresh,
            ..
        } => run_table_schema(&table, refresh, &client, &config, &output).await,
        Command::Choices {
            table,
            field,
            refresh,
        } => run_choices(&table, &field, refresh, &client, &config, &output).await,
        Command::Resolve { kind, value } => metadata::resolve_reference(&client, kind, &value)
            .await
            .map(|record| emit_record(&output, record)),
        Command::Doctor { offline: false } => run_doctor(&client, &config, &output).await,
        Command::Auth(AuthCommand::Status { offline: false }) => {
            run_auth_status(&client, &config, &output).await
        }
        Command::Doctor { offline: true }
        | Command::Init { .. }
        | Command::Auth(_)
        | Command::Profile(_)
        | Command::Config(_)
        | Command::Schema { .. }
        | Command::Completions { .. } => {
            unreachable!()
        }
    };
    if command_result.is_ok()
        && let Some(cookie) = client.refreshed_browser_cookie()
        && let Err(error) = config.persist_browser_cookie(&cookie)
    {
        // The command itself succeeded. Reporting a completed write as a
        // failure invites a retry, which for `catalog order` orders twice.
        // Printed even with --quiet, since later commands may need a login.
        eprintln!(
            "warning: the command succeeded, but the refreshed browser session could not be saved ({error}); run `servicenow auth login` if later commands fail"
        );
    }
    command_result
}

#[allow(clippy::too_many_arguments)]
async fn run_tui_command(
    output: &OutputConfig,
    instance_arg: Option<String>,
    username_arg: Option<String>,
    profile_arg: Option<String>,
    table: String,
    query: Option<String>,
    page_size: usize,
    verbose: bool,
) -> Result<(), ApiError> {
    let options = servicenow_cli::tui::TuiOptions {
        table,
        query,
        page_size,
        color: output.color,
    };
    options.validate()?;
    let requested_profile = profile_arg.unwrap_or(active_profile_name()?);

    loop {
        let mut config = match Config::load(
            instance_arg.clone(),
            username_arg.clone(),
            Some(requested_profile.clone()),
        ) {
            Ok(config) => config,
            Err(error) if tui_login_recoverable(&error) => {
                let saved = profile_defaults(&requested_profile)?;
                let instance_hint = instance_arg
                    .as_deref()
                    .or_else(|| saved.as_ref().map(|profile| profile.instance.as_str()));
                let login_instance = saved.is_none().then(|| instance_arg.clone()).flatten();
                let reason = tui_connection_reason(&error);
                if !request_tui_login(
                    output,
                    &requested_profile,
                    instance_hint,
                    login_instance,
                    username_arg.clone(),
                    &reason,
                    verbose,
                )
                .await?
                {
                    return Ok(());
                }
                continue;
            }
            Err(error) => return Err(error),
        };

        if let Err(error) = servicenow_cli::auth::refresh_if_needed(&mut config).await {
            if !tui_login_recoverable(&error) {
                return Err(error);
            }
            let reason = tui_connection_reason(&error);
            let login_instance = profile_defaults(&config.profile)?
                .is_none()
                .then(|| config.instance.clone());
            if !request_tui_login(
                output,
                &config.profile,
                Some(&config.instance),
                login_instance,
                config.username.clone(),
                &reason,
                verbose,
            )
            .await?
            {
                return Ok(());
            }
            continue;
        }

        let client = ServiceNowClient::new_with_user_token(
            &config.instance,
            config.username.as_deref(),
            &config.secret,
            config.auth_type,
            config.browser_user_token.as_deref(),
        )?;
        let tui_exit = servicenow_cli::tui::run(&client, &config, options.clone()).await?;
        match tui_exit {
            servicenow_cli::tui::TuiExit::Quit => {
                if let Some(cookie) = client.refreshed_browser_cookie() {
                    config.persist_browser_cookie(&cookie)?;
                }
                return Ok(());
            }
            servicenow_cli::tui::TuiExit::Authenticate => {
                let login_instance = profile_defaults(&config.profile)?
                    .is_none()
                    .then(|| config.instance.clone());
                if !request_tui_login(
                    output,
                    &config.profile,
                    Some(&config.instance),
                    login_instance,
                    config.username.clone(),
                    "ServiceNow rejected the current session. Sign in again to continue where you left off.",
                    verbose,
                )
                .await?
                {
                    return Ok(());
                }
            }
        }
    }
}

#[allow(clippy::too_many_arguments)]
async fn request_tui_login(
    output: &OutputConfig,
    profile: &str,
    instance_hint: Option<&str>,
    login_instance: Option<String>,
    username: Option<String>,
    reason: &str,
    verbose: bool,
) -> Result<bool, ApiError> {
    if servicenow_cli::tui::request_authentication(profile, instance_hint, reason, output.color)?
        == servicenow_cli::tui::TuiExit::Quit
    {
        return Ok(false);
    }

    let auth_output = OutputConfig {
        json: false,
        quiet: false,
        format: OutputFormat::Text,
        color: output.color,
    };
    run_auth_login(
        &auth_output,
        profile.to_string(),
        login_instance,
        None,
        username,
        None,
        None,
        None,
        false,
        false,
        false,
        false,
        verbose,
    )
    .await
}

fn tui_login_recoverable(error: &ApiError) -> bool {
    if matches!(error, ApiError::Auth(_)) {
        return true;
    }
    let message = error.to_string();
    matches!(error, ApiError::InvalidInput(_) | ApiError::NotFound(_))
        && [
            "No ServiceNow instance configured",
            "No username configured",
            "No password configured",
            "No browser session configured",
            "No access token configured",
            "config profile '",
            "OAuth profile is missing client_id",
        ]
        .iter()
        .any(|marker| message.contains(marker))
}

fn tui_connection_reason(error: &ApiError) -> String {
    let message = error.to_string();
    if message.contains("No ServiceNow instance configured") {
        "No ServiceNow instance is connected to this profile yet.".into()
    } else if message.contains("config profile '") {
        "This profile has not been connected yet.".into()
    } else if message.contains("No username configured")
        || message.contains("No password configured")
        || message.contains("No browser session configured")
        || message.contains("No access token configured")
    {
        "This profile does not have a usable credential yet.".into()
    } else {
        message
    }
}

async fn run_table_schema(
    table: &str,
    refresh: bool,
    client: &ServiceNowClient,
    config: &Config,
    output: &OutputConfig,
) -> Result<(), ApiError> {
    let metadata = if refresh {
        metadata::sync_table(client, &config.profile, table).await?
    } else if let Some(metadata) = metadata::load(&config.profile, table)? {
        metadata
    } else {
        output.message("No cached metadata found; fetching it from the instance.");
        metadata::sync_table(client, &config.profile, table).await?
    };
    if output.json {
        output.value(&serde_json::json!({"result": metadata}));
    } else {
        outln!(
            "{}  {} fields  {} choice fields\n",
            output.heading(&metadata.table),
            metadata.fields.len(),
            metadata.choices.len()
        );
        let records = metadata::metadata_as_records(&metadata);
        let fields = [
            "field".into(),
            "label".into(),
            "type".into(),
            "reference".into(),
            "mandatory".into(),
            "read_only".into(),
            "choices".into(),
        ];
        print_records(&records, Some(&fields), output.color);
    }
    Ok(())
}

async fn run_choices(
    table: &str,
    field: &str,
    refresh: bool,
    client: &ServiceNowClient,
    config: &Config,
    output: &OutputConfig,
) -> Result<(), ApiError> {
    let metadata = if refresh {
        metadata::sync_table(client, &config.profile, table).await?
    } else if let Some(metadata) = metadata::load(&config.profile, table)? {
        metadata
    } else {
        metadata::sync_table(client, &config.profile, table).await?
    };
    if metadata.field(field).is_none() {
        return Err(ApiError::NotFound(format!("field {table}.{field}")));
    }
    let choices = metadata.choices.get(field).cloned().unwrap_or_default();
    if output.json {
        output.value(&serde_json::json!({
            "table": table,
            "field": field,
            "result": choices,
        }));
    } else if choices.is_empty() {
        outln!("No configured choices for {table}.{field}.");
    } else {
        let records = choices
            .into_iter()
            .map(serde_json::to_value)
            .collect::<Result<Vec<_>, _>>()
            .map_err(|error| ApiError::Other(error.to_string()))?;
        print_records(
            &records,
            Some(&["value".into(), "label".into(), "sequence".into()]),
            output.color,
        );
    }
    Ok(())
}

#[allow(clippy::too_many_arguments)]
async fn run_auth_login(
    output: &OutputConfig,
    profile: String,
    instance: Option<String>,
    method: Option<AuthType>,
    username: Option<String>,
    client_id: Option<String>,
    scope: Option<String>,
    redirect_uri: Option<String>,
    secret_stdin: bool,
    insecure_storage: bool,
    no_browser: bool,
    read_only: bool,
    verbose: bool,
) -> Result<bool, ApiError> {
    servicenow_cli::config::validate_profile_name(&profile)?;
    if output.format == OutputFormat::Text && std::io::stdin().is_terminal() {
        output.message(&format!(
            "{}\n  Secure sign-in, tailored to your instance.",
            output.heading("Connect to ServiceNow")
        ));
    }
    let saved = if instance.is_none() {
        profile_defaults(&profile)?
    } else {
        None
    };
    let resumed = saved.is_some();
    let instance = required_prompt(
        instance.or_else(|| saved.as_ref().map(|value| value.instance.clone())),
        "ServiceNow instance",
    )?;
    let method = method.or(saved
        .as_ref()
        .and_then(|value| value.auth_type.as_deref())
        .map(str::parse)
        .transpose()?);
    let username = username.or_else(|| saved.as_ref().and_then(|value| value.username.clone()));
    let client_id = client_id.or_else(|| saved.as_ref().and_then(|value| value.client_id.clone()));
    let scope = scope
        .or_else(|| saved.as_ref().and_then(|value| value.oauth_scope.clone()))
        .unwrap_or_else(|| "useraccount".into());
    let redirect_uri = redirect_uri
        .or_else(|| saved.as_ref().and_then(|value| value.redirect_uri.clone()))
        .unwrap_or_else(|| "http://127.0.0.1:8484/callback".into());
    let read_only = read_only
        || saved
            .as_ref()
            .and_then(|value| value.read_only)
            .unwrap_or(false);
    if resumed {
        output.success(&format!("Resuming profile '{profile}'"));
    }
    let method = resolve_auth_method(output, &instance, method, client_id.as_deref()).await?;
    let mut username = username;
    if matches!(method, AuthType::Basic) {
        username = Some(required_prompt(username, "Username")?);
    }
    let configured_client_id = if matches!(method, AuthType::OAuth) {
        if client_id
            .as_deref()
            .is_none_or(|value| value.trim().is_empty())
        {
            print_oauth_admin_request(output, &redirect_uri);
            if std::io::stdin().is_terminal() {
                let ready = Confirm::new()
                    .with_prompt("Do you have the client ID ready?")
                    .default(true)
                    .interact()
                    .map_err(|error| {
                        ApiError::Other(format!("failed to confirm OAuth readiness: {error}"))
                    })?;
                if !ready {
                    save_oauth_draft(&profile, &instance, &scope, &redirect_uri, read_only)?;
                    let resume_command = format!("servicenow auth login {profile}");
                    if output.json {
                        output.value(&serde_json::json!({
                            "profile": profile,
                            "instance": instance,
                            "authType": "oauth",
                            "authenticated": false,
                            "status": "awaiting-client-id",
                            "resumeCommand": resume_command,
                        }));
                    } else {
                        output.success("Setup saved—no credential was stored");
                        outln!(
                            "\nWhen your administrator sends the client ID, continue with:\n  {resume_command} --client-id YOUR_CLIENT_ID"
                        );
                    }
                    return Ok(false);
                }
            }
        }
        Some(required_prompt(client_id, "OAuth client ID")?)
    } else {
        None
    };
    let file_storage = if matches!(method, AuthType::Browser) {
        None
    } else {
        Some(choose_credential_storage(insecure_storage)?)
    };
    let mut credential = match method {
        AuthType::Basic => StoredCredential::Basic {
            password: read_login_secret(secret_stdin, "Password", false)?,
        },
        AuthType::Browser => {
            if secret_stdin {
                return Err(ApiError::InvalidInput(
                    "browser sign-in cannot be read from stdin; remove --secret-stdin".into(),
                ));
            }
            if !no_browser {
                output.message("\nOpening a private browser window for ServiceNow…");
                output.message(
                    "Complete your normal SSO sign-in there. This CLI never receives your identity-provider password.",
                );
            }
            let spinner = if verbose {
                output.message(
                    "Verbose browser diagnostics enabled; secrets, URLs, and page content are redacted.",
                );
                None
            } else {
                OnboardingSpinner::start(
                    output,
                    "Waiting for ServiceNow to complete the secure browser handoff",
                )
            };
            let credential = if verbose {
                let started = std::time::Instant::now();
                servicenow_cli::browser::browser_login_with_progress(
                    &instance,
                    !no_browser,
                    |progress| {
                        eprintln!(
                            "[+{:>6.1}s] browser: {}",
                            started.elapsed().as_secs_f64(),
                            progress.message()
                        );
                    },
                )
                .await
            } else {
                servicenow_cli::browser::browser_login(&instance, !no_browser).await
            };
            drop(spinner);
            credential?
        }
        AuthType::Bearer => StoredCredential::Bearer {
            access_token: read_login_secret(secret_stdin, "Access token", false)?,
        },
        AuthType::OAuth => {
            let id = configured_client_id
                .as_deref()
                .expect("OAuth client ID was collected before reading credentials");
            let client_secret = read_login_secret(
                secret_stdin,
                "OAuth client secret (optional; press Enter to skip)",
                true,
            )?;
            servicenow_cli::auth::oauth_login(
                &instance,
                id,
                (!client_secret.is_empty()).then_some(client_secret),
                Some(&scope),
                &redirect_uri,
                !no_browser,
            )
            .await?
        }
    };
    let browser_user_token = match &credential {
        StoredCredential::Browser { user_token, .. } => Some(user_token.as_str()),
        _ => None,
    };
    let client = ServiceNowClient::new_with_user_token(
        &instance,
        username.as_deref(),
        credential.secret(),
        method,
        browser_user_token,
    )?;
    let users = match client
        .list_records(
            "sys_user",
            &ListOptions {
                query: Some("sys_id=javascript:gs.getUserID()".into()),
                fields: Some(vec!["sys_id".into(), "user_name".into(), "name".into()]),
                limit: 1,
                ..ListOptions::default()
            },
        )
        .await
    {
        Ok(users) => users,
        Err(error) if matches!(method, AuthType::Basic) && matches!(error, ApiError::Auth(_)) => {
            return Err(enrich_basic_auth_error(&instance, error).await);
        }
        Err(error) => return Err(error),
    };
    let mut browser_identity = None;
    if let Some(user) = users.first() {
        username = field_text(user, "user_name").or(username);
        if matches!(method, AuthType::Browser) {
            let name = field_text(user, "name");
            browser_identity = match (name.as_deref(), username.as_deref()) {
                (Some(name), Some(username)) if name != username => {
                    Some(format!("{name} ({username})"))
                }
                (Some(name), _) => Some(name.into()),
                (_, Some(username)) => Some(username.into()),
                _ => None,
            };
        }
    }
    if matches!(method, AuthType::Browser) {
        let identity = browser_identity.unwrap_or_else(|| "your ServiceNow account".into());
        if output.format == OutputFormat::Text {
            output.success(&format!("Browser sign-in complete as {identity}"));
        }
        if let Some(cookie) = client.refreshed_browser_cookie()
            && let StoredCredential::Browser {
                cookie: stored_cookie,
                ..
            } = &mut credential
        {
            *stored_cookie = cookie;
        }
    }

    let file_storage = match file_storage {
        Some(file_storage) => file_storage,
        None => choose_credential_storage(insecure_storage)?,
    };

    let mut profile_config = ProfileConfig::default();
    profile_config.instance = Some(instance);
    profile_config.username = username.clone();
    profile_config.auth_type = Some(method.as_str().into());
    profile_config.read_only = Some(read_only);
    profile_config.credential_store = Some(if file_storage { "file" } else { "keyring" }.into());
    profile_config.credential = file_storage.then_some(credential.clone());
    profile_config.client_id = configured_client_id;
    profile_config.oauth_scope = matches!(method, AuthType::OAuth).then_some(scope);
    profile_config.redirect_uri = matches!(method, AuthType::OAuth).then_some(redirect_uri);
    if !file_storage {
        credentials::store(&profile, &credential)?;
    }
    if let Err(error) = save_profile(&profile, profile_config, true) {
        if !file_storage {
            let _ = credentials::delete(&profile);
        }
        return Err(error);
    }

    let result = serde_json::json!({
        "profile": profile,
        "instance": client.site_url(),
        "username": username,
        "authType": method.as_str(),
        "readOnly": read_only,
        "credentialStore": if file_storage { "config-file" } else { "os-keychain" },
        "authenticated": true,
    });
    if output.json {
        output.value(&result);
    } else {
        output.success("Connected to ServiceNow");
        outln!("\n{}", output.heading("Connection"));
        outln!(
            "  Profile      {}",
            result["profile"].as_str().unwrap_or("")
        );
        outln!(
            "  Instance     {}",
            result["instance"].as_str().unwrap_or("")
        );
        outln!(
            "  User         {}",
            result["username"].as_str().unwrap_or("")
        );
        outln!(
            "  Auth         {}",
            result["authType"].as_str().unwrap_or("")
        );
        outln!(
            "  Safety       {}",
            if read_only {
                "read-only"
            } else {
                "writes enabled"
            }
        );
        outln!(
            "  Credentials  {}",
            if file_storage {
                "config file (plaintext, mode 0600)"
            } else {
                "OS keychain"
            }
        );
    }
    Ok(true)
}

fn print_oauth_admin_request(output: &OutputConfig, redirect_uri: &str) {
    let heading = output.heading("ServiceNow OAuth app required");
    output.message(&format!(
        "\n{heading}\n\nAsk your ServiceNow administrator:\n\n  Please create an OAuth API endpoint for external clients under\n  System OAuth → Application Registry for the ServiceNow CLI, and\n  register this redirect URI:\n\n    {redirect_uri}\n\n  Then send me the client ID.\n\nMicrosoft Entra remains the browser sign-in; the OAuth app itself is\nconfigured in ServiceNow."
    ));
}

async fn enrich_basic_auth_error(instance: &str, error: ApiError) -> ApiError {
    let ApiError::Auth(message) = error else {
        return error;
    };
    match servicenow_cli::auth::discover_login_provider(instance).await {
        Ok(servicenow_cli::auth::LoginProvider::MicrosoftEntra) => ApiError::Auth(format!(
            "Basic authentication was rejected, and this instance appears to use Microsoft Entra SSO. Federated accounts usually do not have a usable ServiceNow password. Use browser sign-in instead; it needs no OAuth application or administrator setup. ServiceNow response: {message}"
        )),
        Ok(servicenow_cli::auth::LoginProvider::ExternalSso(host)) => {
            let provider = host
                .map(|host| format!(" through {host}"))
                .unwrap_or_default();
            ApiError::Auth(format!(
                "Basic authentication was rejected, and this instance appears to use external SSO{provider}. Federated accounts usually do not have a usable ServiceNow password. Use browser sign-in instead; it needs no OAuth application or administrator setup. ServiceNow response: {message}"
            ))
        }
        _ => ApiError::Auth(message),
    }
}

fn save_oauth_draft(
    profile: &str,
    instance: &str,
    scope: &str,
    redirect_uri: &str,
    read_only: bool,
) -> Result<(), ApiError> {
    let mut draft = ProfileConfig::default();
    draft.instance = Some(instance.into());
    draft.auth_type = Some("oauth".into());
    draft.read_only = Some(read_only);
    draft.oauth_scope = Some(scope.into());
    draft.redirect_uri = Some(redirect_uri.into());
    save_profile(profile, draft, true)
}

async fn resolve_auth_method(
    output: &OutputConfig,
    instance: &str,
    explicit: Option<AuthType>,
    client_id: Option<&str>,
) -> Result<AuthType, ApiError> {
    if let Some(method) = explicit {
        return Ok(method);
    }
    if client_id.is_some_and(|value| !value.trim().is_empty()) {
        return Ok(AuthType::OAuth);
    }
    let spinner = OnboardingSpinner::start(output, "Checking how this instance signs users in");
    if spinner.is_none() {
        output.message("Checking how this instance signs users in…");
    }
    let discovery = servicenow_cli::auth::discover_login_provider(instance).await;
    drop(spinner);
    match discovery {
        Ok(servicenow_cli::auth::LoginProvider::MicrosoftEntra) => {
            output.success("Microsoft Entra SSO detected");
            output.message(
                "Sign in through your browser—no ServiceNow password or OAuth application is required.",
            );
            Ok(AuthType::Browser)
        }
        Ok(servicenow_cli::auth::LoginProvider::ExternalSso(host)) => {
            let provider = host
                .as_deref()
                .map(|host| format!("External SSO detected ({host})"))
                .unwrap_or_else(|| "External SSO detected".into());
            output.success(&provider);
            output.message(
                "Sign in through your browser—no identity-provider password is entered into this CLI.",
            );
            Ok(AuthType::Browser)
        }
        Ok(servicenow_cli::auth::LoginProvider::Undetermined)
            if std::io::stdin().is_terminal() =>
        {
            output.message(
                "No SSO redirect was detected. A ServiceNow login page does not prove that your account has a local password.",
            );
            select_auth_method()
        }
        Ok(servicenow_cli::auth::LoginProvider::Undetermined) => Err(ApiError::InvalidInput(
            "the instance did not expose a definitive login method; pass --method browser, basic, oauth, or bearer"
                .into(),
        )),
        Err(error) if std::io::stdin().is_terminal() => {
            output.message(&format!(
                "Could not identify the login method automatically ({error})."
            ));
            select_auth_method()
        }
        Err(error) => Err(ApiError::InvalidInput(format!(
            "could not auto-detect the authentication method ({error}); pass --method browser, basic, oauth, or bearer"
        ))),
    }
}

struct OnboardingSpinner {
    running: std::sync::Arc<std::sync::atomic::AtomicBool>,
    handle: Option<std::thread::JoinHandle<()>>,
}

impl OnboardingSpinner {
    fn start(output: &OutputConfig, message: &str) -> Option<Self> {
        if output.quiet || output.format != OutputFormat::Text || !std::io::stderr().is_terminal() {
            return None;
        }
        let running = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true));
        let thread_running = running.clone();
        let message = message.to_string();
        let handle = std::thread::spawn(move || {
            let frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
            let mut frame = 0;
            while thread_running.load(std::sync::atomic::Ordering::Relaxed) {
                eprint!("\r{} {message}", frames[frame % frames.len()]);
                let _ = std::io::stderr().flush();
                frame += 1;
                std::thread::sleep(std::time::Duration::from_millis(80));
            }
        });
        Some(Self {
            running,
            handle: Some(handle),
        })
    }
}

impl Drop for OnboardingSpinner {
    fn drop(&mut self) {
        self.running
            .store(false, std::sync::atomic::Ordering::Relaxed);
        if let Some(handle) = self.handle.take() {
            let _ = handle.join();
        }
        eprint!("\r{:width$}\r", "", width = 72);
        let _ = std::io::stderr().flush();
    }
}

fn select_auth_method() -> Result<AuthType, ApiError> {
    let options = [
        "Browser sign-in (SSO, no administrator setup)",
        "Managed OAuth application",
        "ServiceNow username and password",
        "Access token",
    ];
    let selected = Select::new()
        .with_prompt("How do you sign in?")
        .items(options)
        .default(0)
        .interact()
        .map_err(|error| ApiError::Other(format!("failed to choose authentication: {error}")))?;
    Ok(match selected {
        0 => AuthType::Browser,
        1 => AuthType::OAuth,
        2 => AuthType::Basic,
        _ => AuthType::Bearer,
    })
}

fn choose_credential_storage(insecure_storage: bool) -> Result<bool, ApiError> {
    if insecure_storage {
        eprintln!(
            "warning: the credential will be stored in plaintext in {} (protected with mode 0600 on Unix)",
            config_path().display()
        );
        return Ok(true);
    }
    match credentials::available() {
        Ok(()) => Ok(false),
        Err(error) => {
            eprintln!(
                "warning: {error}; storing the credential in plaintext in {} (protected with mode 0600 on Unix)",
                config_path().display()
            );
            Ok(true)
        }
    }
}

fn required_prompt(value: Option<String>, prompt: &str) -> Result<String, ApiError> {
    if let Some(value) = value.filter(|value| !value.trim().is_empty()) {
        return Ok(value.trim().into());
    }
    if !std::io::stdin().is_terminal() {
        return Err(ApiError::InvalidInput(format!(
            "{prompt} is required in non-interactive mode"
        )));
    }
    Input::<String>::new()
        .with_prompt(prompt)
        .interact_text()
        .map_err(|error| ApiError::Other(format!("failed to read {prompt}: {error}")))
        .and_then(|value| {
            (!value.trim().is_empty())
                .then(|| value.trim().into())
                .ok_or_else(|| ApiError::InvalidInput(format!("{prompt} cannot be empty")))
        })
}

fn read_login_secret(
    from_stdin: bool,
    prompt: &str,
    allow_empty: bool,
) -> Result<String, ApiError> {
    let value = if from_stdin {
        let mut value = String::new();
        std::io::stdin()
            .read_to_string(&mut value)
            .map_err(|error| ApiError::Other(format!("failed to read secret: {error}")))?;
        value.trim_end_matches(['\r', '\n']).to_string()
    } else {
        if !std::io::stdin().is_terminal() {
            return Err(ApiError::InvalidInput(format!(
                "{prompt} requires --secret-stdin in non-interactive mode"
            )));
        }
        Password::new()
            .with_prompt(prompt)
            .allow_empty_password(allow_empty)
            .interact()
            .map_err(|error| ApiError::Other(format!("failed to read {prompt}: {error}")))?
    };
    if value.is_empty() && !allow_empty {
        Err(ApiError::InvalidInput(format!("{prompt} cannot be empty")))
    } else {
        Ok(value)
    }
}

fn credential_detail(config: &Config) -> &'static str {
    match config.credential_store() {
        "config-file" => "config file (plaintext, mode 0600)",
        "os-keychain" => "OS keychain",
        "environment" => "environment variable",
        "legacy-config" => "legacy plaintext config field",
        _ => "unknown",
    }
}

/// Confirms a destructive, irreversible action the same way at every call site: `--yes`
/// skips the prompt outright, an interactive terminal gets a dialoguer confirmation
/// defaulting to "no", and anything else (piped or non-interactive stdin without `--yes`)
/// is refused rather than silently assumed.
fn confirm_destructive(yes: bool, prompt: String, cancelled_message: &str) -> Result<(), ApiError> {
    let confirmed = yes
        || (std::io::stdin().is_terminal()
            && Confirm::new()
                .with_prompt(prompt)
                .default(false)
                .interact()
                .map_err(|error| ApiError::Other(format!("failed to confirm: {error}")))?);
    if confirmed {
        Ok(())
    } else {
        Err(ApiError::InvalidInput(cancelled_message.into()))
    }
}

fn selected_profile(
    profile_override: Option<&str>,
    legacy_profile: Option<String>,
) -> Result<Option<String>, ApiError> {
    match (profile_override, legacy_profile) {
        (Some(_), Some(_)) => Err(ApiError::InvalidInput(
            "provide the profile with --profile or the legacy positional argument, not both".into(),
        )),
        (Some(profile), None) => Ok(Some(profile.into())),
        (None, legacy_profile) => Ok(legacy_profile),
    }
}

fn render_offline_auth_status(config: &Config, output: &OutputConfig) {
    let value = serde_json::json!({
        "profile": config.profile,
        "status": "configured",
        "verified": false,
        "instance": config.instance,
        "authType": config.auth_type.as_str(),
        "credentialStore": config.credential_store(),
    });
    if output.json {
        output.value(&value);
    } else {
        outln!(
            "Profile: {}\nStatus: configured (network not checked)\nAuthentication: {}\nCredentials: {}",
            config.profile,
            config.auth_type.as_str(),
            credential_detail(config)
        );
    }
}

fn render_offline_doctor(config: &Config, output: &OutputConfig) {
    let checks = serde_json::json!([
        {"name": "configuration", "ok": true, "detail": config.instance},
        {"name": "credentials", "ok": true, "detail": credential_detail(config)},
        {"name": "authentication", "skipped": true, "detail": "network check skipped"},
        {"name": "table_api", "skipped": true, "detail": "network check skipped"},
        {"name": "write_safety", "ok": true, "detail": if config.read_only { "read-only mode enabled" } else { "write operations enabled" }}
    ]);
    if output.json {
        output.value(&serde_json::json!({
            "ok": true,
            "offline": true,
            "verified": false,
            "checks": checks
        }));
    } else {
        outln!("ServiceNow connection (offline)\n");
        for check in checks.as_array().expect("checks are an array") {
            let marker = if check["skipped"].as_bool().unwrap_or(false) {
                "–"
            } else {
                "✓"
            };
            outln!(
                "  {marker} {:<16} {}",
                check["name"].as_str().unwrap_or("check"),
                check["detail"].as_str().unwrap_or("")
            );
        }
    }
}

async fn run_auth_status(
    client: &ServiceNowClient,
    config: &Config,
    output: &OutputConfig,
) -> Result<(), ApiError> {
    let users = client
        .list_records(
            "sys_user",
            &ListOptions {
                query: Some("sys_id=javascript:gs.getUserID()".into()),
                fields: Some(vec!["sys_id".into(), "user_name".into(), "name".into()]),
                limit: 1,
                ..ListOptions::default()
            },
        )
        .await?;
    let user = users.first().ok_or_else(|| {
        ApiError::Other("authentication succeeded, but the current user was not returned".into())
    })?;
    let username = field_text(user, "user_name")
        .or_else(|| field_text(user, "name"))
        .unwrap_or_else(|| "unknown".into());
    let value = serde_json::json!({
        "profile": config.profile,
        "status": "ok",
        "verified": true,
        "identity": username,
        "instance": config.instance,
        "authType": config.auth_type.as_str(),
        "credentialStore": config.credential_store(),
    });
    if output.json {
        output.value(&value);
    } else {
        outln!(
            "Authenticated as {} ({}, {})",
            value["identity"].as_str().unwrap_or("unknown"),
            config.auth_type.as_str(),
            credential_detail(config)
        );
    }
    Ok(())
}

async fn run_doctor(
    client: &ServiceNowClient,
    config: &Config,
    output: &OutputConfig,
) -> Result<(), ApiError> {
    let users = client
        .list_records(
            "sys_user",
            &ListOptions {
                query: Some("sys_id=javascript:gs.getUserID()".into()),
                fields: Some(vec![
                    "sys_id".into(),
                    "user_name".into(),
                    "name".into(),
                    "active".into(),
                ]),
                limit: 1,
                ..ListOptions::default()
            },
        )
        .await?;
    let user = users.first().ok_or_else(|| {
        ApiError::Other("authentication succeeded, but the current user was not returned".into())
    })?;
    let username = field_text(user, "user_name").unwrap_or_else(|| "unknown".into());

    client
        .list_records(
            "incident",
            &ListOptions {
                fields: Some(vec!["sys_id".into(), "number".into()]),
                limit: 1,
                ..ListOptions::default()
            },
        )
        .await?;

    let credential_detail = credential_detail(config);
    let checks = serde_json::json!([
        {"name": "configuration", "ok": true, "detail": config.instance},
        {"name": "authentication", "ok": true, "detail": username},
        {"name": "credentials", "ok": true, "detail": credential_detail},
        {"name": "table_api", "ok": true, "detail": "incident table is readable"},
        {
            "name": "write_safety",
            "ok": true,
            "detail": if config.read_only { "read-only mode enabled" } else { "write operations enabled" }
        }
    ]);
    let result = serde_json::json!({
        "ok": true,
        "instance": client.site_url(),
        "checks": checks,
    });
    if output.json {
        output.value(&result);
    } else {
        outln!("ServiceNow connection\n");
        for check in result["checks"].as_array().expect("checks are an array") {
            outln!(
                "  ✓ {:<16} {}",
                check["name"].as_str().unwrap_or("check"),
                check["detail"].as_str().unwrap_or("")
            );
        }
        outln!("\nReady.");
    }
    Ok(())
}

async fn run_incidents(
    command: IncidentsCommand,
    client: &ServiceNowClient,
    config: &Config,
    output: &OutputConfig,
) -> Result<(), ApiError> {
    match command {
        IncidentsCommand::List {
            query,
            active,
            limit,
            offset,
            all,
            fields,
            display_value,
        } => {
            let query = combine_query(active.then_some("active=true"), query.as_deref());
            let custom_fields = fields.is_some();
            let fields = parse_fields(fields.as_deref()).or_else(|| {
                Some(
                    INCIDENT_LIST_FIELDS
                        .iter()
                        .map(|field| (*field).into())
                        .collect(),
                )
            });
            let records = client
                .list_records(
                    "incident",
                    &ListOptions {
                        query,
                        fields: fields.clone(),
                        limit,
                        offset,
                        all,
                        display_value: display_value.unwrap_or_else(|| {
                            if output.format == OutputFormat::Text {
                                DisplayValue::True
                            } else {
                                DisplayValue::False
                            }
                        }),
                    },
                )
                .await?;
            let human_fields: Vec<String> = INCIDENT_HUMAN_FIELDS
                .iter()
                .map(|field| (*field).into())
                .collect();
            let visible_fields = if custom_fields {
                fields.as_deref()
            } else {
                Some(human_fields.as_slice())
            };
            emit_records_or(
                output,
                records,
                visible_fields,
                "No incidents matched. Try broadening --query or removing --active.",
            );
        }
        IncidentsCommand::Mine {
            query,
            limit,
            all,
            display_value,
        } => {
            let query = combine_query(
                Some("assigned_to=javascript:gs.getUserID()"),
                query.as_deref(),
            );
            let fields: Vec<String> = INCIDENT_LIST_FIELDS
                .iter()
                .map(|field| (*field).into())
                .collect();
            let records = client
                .list_records(
                    "incident",
                    &ListOptions {
                        query,
                        fields: Some(fields.clone()),
                        limit,
                        all,
                        display_value: display_value.unwrap_or_else(|| {
                            if output.format == OutputFormat::Text {
                                DisplayValue::True
                            } else {
                                DisplayValue::False
                            }
                        }),
                        ..ListOptions::default()
                    },
                )
                .await?;
            let human_fields: Vec<String> = INCIDENT_HUMAN_FIELDS
                .iter()
                .map(|field| (*field).into())
                .collect();
            emit_records_or(
                output,
                records,
                Some(&human_fields),
                "Nothing is assigned to you. You’re clear for now. Explore with `servicenow incidents list --active`.",
            );
        }
        IncidentsCommand::Show {
            identifier,
            fields,
            display_value,
        } => {
            let fields = parse_fields(fields.as_deref());
            let record =
                resolve_incident(client, &identifier, fields.clone(), display_value).await?;
            emit_record(output, record);
        }
        IncidentsCommand::Create {
            short_description,
            description,
            category,
            impact,
            urgency,
            assignment_group,
            assignee,
            fields,
        } => {
            config.require_writable()?;
            let mut body = build_body(None, &fields)?;
            insert(&mut body, "short_description", Some(short_description));
            insert(&mut body, "description", description);
            insert(&mut body, "category", category);
            insert(&mut body, "impact", impact);
            insert(&mut body, "urgency", urgency);
            insert(
                &mut body,
                "assignment_group",
                resolve_reference_id(client, ReferenceKind::Group, assignment_group).await?,
            );
            insert(
                &mut body,
                "assigned_to",
                resolve_reference_id(client, ReferenceKind::User, assignee).await?,
            );
            let record = client.create_record("incident", &body).await?;
            output.success("Incident created.");
            emit_record(output, record);
        }
        IncidentsCommand::Update {
            identifier,
            short_description,
            description,
            state,
            assignee,
            work_notes,
            fields,
        } => {
            config.require_writable()?;
            let mut body = build_body(None, &fields)?;
            insert(&mut body, "short_description", short_description);
            insert(&mut body, "description", description);
            insert(&mut body, "state", state);
            insert(
                &mut body,
                "assigned_to",
                resolve_reference_id(client, ReferenceKind::User, assignee).await?,
            );
            insert(&mut body, "work_notes", work_notes);
            if body.is_empty() {
                return Err(ApiError::InvalidInput(
                    "at least one field must be supplied".into(),
                ));
            }
            let existing = resolve_incident(
                client,
                &identifier,
                Some(vec!["sys_id".into()]),
                DisplayValue::False,
            )
            .await?;
            let sys_id = record_sys_id(&existing)?.to_string();
            let record = client.update_record("incident", &sys_id, &body).await?;
            output.success("Incident updated.");
            emit_record(output, record);
        }
        IncidentsCommand::Resolve {
            identifier,
            code,
            notes,
            notes_file,
            state,
            fields,
            refresh,
            dry_run,
        } => {
            let notes = match (notes, notes_file) {
                (Some(notes), None) => notes,
                (None, Some(path)) => read_file_or_stdin(&path, "resolution notes")?,
                (Some(_), Some(_)) => unreachable!("clap rejects conflicting note inputs"),
                (None, None) => {
                    return Err(ApiError::InvalidInput(
                        "resolution notes are required; provide --notes or --notes-file".into(),
                    ));
                }
            };
            incident::require_resolution_input(&code, &notes)?;
            let mut body = build_body(None, &fields)?;
            for reserved in ["state", "close_code", "close_notes"] {
                if body.contains_key(reserved) {
                    return Err(ApiError::InvalidInput(format!(
                        "--field {reserved}=... conflicts with the dedicated resolution option"
                    )));
                }
            }
            if !dry_run {
                config.require_writable()?;
            }
            let metadata = if refresh {
                metadata::sync_table(client, &config.profile, "incident").await?
            } else if let Some(metadata) = metadata::load(&config.profile, "incident")? {
                metadata
            } else {
                metadata::sync_table(client, &config.profile, "incident").await?
            };
            let resolution = incident::resolution_body(&metadata, &code, notes, state.as_deref())?;
            let resolved_state = resolution["state"]
                .as_str()
                .expect("resolution state is a string")
                .to_string();
            body.extend(resolution);

            let existing = resolve_incident(
                client,
                &identifier,
                Some(vec!["sys_id".into(), "number".into(), "state".into()]),
                DisplayValue::All,
            )
            .await?;
            incident::require_resolvable(&existing, &resolved_state, &metadata)?;
            if dry_run {
                emit_mutation_plan(output, "resolve", &identifier, &body);
                return Ok(());
            }
            let record = client
                .update_record("incident", record_sys_id(&existing)?, &body)
                .await?;
            output.success(&format!("Resolved {identifier}."));
            emit_record(output, record);
        }
        IncidentsCommand::Edit {
            identifier,
            file,
            dry_run,
            yes,
        } => {
            let existing = resolve_incident(client, &identifier, None, DisplayValue::All).await?;
            let sys_id = record_sys_id(&existing)?.to_string();
            let original = incident::edit_document(
                &existing,
                metadata::load(&config.profile, "incident")?.as_ref(),
            )?;
            let edited = match file {
                Some(path) => read_file_or_stdin(&path, "edited incident")?,
                None if std::io::stdin().is_terminal() => Editor::new()
                    .extension(".yaml")
                    .edit(&original)
                    .map_err(|error| ApiError::Other(format!("failed to open editor: {error}")))?
                    .ok_or_else(|| ApiError::InvalidInput("incident edit cancelled".into()))?,
                None => {
                    return Err(ApiError::InvalidInput(
                        "an interactive terminal or --file is required for incident edit".into(),
                    ));
                }
            };
            let body = incident::changed_fields(&existing, incident::parse_edit_document(&edited)?);
            if body.is_empty() {
                if output.json {
                    output.value(&serde_json::json!({
                        "changed": false,
                        "incident": identifier,
                        "changes": {},
                    }));
                } else {
                    outln!("No changes to apply.");
                }
                return Ok(());
            }
            if dry_run {
                emit_mutation_plan(output, "update", &identifier, &body);
                return Ok(());
            }
            config.require_writable()?;
            if !yes {
                if !std::io::stdin().is_terminal() {
                    return Err(ApiError::InvalidInput(
                        "confirmation requires an interactive terminal; rerun with --yes".into(),
                    ));
                }
                let diff = incident::unified_diff(&original, &edited);
                if !diff.is_empty() {
                    eprintln!("{diff}");
                }
                let confirmed = Confirm::new()
                    .with_prompt(format!(
                        "Apply {} changed field(s) to {identifier}?",
                        body.len()
                    ))
                    .default(false)
                    .interact()
                    .map_err(|error| {
                        ApiError::Other(format!("failed to confirm update: {error}"))
                    })?;
                if !confirmed {
                    return Err(ApiError::InvalidInput("incident edit cancelled".into()));
                }
            }
            let record = client.update_record("incident", &sys_id, &body).await?;
            output.success(&format!("Updated {identifier} ({} field(s)).", body.len()));
            emit_record(output, record);
        }
        IncidentsCommand::Note {
            identifier,
            text,
            file,
            dry_run,
        } => {
            let note = match (text, file) {
                (Some(_), Some(_)) => {
                    return Err(ApiError::InvalidInput(
                        "provide work note text or --file, not both".into(),
                    ));
                }
                (Some(text), None) => text,
                (None, Some(path)) => read_file_or_stdin(&path, "work note")?,
                (None, None) => {
                    return Err(ApiError::InvalidInput(
                        "work note text or --file is required".into(),
                    ));
                }
            };
            let body = incident::work_note_body(note)?;
            let existing = resolve_incident(
                client,
                &identifier,
                Some(vec!["sys_id".into()]),
                DisplayValue::False,
            )
            .await?;
            if dry_run {
                emit_mutation_plan(output, "append_work_note", &identifier, &body);
                return Ok(());
            }
            config.require_writable()?;
            let record = client
                .update_record("incident", record_sys_id(&existing)?, &body)
                .await?;
            output.success(&format!("Added a work note to {identifier}."));
            emit_record(output, record);
        }
        IncidentsCommand::Assign {
            identifier,
            assignee,
            group,
            dry_run,
        } => {
            incident::require_assignment(assignee.as_deref(), group.as_deref())?;
            let mut body = Map::new();
            insert(
                &mut body,
                "assigned_to",
                resolve_reference_id(client, ReferenceKind::User, assignee).await?,
            );
            insert(
                &mut body,
                "assignment_group",
                resolve_reference_id(client, ReferenceKind::Group, group).await?,
            );
            let existing = resolve_incident(
                client,
                &identifier,
                Some(vec!["sys_id".into()]),
                DisplayValue::False,
            )
            .await?;
            if dry_run {
                emit_mutation_plan(output, "assign", &identifier, &body);
                return Ok(());
            }
            config.require_writable()?;
            let record = client
                .update_record("incident", record_sys_id(&existing)?, &body)
                .await?;
            output.success(&format!("Assigned {identifier}."));
            emit_record(output, record);
        }
        IncidentsCommand::Open { identifier, print } => {
            let existing = resolve_incident(
                client,
                &identifier,
                Some(vec!["sys_id".into(), "number".into()]),
                DisplayValue::False,
            )
            .await?;
            let url = client.record_url("incident", record_sys_id(&existing)?);
            if output.json {
                output.value(&serde_json::json!({
                    "incident": field_text(&existing, "number").unwrap_or(identifier),
                    "url": url,
                }));
            } else if print || !std::io::stdout().is_terminal() {
                outln!("{url}");
            } else {
                open::that(&url).map_err(|error| {
                    ApiError::Other(format!("failed to open ServiceNow in a browser: {error}"))
                })?;
                output.success("Opened incident in ServiceNow.");
            }
        }
        IncidentsCommand::Watch {
            identifier,
            interval,
            count,
            fields,
        } => {
            if interval == 0 {
                return Err(ApiError::InvalidInput(
                    "--interval must be greater than zero".into(),
                ));
            }
            if count == Some(0) {
                return Err(ApiError::InvalidInput(
                    "--count must be greater than zero".into(),
                ));
            }
            if output.format == OutputFormat::Csv {
                return Err(ApiError::InvalidInput(
                    "incident watch is a stream; use table, json, jsonl, or yaml output".into(),
                ));
            }
            let fields = parse_fields(fields.as_deref()).unwrap_or_else(|| {
                [
                    "sys_id",
                    "number",
                    "short_description",
                    "state",
                    "priority",
                    "assigned_to",
                    "assignment_group",
                    "sys_updated_on",
                ]
                .into_iter()
                .map(str::to_string)
                .collect()
            });
            let mut previous =
                resolve_incident(client, &identifier, Some(fields.clone()), DisplayValue::All)
                    .await?;
            let sys_id = record_sys_id(&previous)?.to_string();
            emit_watch_event(output, &identifier, 0, &[], Some(&previous));
            let mut polls = 0usize;
            loop {
                if count.is_some_and(|limit| polls >= limit) {
                    break;
                }
                tokio::select! {
                    _ = tokio::signal::ctrl_c() => {
                        output.message("Watch stopped.");
                        break;
                    }
                    _ = tokio::time::sleep(std::time::Duration::from_secs(interval)) => {}
                }
                polls += 1;
                let current = client
                    .get_record("incident", &sys_id, Some(&fields), DisplayValue::All)
                    .await?;
                let changes = incident::change_records(&previous, &current);
                if !changes.is_empty() {
                    emit_watch_event(output, &identifier, polls, &changes, None);
                }
                previous = current;
            }
        }
    }
    Ok(())
}

async fn resolve_reference_id(
    client: &ServiceNowClient,
    kind: ReferenceKind,
    value: Option<String>,
) -> Result<Option<String>, ApiError> {
    let Some(value) = value else {
        return Ok(None);
    };
    let record = metadata::resolve_reference(client, kind, &value).await?;
    Ok(Some(record_sys_id(&record)?.to_string()))
}

const RITM_LIST_FIELDS: &[&str] = &[
    "number",
    "cat_item",
    "stage",
    "state",
    "quantity",
    "requested_for",
    "request",
    "sys_created_on",
    "sys_id",
];

async fn run_catalog(
    command: CatalogCommand,
    client: &ServiceNowClient,
    config: &Config,
    output: &OutputConfig,
) -> Result<(), ApiError> {
    match command {
        CatalogCommand::Search {
            text,
            limit,
            offset,
        } => {
            let items = client
                .search_catalog_items(text.as_deref(), limit, offset)
                .await?;
            let rows: Vec<Value> = items.iter().map(catalog_search_row).collect();
            let fields: Vec<String> = ["name", "kind", "short_description", "sys_id"]
                .into_iter()
                .map(str::to_string)
                .collect();
            emit_records_or(output, rows, Some(&fields), "No catalog items found.");
        }
        CatalogCommand::Show { item } => {
            let item = resolve_catalog_item(client, &item, true).await?;
            emit_catalog_item(output, &item, client.site_url());
        }
        CatalogCommand::Order {
            item,
            vars,
            vars_file,
            quantity,
            requested_for,
            allow_unknown_vars,
            allow_unverified_formats,
            checkout,
            dry_run,
            yes,
        } => {
            if checkout && requested_for.is_some() {
                return Err(ApiError::InvalidInput(
                    "--checkout cannot order for someone else: the instance ignores --requested-for for items added to a cart, so the request would be raised for you; order without --checkout".into(),
                ));
            }
            let file_values = match vars_file {
                Some(path) => {
                    catalog::parse_vars_document(&read_file_or_stdin(&path, "catalog variables")?)?
                }
                None => Default::default(),
            };
            let command_line = vars
                .iter()
                .map(|assignment| catalog::parse_var_assignment(assignment))
                .collect::<Result<Vec<_>, _>>()?;
            let inputs = catalog::merge_inputs(file_values, command_line);
            let item = resolve_catalog_item(client, &item, false).await?;
            item.ensure_orderable(client.site_url())?;
            let requested_for =
                resolve_reference_id(client, ReferenceKind::User, requested_for).await?;
            let unverified_formats = if allow_unverified_formats {
                catalog::UnverifiedFormats::Allow
            } else if dry_run {
                catalog::UnverifiedFormats::Preview
            } else {
                catalog::UnverifiedFormats::Refuse
            };
            let plan = catalog::prepare_order(
                client,
                &item,
                &inputs,
                &catalog::OrderOptions {
                    quantity,
                    requested_for,
                    allow_unknown_vars,
                    unverified_formats,
                },
            )
            .await?;
            for warning in &plan.warnings {
                output.message(&format!("warning: {warning}"));
            }
            if item.has_client_logic {
                output.message(
                    "warning: this item has catalog UI policies or client scripts that the CLI does not run",
                );
            }
            if !item.custom_widgets.is_empty() {
                output.message(&format!(
                    "warning: this item has custom widgets the CLI cannot show or fill ({}); if the order is rejected or incomplete, use the portal",
                    item.custom_widgets.join(", ")
                ));
            }
            let mut plan_json = plan.plan_json();
            if checkout {
                if !dry_run {
                    config.require_writable()?;
                }
                ensure_cart_empty(client).await?;
                plan_json["checkout"] = Value::Bool(true);
            }
            let through_cart = if checkout { " through your cart" } else { "" };
            if dry_run {
                emit_plan(
                    output,
                    &format!(
                        "order \"{}\" (quantity {}){through_cart}",
                        plan.item_name, plan.quantity
                    ),
                    &plan_json,
                    "variables",
                );
                return Ok(());
            }
            config.require_writable()?;
            if !yes && !output.json {
                outln!(
                    "Order \"{}\" (quantity {}){through_cart}\n",
                    plan.item_name,
                    plan.quantity
                );
                print_record(&plan_json["variables"], output.color);
            }
            confirm_destructive(
                yes,
                format!(
                    "Submit order for \"{}\" ({} variable(s))?",
                    plan.item_name,
                    plan.variables.len()
                ),
                "order cancelled; rerun with --yes to submit without prompting",
            )?;
            let scrubber = plan.error_scrubber();
            let scrub = scrubber
                .as_ref()
                .map(|scrub| scrub as &dyn Fn(&str) -> String);
            if checkout {
                let added = client
                    .add_catalog_item_to_cart(&plan.item_sys_id, &plan.request_body(), scrub)
                    .await?;
                let request = submit_added_item(client, &plan.item_sys_id, &added, scrub).await?;
                emit_order_result(client, output, &plan.item_name, request, OrderSource::Cart)
                    .await?;
            } else {
                let request = client
                    .order_catalog_item(&plan.item_sys_id, &plan.request_body(), scrub)
                    .await?;
                emit_order_result(
                    client,
                    output,
                    &plan.item_name,
                    request,
                    OrderSource::OrderNow,
                )
                .await?;
            }
        }
        CatalogCommand::Cart(command) => run_catalog_cart(command, client, config, output).await?,
        CatalogCommand::Requests(CatalogRequestsCommand::Mine {
            limit,
            open,
            display_value,
        }) => {
            let mut query =
                "requested_for=javascript:gs.getUserID()^ORopened_by=javascript:gs.getUserID()"
                    .to_string();
            if open {
                query.push_str("^active=true");
            }
            query.push_str("^ORDERBYDESCsys_created_on");
            let records = client
                .list_records(
                    "sc_req_item",
                    &ListOptions {
                        query: Some(query),
                        fields: Some(
                            RITM_LIST_FIELDS
                                .iter()
                                .map(|field| (*field).into())
                                .collect(),
                        ),
                        limit,
                        display_value: display_value.unwrap_or_else(|| {
                            if output.format == OutputFormat::Text {
                                DisplayValue::True
                            } else {
                                DisplayValue::False
                            }
                        }),
                        ..ListOptions::default()
                    },
                )
                .await?;
            let human_fields: Vec<String> =
                ["number", "cat_item", "stage", "state", "sys_created_on"]
                    .into_iter()
                    .map(str::to_string)
                    .collect();
            emit_records_or(
                output,
                records,
                Some(&human_fields),
                "No requested items found.",
            );
        }
        CatalogCommand::Requests(CatalogRequestsCommand::Vars {
            identifier,
            include_empty,
        }) => {
            let ritm = resolve_requested_item(client, &identifier).await?;
            let ritm_sys_id = record_sys_id(&ritm)?.to_string();
            let item_sys_id = ritm
                .get("cat_item")
                .and_then(|cell| cell.get("value").or(Some(cell)))
                .and_then(Value::as_str)
                .filter(|value| !value.is_empty())
                .ok_or_else(|| {
                    ApiError::InvalidInput(format!(
                        "{identifier} has no catalog item, so its variables cannot be listed"
                    ))
                })?
                .to_string();
            let item = CatalogItem::from_api(&client.get_catalog_item(&item_sys_id).await?)?;
            let names = catalog::readable_variable_names(&item);
            let variables = if names.is_empty() {
                Vec::new()
            } else {
                let fields: Vec<String> = names
                    .iter()
                    .map(|name| format!("variables.{name}"))
                    .collect();
                let record = client
                    .get_record(
                        "sc_req_item",
                        &ritm_sys_id,
                        Some(&fields),
                        DisplayValue::All,
                    )
                    .await?;
                catalog::ritm_variables(&item, &record)
            };
            emit_ritm_variables(output, &identifier, &variables, include_empty);
        }
    }
    Ok(())
}

fn catalog_search_row(item: &Value) -> Value {
    let class = item
        .get("sys_class_name")
        .and_then(Value::as_str)
        .unwrap_or_default();
    serde_json::json!({
        "sys_id": item.get("sys_id").cloned().unwrap_or(Value::Null),
        "name": item.get("name").cloned().unwrap_or(Value::Null),
        "short_description": item.get("short_description").cloned().unwrap_or(Value::Null),
        "class": class,
        "kind": catalog::kind_label(class),
        "orderable": catalog::is_orderable_class(class),
        "category": item.get("category").and_then(|category| category.get("title")).cloned().unwrap_or(Value::Null),
    })
}

/// Resolves an item by sys_id or exact (case-insensitive) name. With
/// `allow_search`, a search that returns exactly one item also counts; an
/// order never accepts that, so a fuzzy hit cannot place an order.
async fn resolve_catalog_item(
    client: &ServiceNowClient,
    identifier: &str,
    allow_search: bool,
) -> Result<CatalogItem, ApiError> {
    let identifier = identifier.trim();
    if servicenow_cli::api::validate_sys_id(identifier).is_ok() {
        return CatalogItem::from_api(
            &client
                .get_catalog_item(&identifier.to_ascii_lowercase())
                .await?,
        );
    }
    // Every page is read: a second item with the same name on a later page
    // would otherwise go unnoticed and the first one be ordered.
    const PAGE: usize = 100;
    const MAX_RESULTS: usize = 1000;
    let mut hits = Vec::new();
    loop {
        let page = client
            .search_catalog_items(Some(identifier), PAGE, hits.len())
            .await?;
        let full = page.len() == PAGE;
        hits.extend(page);
        if !full {
            break;
        }
        if hits.len() >= MAX_RESULTS {
            return Err(ApiError::Conflict(format!(
                "more than {MAX_RESULTS} catalog items match \"{identifier}\", so the name cannot be checked for uniqueness; use the sys_id"
            )));
        }
    }
    let exact: Vec<&Value> = hits
        .iter()
        .filter(|hit| {
            hit.get("name")
                .and_then(Value::as_str)
                .is_some_and(|name| name.eq_ignore_ascii_case(identifier))
        })
        .collect();
    let candidates = |items: &[&Value]| {
        items
            .iter()
            .take(10)
            .map(|item| {
                format!(
                    "{} ({}, {})",
                    item.get("name").and_then(Value::as_str).unwrap_or("?"),
                    catalog::kind_label(
                        item.get("sys_class_name")
                            .and_then(Value::as_str)
                            .unwrap_or_default()
                    ),
                    item.get("sys_id").and_then(Value::as_str).unwrap_or("?"),
                )
            })
            .collect::<Vec<_>>()
            .join("\n  ")
    };
    let chosen = match exact.as_slice() {
        [item] => *item,
        [] if allow_search && hits.len() == 1 => &hits[0],
        [] if hits.is_empty() => {
            return Err(ApiError::NotFound(format!(
                "no catalog item matches \"{identifier}\""
            )));
        }
        [] => {
            let all: Vec<&Value> = hits.iter().collect();
            let hint = if allow_search {
                "use a more specific name or the sys_id"
            } else {
                "orders need the exact item name or sys_id"
            };
            return Err(ApiError::NotFound(format!(
                "no catalog item is named \"{identifier}\"; {hint}. Matches:\n  {}",
                candidates(&all)
            )));
        }
        several => {
            return Err(ApiError::Conflict(format!(
                "{} catalog items are named \"{identifier}\"; use the sys_id:\n  {}",
                several.len(),
                candidates(several)
            )));
        }
    };
    let sys_id = chosen
        .get("sys_id")
        .and_then(Value::as_str)
        .ok_or_else(|| ApiError::Other("catalog search result omitted sys_id".into()))?;
    CatalogItem::from_api(&client.get_catalog_item(sys_id).await?)
}

fn emit_catalog_item(output: &OutputConfig, item: &CatalogItem, site_url: &str) {
    let item = &item.redacted();
    let portal_url = item.portal_url(site_url);
    let orderable = item.ensure_orderable(site_url);
    if output.json {
        let mut value = serde_json::to_value(item).expect("catalog item is serializable");
        value["kind"] = catalog::kind_label(&item.class).into();
        value["orderable"] = orderable.is_ok().into();
        value["portal_url"] = portal_url.into();
        output.value(&serde_json::json!({ "result": value }));
        return;
    }
    outln!("{}", output.heading(&item.name));
    if !item.short_description.is_empty() {
        outln!("{}", item.short_description);
    }
    outln!(
        "{} ({}) {}\n{}\n",
        catalog::kind_label(&item.class),
        item.class,
        item.sys_id,
        portal_url
    );
    if let Err(reason) = &orderable {
        outln!("Not orderable from the CLI: {reason}\n");
    }
    if item.instance_orderable == Some(false) {
        outln!("Note: {}.\n", catalog::INSTANCE_UNORDERABLE);
    }
    if item.has_client_logic {
        outln!(
            "Note: this item has client-side logic (UI policies or client scripts) the CLI does not run.\n"
        );
    }
    let empty_sets: Vec<&str> = item
        .variables
        .iter()
        .filter(|variable| {
            variable.kind == catalog::VariableKind::MultiRowSet && !variable.mandatory
        })
        .map(|variable| variable.name.as_str())
        .collect();
    if orderable.is_ok() && !empty_sets.is_empty() {
        outln!(
            "Note: the CLI cannot fill multi-row variable sets; these optional ones are left empty when ordering: {}.\n",
            empty_sets.join(", ")
        );
    }
    if !item.custom_widgets.is_empty() {
        outln!(
            "Note: this item has custom widgets the CLI cannot show or fill: {}.\n",
            item.custom_widgets.join(", ")
        );
    }
    let rows: Vec<Value> = item
        .variables
        .iter()
        .map(|variable| {
            let options = if !variable.choices.is_empty() {
                variable
                    .choices
                    .iter()
                    .map(|choice| choice.value.as_str())
                    .collect::<Vec<_>>()
                    .join(", ")
            } else if let Some(table) = &variable.reference_table {
                format!("→ {table}")
            } else {
                String::new()
            };
            serde_json::json!({
                "name": variable.name,
                "label": variable.label,
                "type": variable.type_name,
                "required": if variable.mandatory { "yes" } else { "" },
                "default": variable.default_value.clone().unwrap_or_default(),
                "options": options,
            })
        })
        .collect();
    let fields: Vec<String> = ["name", "label", "type", "required", "default", "options"]
        .into_iter()
        .map(str::to_string)
        .collect();
    print_records_or(
        &rows,
        Some(&fields),
        output.color,
        "This item has no variables.",
    );
}

async fn run_catalog_cart(
    command: CatalogCartCommand,
    client: &ServiceNowClient,
    config: &Config,
    output: &OutputConfig,
) -> Result<(), ApiError> {
    match command {
        CatalogCartCommand::Show => {
            let cart = catalog::Cart::from_api(&client.get_cart().await?)?;
            if output.json {
                output.value(&cart.to_json());
            } else if cart.items.is_empty() {
                outln!("Your cart is empty.");
            } else {
                outln!(
                    "Cart {} ({} item(s))  {}\n",
                    cart.cart_id,
                    cart.items.len(),
                    client.record_url("sc_cart", &cart.cart_id)
                );
                print_cart_items(&cart, output);
            }
        }
        CatalogCartCommand::Submit { yes } => {
            config.require_writable()?;
            let cart = catalog::Cart::from_api(&client.get_cart().await?)?;
            if cart.items.is_empty() {
                return Err(ApiError::InvalidInput(
                    "your cart is empty, so there is nothing to submit".into(),
                ));
            }
            for item in &cart.items {
                if item.can_order == Some(false) {
                    output.message(&format!(
                        "warning: the instance reports that \"{}\" cannot be ordered as it is; it may refuse the cart",
                        item.name
                    ));
                }
            }
            if !yes && !output.json {
                print_cart_items(&cart, output);
                outln!();
            }
            confirm_destructive(
                yes,
                format!("Order the {} item(s) in your cart?", cart.items.len()),
                "cart submission cancelled; rerun with --yes to submit without prompting",
            )?;
            let withhold = |_: &str| WITHHELD_FOR_CART.to_string();
            let scrub = if cart_may_hold_secrets(client, &cart).await {
                Some(&withhold as &dyn Fn(&str) -> String)
            } else {
                None
            };
            ensure_cart_unchanged(client, &cart).await?;
            let request = client.submit_cart(scrub).await?;
            emit_order_result(
                client,
                output,
                &cart.item_names(),
                request,
                OrderSource::Cart,
            )
            .await?;
        }
        CatalogCartCommand::Remove { cart_item_id, yes } => {
            config.require_writable()?;
            let cart_item_id = cart_item_id.trim().to_ascii_lowercase();
            servicenow_cli::api::validate_sys_id(&cart_item_id)?;
            let cart = catalog::Cart::from_api(&client.get_cart().await?)?;
            let item = cart.item(&cart_item_id).ok_or_else(|| {
                ApiError::NotFound(format!(
                    "cart item {cart_item_id} is not in your cart; `servicenow catalog cart show` lists what is"
                ))
            })?;
            confirm_destructive(
                yes,
                format!("Remove \"{}\" from your cart?", item.name),
                "cart item removal cancelled; rerun with --yes to remove without prompting",
            )?;
            client.remove_cart_item(&cart_item_id).await?;
            if output.json {
                output.value(&serde_json::json!({
                    "removed": true,
                    "cart_id": cart.cart_id,
                    "cart_item_id": cart_item_id,
                    "item_name": item.name,
                }));
            } else {
                outln!("Removed \"{}\" from your cart.", item.name);
            }
        }
        CatalogCartCommand::Clear { yes } => {
            config.require_writable()?;
            let cart = catalog::Cart::from_api(&client.get_cart().await?)?;
            if !cart.items.is_empty() {
                confirm_destructive(
                    yes,
                    format!("Remove all {} item(s) from your cart?", cart.items.len()),
                    "cart clearing cancelled; rerun with --yes to clear without prompting",
                )?;
                ensure_cart_unchanged(client, &cart).await?;
                client.empty_cart(&cart.cart_id).await?;
            }
            if output.json {
                output.value(&serde_json::json!({
                    "cleared": true,
                    "cart_id": cart.cart_id,
                    "items_removed": cart.items.len(),
                }));
            } else if cart.items.is_empty() {
                outln!("Your cart is already empty.");
            } else {
                outln!("Removed {} item(s) from your cart.", cart.items.len());
            }
        }
    }
    Ok(())
}

fn print_cart_items(cart: &catalog::Cart, output: &OutputConfig) {
    let rows: Vec<Value> = cart
        .items
        .iter()
        .map(|item| {
            serde_json::json!({
                "item_name": item.name,
                "quantity": item.details.get("quantity").cloned().unwrap_or(Value::Null),
                "cart_item_id": item.cart_item_id,
            })
        })
        .collect();
    let fields: Vec<String> = ["item_name", "quantity", "cart_item_id"]
        .into_iter()
        .map(str::to_string)
        .collect();
    print_records_or(&rows, Some(&fields), output.color, "Your cart is empty.");
}

/// Replaces the instance's error message for a cart that may hold sensitive
/// values: the cart answer lists no variable values, so none can be scrubbed.
const WITHHELD_FOR_CART: &str = "error message withheld: your cart may hold sensitive values the CLI cannot see, so the message could quote one; open the cart in the portal to see why";

/// Whether any item in `cart` has a sensitive variable. The cart answer
/// carries no variable values, so this reads each item's definition, and an
/// item that cannot be read counts as sensitive.
async fn cart_may_hold_secrets(client: &ServiceNowClient, cart: &catalog::Cart) -> bool {
    let mut ids = BTreeSet::new();
    for item in &cart.items {
        match &item.catalog_item_id {
            Some(id) => {
                ids.insert(id.clone());
            }
            None => return true,
        }
    }
    for id in ids {
        let sensitive = match client.get_catalog_item(&id).await {
            Ok(value) => catalog::CatalogItem::from_api(&value).map_or(true, |item| {
                // A multi-row set's rows are typed in the portal and its
                // columns are not listed here, so any of them could hold
                // a secret.
                item.variables.iter().any(|variable| {
                    variable.is_sensitive() || variable.kind == catalog::VariableKind::MultiRowSet
                })
            }),
            Err(_) => true,
        };
        if sensitive {
            return true;
        }
    }
    false
}

/// `catalog order --checkout` submits the whole cart, so it starts only from
/// an empty one: anything already there would be ordered too.
async fn ensure_cart_empty(client: &ServiceNowClient) -> Result<(), ApiError> {
    let cart = catalog::Cart::from_api(&client.get_cart().await?)?;
    if cart.items.is_empty() {
        return Ok(());
    }
    Err(ApiError::Conflict(format!(
        "your cart already holds {} item(s) ({}), and --checkout submits the whole cart, so they would be ordered too; review it with `servicenow catalog cart show`, then order it with `servicenow catalog cart submit` or empty it with `servicenow catalog cart clear`",
        cart.items.len(),
        cart.item_names()
    )))
}

/// Submits the cart an `add_to_cart` answer describes, provided it holds only
/// the item just added. Until the submission is sent, nothing is ordered and
/// the item stays in the cart, so every refusal says how to finish or undo it.
async fn submit_added_item(
    client: &ServiceNowClient,
    item_sys_id: &str,
    added: &Value,
    scrub: Option<&dyn Fn(&str) -> String>,
) -> Result<Value, ApiError> {
    let cart = catalog::Cart::from_api(added).map_err(|error| {
        ApiError::Other(format!(
            "the item was added to your cart, but the answer could not be read ({error}); nothing was ordered, so check `servicenow catalog cart show` before retrying"
        ))
    })?;
    let left_in_cart = |reason: String| ApiError::NotOrdered {
        message: format!(
            "{reason}; nothing was ordered, and the item is still in your cart {} ({})",
            cart.cart_id,
            client.record_url("sc_cart", &cart.cart_id)
        ),
        cart_id: cart.cart_id.clone(),
    };
    if cart.items.is_empty() {
        // Without the item in the answer, nothing says where it went.
        return Err(ApiError::Other(format!(
            "the instance accepted the item for cart {} but listed no items in it; {}",
            cart.cart_id,
            servicenow_cli::api::MAY_HAVE_ADDED_TO_CART
        )));
    }
    if let [only] = cart.items.as_slice()
        && only
            .catalog_item_id
            .as_deref()
            .is_some_and(|id| !id.eq_ignore_ascii_case(item_sys_id))
    {
        return Err(left_in_cart(format!(
            "your cart changed while the item was added and now holds \"{}\" instead, so it was not submitted",
            only.name
        )));
    }
    if cart.items.len() != 1 {
        return Err(left_in_cart(format!(
            "your cart changed while the item was added and now holds {} item(s) ({}), so it was not submitted",
            cart.items.len(),
            cart.item_names()
        )));
    }
    match client.submit_cart(scrub).await {
        Ok(request) => Ok(request),
        // A failure after the submission was sent, or a server error, may
        // have ordered and already says so. Anything else (a connection that
        // never opened, or an answer refusing the submission) ordered nothing.
        Err(error @ (ApiError::Other(_) | ApiError::Api { status: 500.., .. })) => Err(error),
        Err(error) => {
            // The cart is shared with the portal, which may have ordered or
            // removed the item meanwhile: only a cart still holding it shows
            // that nothing was ordered.
            let added_id = &cart.items[0].cart_item_id;
            let still_there = match client.get_cart().await {
                Ok(answer) => {
                    catalog::Cart::from_api(&answer).is_ok_and(|now| now.item(added_id).is_some())
                }
                Err(_) => false,
            };
            if still_there {
                Err(left_in_cart(format!(
                    "the item was added to your cart, but submitting the cart failed ({error})"
                )))
            } else {
                Err(ApiError::Other(format!(
                    "submitting the cart failed ({error}), and the added item is no longer in your cart, so it may have been ordered or removed elsewhere; check `servicenow catalog requests mine` and `servicenow catalog cart show` before ordering again"
                )))
            }
        }
    }
}

/// Re-reads the cart just before a write and refuses when it no longer holds
/// what the user confirmed: the cart is shared with the portal, and a change
/// would otherwise be ordered or removed unseen.
async fn ensure_cart_unchanged(
    client: &ServiceNowClient,
    confirmed: &catalog::Cart,
) -> Result<(), ApiError> {
    let now = catalog::Cart::from_api(&client.get_cart().await?)?;
    if now.fingerprint() != confirmed.fingerprint() {
        return Err(ApiError::Conflict(format!(
            "your cart changed after it was read (it now holds {} item(s): {}); nothing was changed, so review it with `servicenow catalog cart show` and run the command again",
            now.items.len(),
            if now.items.is_empty() {
                "none".to_string()
            } else {
                now.item_names()
            }
        )));
    }
    Ok(())
}

/// Which call an order answer came from, since a cart answer means something
/// different for each.
#[derive(Clone, Copy)]
enum OrderSource {
    /// `order_now`, which some instances answer with a cart.
    OrderNow,
    /// A cart submission, which should only ever answer with a request.
    Cart,
}

async fn emit_order_result(
    client: &ServiceNowClient,
    output: &OutputConfig,
    item_name: &str,
    request: Value,
    source: OrderSource,
) -> Result<(), ApiError> {
    let (request_id, request_label) = match catalog::OrderOutcome::classify(&request) {
        catalog::OrderOutcome::Request { sys_id, number } => {
            let label = number.unwrap_or_else(|| format!("request {sys_id}"));
            (sys_id, label)
        }
        catalog::OrderOutcome::CartOnly { cart_id } => {
            let cart_url = client.record_url("sc_cart", &cart_id);
            let message = match source {
                OrderSource::OrderNow => format!(
                    "the instance accepted the order but created no request; the item was left in cart {cart_id} ({cart_url}) instead, and the instance may also have put a copy in your portal cart. This usually means the instance needs a separate checkout step (`servicenow catalog order --checkout` orders through the cart), or the item cannot be ordered through the API. Nothing was ordered."
                ),
                // A cart submission is never meant to answer with a cart, so
                // nothing here says whether it ordered: resubmitting could
                // order twice.
                OrderSource::Cart => {
                    return Err(ApiError::Other(format!(
                        "the instance answered the cart submission with cart {cart_id} ({cart_url}) instead of a request, so it is unclear whether anything was ordered; check `servicenow catalog requests mine` and `servicenow catalog cart show` before submitting again"
                    )));
                }
            };
            return Err(ApiError::NotOrdered { message, cart_id });
        }
        catalog::OrderOutcome::Unrecognized { keys, number } => {
            let fields = if keys.is_empty() {
                "no fields".to_string()
            } else {
                format!("fields: {}", keys.join(", "))
            };
            let named = number
                .map(|number| format!(", though it named request {number}"))
                .unwrap_or_default();
            return Err(ApiError::Other(format!(
                "the instance answered the order with neither a request id nor a cart ({fields}){named}; {}",
                servicenow_cli::api::MAY_HAVE_ORDERED
            )));
        }
    };
    // The order is already placed, so a failed follow-up lookup must not turn
    // into an error exit: a retry would place a second order.
    let requested_items = match client
        .list_records(
            "sc_req_item",
            &ListOptions {
                query: Some(format!("request={request_id}")),
                fields: Some(
                    RITM_LIST_FIELDS
                        .iter()
                        .map(|field| (*field).into())
                        .collect(),
                ),
                limit: 100,
                display_value: DisplayValue::False,
                ..ListOptions::default()
            },
        )
        .await
    {
        Ok(items) => Some(items),
        Err(error) => {
            output.message(&format!(
                "warning: the order was placed, but its requested items could not be read ({error}); do not reorder, check `servicenow catalog requests mine`"
            ));
            None
        }
    };
    let numbers: Vec<&str> = requested_items
        .iter()
        .flatten()
        .filter_map(|item| item.get("number").and_then(Value::as_str))
        .collect();
    if numbers.is_empty() {
        output.success(&format!("Ordered {item_name}: {request_label}"));
        if requested_items.is_some() {
            output.message("No requested items were found for this request yet; check `servicenow catalog requests mine`.");
        }
    } else {
        output.success(&format!(
            "Ordered {item_name}: {request_label} / {}",
            numbers.join(", ")
        ));
    }
    if output.json {
        output.value(&serde_json::json!({
            "request": request,
            "requestedItems": requested_items,
        }));
    } else {
        outln!(
            "{request_label}  {}",
            client.record_url("sc_request", &request_id)
        );
        for item in requested_items.iter().flatten() {
            if let (Some(number), Some(sys_id)) = (
                item.get("number").and_then(Value::as_str),
                item.get("sys_id").and_then(Value::as_str),
            ) {
                outln!("{number}  {}", client.record_url("sc_req_item", sys_id));
            }
        }
    }
    Ok(())
}

/// Resolves a requested item by sys_id or number. Numbers are not unique, so
/// several matches fail with the candidates instead of picking one.
async fn resolve_requested_item(
    client: &ServiceNowClient,
    identifier: &str,
) -> Result<Value, ApiError> {
    let identifier = identifier.trim();
    let fields: Vec<String> = ["sys_id", "number", "cat_item", "sys_created_on"]
        .into_iter()
        .map(str::to_string)
        .collect();
    if servicenow_cli::api::validate_sys_id(identifier).is_ok() {
        return client
            .get_record("sc_req_item", identifier, Some(&fields), DisplayValue::All)
            .await;
    }
    if identifier.is_empty() || !identifier.bytes().all(|byte| byte.is_ascii_alphanumeric()) {
        return Err(ApiError::InvalidInput(format!(
            "invalid requested item '{identifier}'; give a RITM number or sys_id"
        )));
    }
    let records = client
        .list_records(
            "sc_req_item",
            &ListOptions {
                query: Some(format!("number={identifier}")),
                fields: Some(fields),
                limit: 10,
                display_value: DisplayValue::All,
                ..ListOptions::default()
            },
        )
        .await?;
    match records.as_slice() {
        [] => Err(ApiError::NotFound(format!("requested item {identifier}"))),
        [record] => Ok(record.clone()),
        several => Err(ApiError::Conflict(format!(
            "{} requested items are numbered {identifier}; use the sys_id:\n  {}",
            several.len(),
            several
                .iter()
                .map(|record| {
                    let cell = |field: &str| {
                        record
                            .get(field)
                            .and_then(|cell| cell.get("display_value").or(Some(cell)))
                            .and_then(Value::as_str)
                            .unwrap_or("?")
                            .to_string()
                    };
                    let sys_id = record_sys_id(record).unwrap_or("?");
                    format!(
                        "{sys_id} ({}, created {})",
                        cell("cat_item"),
                        cell("sys_created_on")
                    )
                })
                .collect::<Vec<_>>()
                .join("\n  ")
        ))),
    }
}

fn emit_ritm_variables(
    output: &OutputConfig,
    identifier: &str,
    variables: &[catalog::RitmVariable],
    include_empty: bool,
) {
    // A reorder from the JSON export would replace a cleared value with the
    // item's default, so a cleared default is kept there.
    let shown: Vec<&catalog::RitmVariable> = variables
        .iter()
        .filter(|variable| {
            include_empty || !variable.value.is_empty() || (output.json && variable.has_default)
        })
        .collect();
    let withheld: Vec<&str> = shown
        .iter()
        .filter(|variable| variable.sensitive)
        .map(|variable| variable.name.as_str())
        .collect();
    if output.json {
        if !withheld.is_empty() {
            output.message(&format!(
                "Omitted sensitive variable(s) {}; supply them yourself with --vars-file.",
                withheld.join(", ")
            ));
        }
        // The object is input for `catalog order --vars-file`, which refuses
        // read-only variables, so they are left out.
        let read_only: Vec<&str> = shown
            .iter()
            .filter(|variable| variable.read_only && !variable.sensitive)
            .map(|variable| variable.name.as_str())
            .collect();
        if !read_only.is_empty() {
            output.message(&format!(
                "Omitted read-only variable(s) {}, which the form fills itself; see them with --output text.",
                read_only.join(", ")
            ));
        }
        let reusable: Vec<&&catalog::RitmVariable> = shown
            .iter()
            .filter(|variable| !variable.sensitive && !variable.read_only)
            .collect();
        let unplaced: Vec<&str> = reusable
            .iter()
            .filter(|variable| variable.order_value.is_none())
            .map(|variable| variable.name.as_str())
            .collect();
        if !unplaced.is_empty() {
            output.message(&format!(
                "Omitted variable(s) {}: the instance returned them without a value in your time zone; see them with --output text.",
                unplaced.join(", ")
            ));
        }
        let values: Map<String, Value> = reusable
            .iter()
            .filter_map(|variable| {
                let value = variable.order_value.clone()?;
                Some((variable.name.clone(), Value::String(value)))
            })
            .collect();
        output.value(&Value::Object(values));
        return;
    }
    let rows: Vec<Value> = shown
        .iter()
        .map(|variable| {
            let display = if variable.sensitive {
                servicenow_cli::sensitive::REDACTED.to_string()
            } else {
                variable.display_value.clone()
            };
            serde_json::json!({
                "name": variable.name,
                "label": variable.label,
                "value": display,
            })
        })
        .collect();
    let fields: Vec<String> = ["name", "label", "value"]
        .into_iter()
        .map(str::to_string)
        .collect();
    print_records_or(
        &rows,
        Some(&fields),
        output.color,
        &format!("{identifier} has no variable values."),
    );
}

fn read_file_or_stdin(path: &std::path::Path, label: &str) -> Result<String, ApiError> {
    if path == std::path::Path::new("-") {
        let mut value = String::new();
        std::io::stdin()
            .read_to_string(&mut value)
            .map_err(|error| {
                ApiError::Other(format!("failed to read {label} from stdin: {error}"))
            })?;
        Ok(value)
    } else {
        std::fs::read_to_string(path).map_err(|error| {
            ApiError::Other(format!(
                "failed to read {label} from {}: {error}",
                path.display()
            ))
        })
    }
}

fn emit_mutation_plan(
    output: &OutputConfig,
    operation: &str,
    identifier: &str,
    body: &Map<String, Value>,
) {
    let plan = serde_json::json!({
        "dryRun": true,
        "operation": operation,
        "table": "incident",
        "incident": identifier,
        "changes": body,
    });
    emit_plan(
        output,
        &format!("{operation} {identifier}"),
        &plan,
        "changes",
    );
}

/// Prints a dry-run plan: the whole plan as machine output, or a one-line
/// summary followed by the plan's `detail_key` section as a human record.
fn emit_plan(output: &OutputConfig, summary: &str, plan: &Value, detail_key: &str) {
    if output.json {
        output.value(plan);
    } else {
        outln!("Dry run: {summary}\n");
        print_record(&plan[detail_key], output.color);
    }
}

fn emit_watch_event(
    output: &OutputConfig,
    identifier: &str,
    poll: usize,
    changes: &[Value],
    initial: Option<&Value>,
) {
    let event = serde_json::json!({
        "event": if initial.is_some() { "snapshot" } else { "change" },
        "incident": identifier,
        "poll": poll,
        "changes": changes,
        "record": initial,
    });
    match output.format {
        OutputFormat::Json | OutputFormat::JsonLines => outln!(
            "{}",
            serde_json::to_string(&event).expect("watch event is serializable")
        ),
        OutputFormat::Yaml => out!(
            "---\n{}",
            serde_saphyr::to_string(&event).expect("watch event is serializable")
        ),
        OutputFormat::Text => {
            if let Some(record) = initial {
                outln!("Watching {identifier}. Press Ctrl-C to stop.\n");
                print_record(record, output.color);
            } else {
                outln!("\n{} changed", output.heading(identifier));
                print_records(
                    changes,
                    Some(&["field".into(), "before".into(), "after".into()]),
                    output.color,
                );
            }
        }
        OutputFormat::Csv => unreachable!("CSV watch output is rejected before polling"),
    }
}

async fn run_attachments(
    command: AttachmentsCommand,
    client: &ServiceNowClient,
    config: &Config,
    output: &OutputConfig,
) -> Result<(), ApiError> {
    match command {
        AttachmentsCommand::List {
            table,
            record: identifier,
            limit,
            all,
        } => {
            let record = record::resolve(
                client,
                &table,
                &identifier,
                Some(vec!["sys_id".into(), "number".into()]),
                DisplayValue::False,
            )
            .await?;
            let sys_id = record_sys_id(&record)?;
            let attachments = client.list_attachments(&table, sys_id, limit, all).await?;
            emit_attachments(output, attachments)?;
        }
        AttachmentsCommand::Upload {
            table,
            record: identifier,
            file,
            name,
            content_type,
            dry_run,
        } => {
            if !dry_run {
                config.require_writable()?;
            }
            let metadata = std::fs::metadata(&file).map_err(|error| {
                ApiError::InvalidInput(format!(
                    "cannot read attachment {}: {error}",
                    file.display()
                ))
            })?;
            if !metadata.is_file() {
                return Err(ApiError::InvalidInput(format!(
                    "attachment source is not a regular file: {}",
                    file.display()
                )));
            }
            std::fs::File::open(&file).map_err(|error| {
                ApiError::InvalidInput(format!(
                    "cannot open attachment {}: {error}",
                    file.display()
                ))
            })?;
            let file_name = attachment::upload_file_name(&file, name.as_deref())?;
            let content_type = attachment::content_type(&file, content_type.as_deref())?;
            let record = record::resolve(
                client,
                &table,
                &identifier,
                Some(vec!["sys_id".into(), "number".into()]),
                DisplayValue::False,
            )
            .await?;
            let table_sys_id = record_sys_id(&record)?;
            if dry_run {
                let plan = serde_json::json!({
                    "dryRun": true,
                    "operation": "upload_attachment",
                    "table": table,
                    "record": identifier,
                    "tableSysId": table_sys_id,
                    "file": file,
                    "fileName": file_name,
                    "contentType": content_type,
                    "sizeBytes": metadata.len(),
                });
                if output.json {
                    output.value(&plan);
                } else {
                    outln!("Dry run: upload {file_name} to {table}/{identifier}\n");
                    print_record(&plan, output.color);
                }
                return Ok(());
            }
            let uploaded = client
                .upload_attachment_file(&table, table_sys_id, &file_name, &content_type, &file)
                .await?;
            output.success(&format!(
                "Uploaded {file_name} ({}) to {table}/{identifier}.",
                uploaded
                    .size_bytes
                    .as_deref()
                    .map(attachment::human_size)
                    .unwrap_or_else(|| "n/a".into())
            ));
            emit_attachment(output, uploaded)?;
        }
        AttachmentsCommand::Download {
            attachment: identifier,
            destination,
            force,
        } => {
            let sys_id = record::attachment_sys_id(client.site_url(), &identifier)?;
            let metadata = client.get_attachment(&sys_id).await?;
            let file_name = metadata.file_name.as_deref().ok_or_else(|| {
                ApiError::Other("ServiceNow attachment response omitted file_name".into())
            })?;
            let destination = attachment::destination_path(destination.as_deref(), file_name)?;
            if destination == std::path::Path::new("-") {
                let bytes = client
                    .download_attachment(&sys_id, &mut output::Stdout)
                    .await?;
                output.message(&format!(
                    "Downloaded {file_name} ({}) to stdout.",
                    attachment::human_size(&bytes.to_string())
                ));
                return Ok(());
            }
            if destination.exists() && !force {
                return Err(ApiError::Conflict(format!(
                    "{} already exists; use --force to replace it",
                    destination.display()
                )));
            }
            let parent = destination
                .parent()
                .filter(|path| !path.as_os_str().is_empty())
                .unwrap_or_else(|| std::path::Path::new("."));
            if !parent.is_dir() {
                return Err(ApiError::InvalidInput(format!(
                    "destination directory does not exist: {}",
                    parent.display()
                )));
            }
            let mut temporary = tempfile::NamedTempFile::new_in(parent).map_err(|error| {
                ApiError::Other(format!(
                    "failed to create a temporary download in {}: {error}",
                    parent.display()
                ))
            })?;
            let bytes = client.download_attachment(&sys_id, &mut temporary).await?;
            temporary.as_file().sync_all().map_err(|error| {
                ApiError::Other(format!("failed to sync downloaded attachment: {error}"))
            })?;
            if force {
                temporary.persist(&destination).map_err(|error| {
                    ApiError::Other(format!(
                        "failed to save attachment to {}: {}",
                        destination.display(),
                        error.error
                    ))
                })?;
            } else {
                temporary.persist_noclobber(&destination).map_err(|error| {
                    ApiError::Conflict(format!(
                        "could not save {} without replacing a file: {}",
                        destination.display(),
                        error.error
                    ))
                })?;
            }
            let result = serde_json::json!({
                "downloaded": true,
                "attachment": sys_id,
                "fileName": metadata.file_name,
                "contentType": metadata.content_type,
                "path": destination,
                "sizeBytes": bytes,
            });
            output.success(&format!(
                "Downloaded {} ({}) to {}.",
                result["fileName"].as_str().unwrap_or("attachment"),
                attachment::human_size(&bytes.to_string()),
                destination.display()
            ));
            if output.json {
                output.value(&result);
            } else {
                outln!("{}", destination.display());
            }
        }
        AttachmentsCommand::Delete {
            attachment: identifier,
            yes,
            dry_run,
        } => {
            if !dry_run {
                config.require_writable()?;
            }
            let sys_id = record::attachment_sys_id(client.site_url(), &identifier)?;
            let metadata = client.get_attachment(&sys_id).await?;
            if dry_run {
                let plan = serde_json::json!({
                    "dryRun": true,
                    "operation": "delete_attachment",
                    "attachment": sys_id,
                    "fileName": metadata.file_name,
                    "table": metadata.table_name,
                    "tableSysId": metadata.table_sys_id,
                    "sizeBytes": metadata.size_bytes,
                });
                if output.json {
                    output.value(&plan);
                } else {
                    outln!(
                        "Dry run: permanently delete {}\n",
                        metadata.file_name.as_deref().unwrap_or("n/a")
                    );
                    print_record(&plan, output.color);
                }
                return Ok(());
            }
            confirm_destructive(
                yes,
                format!(
                    "Permanently delete '{}' ({})?",
                    metadata.file_name.as_deref().unwrap_or("n/a"),
                    metadata
                        .size_bytes
                        .as_deref()
                        .map(attachment::human_size)
                        .unwrap_or_else(|| "n/a".into())
                ),
                "attachment deletion cancelled; use --yes for non-interactive deletion",
            )?;
            client.delete_attachment(&sys_id).await?;
            let result = serde_json::json!({
                "deleted": true,
                "attachment": sys_id,
                "fileName": metadata.file_name,
                "table": metadata.table_name,
                "tableSysId": metadata.table_sys_id,
            });
            output.success(&format!(
                "Deleted attachment {}.",
                result["fileName"].as_str().unwrap_or("attachment")
            ));
            if output.json {
                output.value(&result);
            } else {
                outln!(
                    "Deleted {}.",
                    result["fileName"].as_str().unwrap_or("attachment")
                );
            }
        }
    }
    Ok(())
}

fn emit_attachments(
    output: &OutputConfig,
    attachments: Vec<servicenow_cli::api::AttachmentMetadata>,
) -> Result<(), ApiError> {
    let mut records = attachments
        .into_iter()
        .map(serde_json::to_value)
        .collect::<Result<Vec<_>, _>>()
        .map_err(|error| {
            ApiError::Other(format!("failed to encode attachment metadata: {error}"))
        })?;
    if output.json {
        emit_records(output, records, None);
    } else {
        for record in &mut records {
            if let Some(object) = record.as_object_mut() {
                let size = object
                    .get("size_bytes")
                    .and_then(Value::as_str)
                    .map(attachment::human_size)
                    .unwrap_or_else(|| "n/a".into());
                object.insert("size".into(), Value::String(size));
                render_missing_attachment_fields_as_na(object);
            }
        }
        let fields = [
            "file_name".into(),
            "content_type".into(),
            "size".into(),
            "sys_created_by".into(),
            "sys_created_on".into(),
            "sys_id".into(),
        ];
        print_records(&records, Some(&fields), output.color);
    }
    Ok(())
}

fn emit_attachment(
    output: &OutputConfig,
    attachment: servicenow_cli::api::AttachmentMetadata,
) -> Result<(), ApiError> {
    let mut record = serde_json::to_value(attachment).map_err(|error| {
        ApiError::Other(format!("failed to encode attachment metadata: {error}"))
    })?;
    if !output.json
        && let Some(object) = record.as_object_mut()
    {
        render_missing_attachment_fields_as_na(object);
    }
    emit_record(output, record);
    Ok(())
}

/// Renders fields ServiceNow omitted (deserialized as `None`, serialized as
/// `Value::Null`) as the text "n/a" instead of the generic record printer's
/// placeholder for missing values, so the difference is visible without
/// changing how JSON output represents them (as `null`).
fn render_missing_attachment_fields_as_na(object: &mut serde_json::Map<String, Value>) {
    for value in object.values_mut() {
        if value.is_null() {
            *value = Value::String("n/a".into());
        }
    }
}

async fn run_tables(
    command: TablesCommand,
    client: &ServiceNowClient,
    config: &Config,
    output: &OutputConfig,
) -> Result<(), ApiError> {
    match command {
        TablesCommand::List {
            table,
            query,
            fields,
            limit,
            offset,
            all,
            display_value,
        } => {
            let fields = parse_fields(fields.as_deref());
            let records = client
                .list_records(
                    &table,
                    &ListOptions {
                        query,
                        fields: fields.clone(),
                        limit,
                        offset,
                        all,
                        display_value,
                    },
                )
                .await?;
            emit_records(output, records, fields.as_deref());
        }
        TablesCommand::Get {
            table,
            sys_id,
            fields,
            display_value,
        } => {
            let fields = parse_fields(fields.as_deref());
            let record = client
                .get_record(&table, &sys_id, fields.as_deref(), display_value)
                .await?;
            emit_record(output, record);
        }
        TablesCommand::Create {
            table,
            data,
            fields,
        } => {
            config.require_writable()?;
            let body = build_body(data.as_deref(), &fields)?;
            let record = client.create_record(&table, &body).await?;
            output.message("Record created.");
            emit_record(output, record);
        }
        TablesCommand::Update {
            table,
            sys_id,
            data,
            fields,
        } => {
            config.require_writable()?;
            let body = build_body(data.as_deref(), &fields)?;
            let record = client.update_record(&table, &sys_id, &body).await?;
            output.message("Record updated.");
            emit_record(output, record);
        }
        TablesCommand::Delete { table, sys_id, yes } => {
            config.require_writable()?;
            confirm_destructive(
                yes,
                format!("Permanently delete {table}/{sys_id}?"),
                "table record deletion cancelled; use --yes for non-interactive deletion",
            )?;
            client.delete_record(&table, &sys_id).await?;
            let result = serde_json::json!({
                "deleted": true,
                "table": table,
                "sys_id": sys_id,
            });
            if output.json {
                output.value(&result);
            } else {
                outln!("Deleted {table}/{sys_id}.");
            }
        }
    }
    Ok(())
}

async fn resolve_incident(
    client: &ServiceNowClient,
    identifier: &str,
    fields: Option<Vec<String>>,
    display_value: DisplayValue,
) -> Result<Value, ApiError> {
    record::resolve(client, "incident", identifier, fields, display_value).await
}

fn emit_records(output: &OutputConfig, records: Vec<Value>, fields: Option<&[String]>) {
    emit_records_or(output, records, fields, "No records found.");
}

fn emit_records_or(
    output: &OutputConfig,
    records: Vec<Value>,
    fields: Option<&[String]>,
    empty_message: &str,
) {
    if output.json {
        output.value(&serde_json::json!({
            "count": records.len(),
            "result": records,
        }));
    } else {
        print_records_or(&records, fields, output.color, empty_message);
    }
}

fn emit_record(output: &OutputConfig, record: Value) {
    if output.json {
        output.value(&serde_json::json!({ "result": record }));
    } else {
        print_record(&record, output.color);
    }
}

fn combine_query(first: Option<&str>, second: Option<&str>) -> Option<String> {
    match (
        first.filter(|value| !value.is_empty()),
        second.filter(|value| !value.is_empty()),
    ) {
        (Some(first), Some(second)) => Some(format!("{first}^{second}")),
        (Some(value), None) | (None, Some(value)) => Some(value.to_string()),
        (None, None) => None,
    }
}

fn insert(body: &mut Map<String, Value>, name: &str, value: Option<String>) {
    if let Some(value) = value {
        body.insert(name.into(), Value::String(value));
    }
}

fn field_text(record: &Value, field: &str) -> Option<String> {
    let value = record.get(field)?;
    match value {
        Value::String(value) => Some(value.clone()),
        Value::Bool(value) => Some(value.to_string()),
        Value::Number(value) => Some(value.to_string()),
        Value::Object(value) => value
            .get("display_value")
            .and_then(Value::as_str)
            .or_else(|| value.get("value").and_then(Value::as_str))
            .map(str::to_string),
        _ => None,
    }
}

fn mask_secret(secret: &str) -> String {
    if secret.chars().count() <= 4 {
        "****".into()
    } else {
        let suffix: String = secret
            .chars()
            .rev()
            .take(4)
            .collect::<String>()
            .chars()
            .rev()
            .collect();
        format!("***{suffix}")
    }
}

fn command_document(command: &clap::Command, selected_path: Option<&str>) -> Value {
    let path = selected_path.unwrap_or(command.get_name());
    let mut schema = command_schema(command, path);
    let object = schema
        .as_object_mut()
        .expect("command schema is always an object");
    object.insert("schemaVersion".into(), Value::String("1.0".into()));
    object.insert(
        "outputContract".into(),
        serde_json::json!({
            "default": "human table on a terminal; JSON when piped",
            "listEnvelope": {"count": "integer", "result": "array"},
            "recordEnvelope": {"result": "object"},
            "errorEnvelope": {"error": {
                "kind": "string", "message": "string", "remediation": "string|null",
                "cart": "{sys_id: string}, only with kind not_ordered"
            }},
            "streams": {"stdout": "data", "stderr": "status and errors"},
            "exitCodes": {
                "0": "success", "1": "unexpected", "2": "invalid_input", "3": "auth or permission",
                "4": "not_found", "5": "api_error", "6": "rate_limit", "7": "conflict",
                "8": "not_ordered"
            }
        }),
    );
    schema
}

fn find_command<'a>(root: &'a clap::Command, path: &str) -> Result<&'a clap::Command, ApiError> {
    let mut command = root;
    let mut parts = path.split_whitespace().peekable();
    if parts.peek().is_none() {
        return Err(ApiError::InvalidInput("--command cannot be empty".into()));
    }
    if parts.peek().copied() == Some(root.get_name()) {
        parts.next();
    }
    for part in parts {
        command = command.find_subcommand(part).ok_or_else(|| {
            ApiError::NotFound(format!(
                "command '{path}'; inspect available commands with `servicenow schema`"
            ))
        })?;
    }
    Ok(command)
}

fn command_schema(command: &clap::Command, path: &str) -> Value {
    let args: Vec<Value> = command
        .get_arguments()
        .filter(|arg| arg.get_id() != "help" && arg.get_id() != "version")
        .map(|arg| {
            let range = arg.get_num_args();
            let takes_value = !matches!(
                arg.get_action(),
                clap::ArgAction::SetTrue | clap::ArgAction::SetFalse | clap::ArgAction::Count
            );
            let minimum = range
                .map(|range| range.min_values())
                .unwrap_or(usize::from(takes_value && arg.is_required_set()));
            let max_values = range
                .and_then(|range| {
                    (range.max_values() != usize::MAX).then_some(range.max_values())
                })
                .or(takes_value.then_some(1));
            let possible_values: Vec<String> = arg
                .get_possible_values()
                .into_iter()
                .map(|value| value.get_name().to_string())
                .collect();
            let default_values: Vec<String> = arg
                .get_default_values()
                .iter()
                .map(|value| value.to_string_lossy().into_owned())
                .collect();
            serde_json::json!({
                "id": arg.get_id().as_str(),
                "long": arg.get_long(),
                "short": arg.get_short().map(|value| value.to_string()),
                "required": arg.is_required_set(),
                "help": arg.get_help().map(|value| value.to_string()),
                "type": argument_type(arg, &possible_values),
                "action": argument_action(arg.get_action()),
                "valueCardinality": {
                    "minimum": minimum,
                    "maximum": max_values,
                },
                "defaultValues": default_values,
                "possibleValues": possible_values,
                "repeatable": matches!(arg.get_action(), clap::ArgAction::Append | clap::ArgAction::Count),
                "global": arg.is_global_set(),
                "environment": arg.get_env().map(|value| value.to_string_lossy().into_owned()),
                "valueHint": format!("{:?}", arg.get_value_hint()).to_lowercase(),
                "dynamicDefault": argument_dynamic_default(path, arg.get_id().as_str()),
            })
        })
        .collect();
    let commands: Vec<Value> = command
        .get_subcommands()
        .map(|subcommand| {
            let subcommand_path = format!("{path} {}", subcommand.get_name());
            command_schema(subcommand, &subcommand_path)
        })
        .collect();
    serde_json::json!({
        "name": command.get_name(),
        "path": path,
        "about": command.get_about().map(|value| value.to_string()),
        "arguments": args,
        "argumentGroups": command_argument_groups(path),
        "commands": commands,
        "behavior": command_behavior(path),
    })
}

fn command_argument_groups(path: &str) -> Vec<Value> {
    if path.ends_with("incidents resolve") {
        vec![serde_json::json!({
            "id": "resolution_notes",
            "arguments": ["notes", "notes_file"],
            "required": true,
            "multiple": false,
        })]
    } else {
        Vec::new()
    }
}

fn argument_dynamic_default(path: &str, argument: &str) -> Option<&'static str> {
    if argument == "display_value" {
        return Some("display values for text output; raw values for machine output");
    }
    if path.ends_with("incidents resolve") && argument == "state" {
        return Some(
            "the configured Resolved choice; standard value 6 when choices are unavailable",
        );
    }
    if path.ends_with("init") || path.ends_with("auth login") {
        return match argument {
            "instance" => Some("saved profile value when resuming; otherwise prompted"),
            "method" => Some(
                "saved profile value when resuming; otherwise detected from the instance login route",
            ),
            "scope" => Some("saved profile value when resuming; otherwise useraccount"),
            "redirect_uri" => {
                Some("saved profile value when resuming; otherwise http://127.0.0.1:8484/callback")
            }
            _ => None,
        };
    }
    None
}

fn argument_type(arg: &clap::Arg, possible_values: &[String]) -> &'static str {
    match arg.get_action() {
        clap::ArgAction::SetTrue | clap::ArgAction::SetFalse => "boolean",
        clap::ArgAction::Count => "integer",
        _ if !possible_values.is_empty() => "enum",
        _ if matches!(
            arg.get_id().as_str(),
            "limit" | "offset" | "interval" | "count"
        ) =>
        {
            "integer"
        }
        _ => "string",
    }
}

fn argument_action(action: &clap::ArgAction) -> &'static str {
    match action {
        clap::ArgAction::Set => "set",
        clap::ArgAction::Append => "append",
        clap::ArgAction::SetTrue => "set_true",
        clap::ArgAction::SetFalse => "set_false",
        clap::ArgAction::Count => "count",
        clap::ArgAction::Help => "help",
        clap::ArgAction::HelpShort => "help_short",
        clap::ArgAction::HelpLong => "help_long",
        clap::ArgAction::Version => "version",
        _ => "other",
    }
}

fn command_behavior(path: &str) -> Value {
    let remote_mutations = [
        "tui",
        "incidents create",
        "incidents update",
        "incidents resolve",
        "incidents edit",
        "incidents note",
        "incidents assign",
        "attachments upload",
        "attachments delete",
        "tables create",
        "tables update",
        "tables delete",
        "catalog order",
        "catalog cart submit",
        "catalog cart remove",
        "catalog cart clear",
    ];
    let local_mutations = [
        "init",
        "auth login",
        "auth logout",
        "profile use",
        "profile remove",
        "attachments download",
    ];
    let mutation = remote_mutations.iter().any(|suffix| path.ends_with(suffix))
        || local_mutations.iter().any(|suffix| path.ends_with(suffix));
    let remote_mutation = remote_mutations.iter().any(|suffix| path.ends_with(suffix));
    let local_mutation = local_mutations.iter().any(|suffix| path.ends_with(suffix));
    let side_effect = if path.ends_with("init") || path.ends_with("auth login") {
        "local_and_remote"
    } else if remote_mutation {
        "remote"
    } else if local_mutation {
        "local"
    } else {
        "none"
    };
    let network_access = if path == "servicenow"
        || path == "auth"
        || path == "schema"
        || path == "doctor"
        || path.ends_with(" auth")
        || path.ends_with(" schema")
        || path.ends_with("auth status")
    {
        "conditional"
    } else if path == "profile"
        || path == "config"
        || path.ends_with(" profile")
        || path.ends_with(" config")
        || path.ends_with("completions")
        || path.ends_with("profile list")
        || path.ends_with("profile use")
        || path.ends_with("profile remove")
        || path.ends_with("auth logout")
        || path.ends_with("config show")
        || path.ends_with("config init")
        || path.ends_with("config path")
    {
        "none"
    } else {
        "required"
    };
    let destructive = path.ends_with("attachments delete")
        || path.ends_with("tables delete")
        || path.ends_with("catalog cart remove")
        || path.ends_with("catalog cart clear")
        || path.ends_with("profile remove");
    let requires_confirmation = destructive
        || path.ends_with("incidents edit")
        || path.ends_with("catalog order")
        || path.ends_with("catalog cart submit")
        || path.ends_with("tui");
    let supports_dry_run = [
        "catalog order",
        "incidents resolve",
        "incidents edit",
        "incidents note",
        "incidents assign",
        "attachments upload",
        "attachments delete",
    ]
    .iter()
    .any(|suffix| path.ends_with(suffix));
    serde_json::json!({
        "sideEffect": side_effect,
        "networkAccess": network_access,
        "mutation": mutation,
        "destructive": destructive,
        "requiresConfirmation": requires_confirmation,
        "supportsDryRun": supports_dry_run,
    })
}

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

    fn raw_flags(args: &[&str]) -> (String, bool) {
        let args: Vec<std::ffi::OsString> = std::iter::once("servicenow")
            .chain(args.iter().copied())
            .map(Into::into)
            .collect();
        raw_output_flags(&args)
    }

    #[test]
    fn raw_output_flags_recognize_every_spelling_clap_accepts() {
        for spelling in [
            &["--output", "yaml"][..],
            &["--output=yaml"],
            &["-o", "yaml"],
            &["-oyaml"],
            &["-o=yaml"],
        ] {
            assert_eq!(raw_flags(spelling), ("yaml".into(), false), "{spelling:?}");
        }
        assert_eq!(raw_flags(&["--json", "bogus"]), ("auto".into(), true));
        assert_eq!(raw_flags(&["bogus"]), ("auto".into(), false));
    }

    #[test]
    fn raw_output_flags_ignore_positional_values_after_the_separator() {
        assert_eq!(
            raw_flags(&["-o", "text", "tables", "get", "--", "-ojson", "--json"]),
            ("text".into(), false)
        );
    }

    #[test]
    fn explicit_formats_decide_error_rendering_regardless_of_the_json_alias() {
        assert!(machine_readable_errors("csv", false));
        assert!(!machine_readable_errors("text", true));
        assert!(!machine_readable_errors("table", true));
        assert!(machine_readable_errors("auto", true));
    }

    #[test]
    fn tui_recovers_only_connection_and_authentication_failures() {
        assert!(tui_login_recoverable(&ApiError::InvalidInput(
            "No ServiceNow instance configured. Run `servicenow init`.".into()
        )));
        assert!(tui_login_recoverable(&ApiError::NotFound(
            "config profile 'work'. Available: none defined".into()
        )));
        assert!(tui_login_recoverable(&ApiError::Auth(
            "browser session expired".into()
        )));
        assert!(!tui_login_recoverable(&ApiError::InvalidInput(
            "invalid table name".into()
        )));
        assert!(!tui_login_recoverable(&ApiError::RateLimit));
    }

    #[test]
    fn tui_connection_copy_removes_dead_end_command_instructions() {
        let reason = tui_connection_reason(&ApiError::InvalidInput(
            "No access token configured. Run `servicenow init`.".into(),
        ));
        assert_eq!(
            reason,
            "This profile does not have a usable credential yet."
        );
        assert!(!reason.contains("servicenow init"));
    }
}