codex-helper-core 0.17.0

Core library for codex-helper.
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
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
use std::collections::BTreeSet;
use std::fs;
use std::io::{Read, Seek, SeekFrom};
use std::path::{Path, PathBuf};

use crate::client_config::{
    CLAUDE_ABSENT_BACKUP_SENTINEL, claude_settings_backup_path_for as claude_settings_backup_path,
    claude_settings_path, codex_app_db_path, codex_auth_path, codex_config_path,
    codex_switch_state_path,
};
use crate::codex_patch_plan::{
    CodexAuthPatchPlan, CodexPatchPlan, CodexSwitchOnEffectOrder, CodexTomlBoolPatch,
};
pub use crate::codex_patch_plan::{CodexPatchMode, CodexSwitchOptions};
use crate::config::{ProxyConfig, ProxyConfigV2, ProxyConfigV4, RoutingAffinityPolicyV5};
use crate::file_replace::write_text_file;
use anyhow::{Context, Result, anyhow};
use toml::Value;
use toml_edit::{
    Document as EditableTomlDocument, Item as EditableTomlItem, Table as EditableTomlTable,
    Value as EditableTomlValue, value as editable_toml_value,
};

fn read_config_text(path: &Path) -> Result<String> {
    if !path.exists() {
        return Ok(String::new());
    }
    let mut file = fs::File::open(path).with_context(|| format!("open {:?}", path))?;
    let mut buf = String::new();
    file.read_to_string(&mut buf)
        .with_context(|| format!("read {:?}", path))?;
    Ok(buf)
}

fn atomic_write(path: &Path, data: &str) -> Result<()> {
    write_text_file(path, data)
}

fn set_toml_value_preserving_decor(item: &mut EditableTomlItem, mut value: EditableTomlValue) {
    if let Some(current) = item.as_value_mut() {
        let decor = current.decor().clone();
        *value.decor_mut() = decor;
        *current = value;
    } else {
        *item = EditableTomlItem::Value(value);
    }
}

fn set_toml_string(table: &mut EditableTomlTable, key: &str, value: impl Into<String>) {
    let item = table.entry(key).or_insert(EditableTomlItem::None);
    set_toml_value_preserving_decor(item, EditableTomlValue::from(value.into()));
}

fn toml_string(table: &EditableTomlTable, key: &str) -> Option<String> {
    table
        .get(key)
        .and_then(EditableTomlItem::as_value)
        .and_then(EditableTomlValue::as_str)
        .map(ToOwned::to_owned)
}

fn local_helper_proxy_item(item: Option<&EditableTomlItem>) -> bool {
    let Some(table) = item.and_then(EditableTomlItem::as_table) else {
        return false;
    };
    let name_is_helper = toml_string(table, "name").as_deref() == Some("codex-helper");
    let base_url_is_local = toml_string(table, "base_url")
        .as_deref()
        .is_some_and(|url| url.contains("127.0.0.1") || url.contains("localhost"));
    name_is_helper || base_url_is_local
}

fn codex_text_points_to_local_helper(text: &str) -> Result<bool> {
    if text.trim().is_empty() {
        return Ok(false);
    }
    let doc = text.parse::<EditableTomlDocument>()?;
    let root = doc.as_table();
    if toml_string(root, "model_provider").as_deref() != Some("codex_proxy") {
        return Ok(false);
    }
    Ok(root
        .get("model_providers")
        .and_then(EditableTomlItem::as_table)
        .and_then(|table| table.get("codex_proxy"))
        .is_some_and(|item| local_helper_proxy_item(Some(item))))
}

#[derive(Debug, Clone, PartialEq, serde::Deserialize, serde::Serialize)]
struct CodexSwitchState {
    version: u32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    patch_mode: Option<CodexPatchMode>,
    #[serde(default, skip_serializing_if = "bool_is_false")]
    responses_websocket: bool,
    original_config_absent: bool,
    original_model_provider: Option<String>,
    original_codex_proxy: Option<Value>,
    had_model_providers: bool,
    #[serde(default)]
    original_auth_json_absent: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    original_auth_json: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    patched_auth_json: Option<String>,
}

impl CodexSwitchState {
    fn from_codex_config_text(text: &str, original_config_absent: bool) -> Result<Self> {
        let doc = if text.trim().is_empty() {
            EditableTomlDocument::new()
        } else {
            text.parse::<EditableTomlDocument>()?
        };
        let root = doc.as_table();
        let providers_table = root
            .get("model_providers")
            .and_then(EditableTomlItem::as_table);

        Ok(Self {
            version: 2,
            patch_mode: None,
            responses_websocket: false,
            original_config_absent,
            original_model_provider: toml_string(root, "model_provider"),
            original_codex_proxy: original_codex_proxy_value(text)?,
            had_model_providers: providers_table.is_some(),
            original_auth_json_absent: false,
            original_auth_json: None,
            patched_auth_json: None,
        })
    }

    fn set_auth_patch(&mut self, patch: &CodexAuthPatch) {
        self.original_auth_json_absent = patch.original_absent;
        self.original_auth_json = patch.original_text.clone();
        self.patched_auth_json = Some(patch.patched_text.clone());
    }

    fn clear_auth_patch(&mut self) {
        self.original_auth_json_absent = false;
        self.original_auth_json = None;
        self.patched_auth_json = None;
    }
}

fn original_codex_proxy_value(text: &str) -> Result<Option<Value>> {
    if text.trim().is_empty() {
        return Ok(None);
    }
    let value = text.parse::<Value>()?;
    Ok(value
        .as_table()
        .and_then(|root| root.get("model_providers"))
        .and_then(Value::as_table)
        .and_then(|providers| providers.get("codex_proxy"))
        .cloned())
}

fn editable_item_from_toml_value(value: &Value) -> Result<EditableTomlItem> {
    match value {
        Value::Table(table) => {
            let body = toml::to_string(table)?;
            let doc = format!("[codex_proxy]\n{body}").parse::<EditableTomlDocument>()?;
            doc.as_table()
                .get("codex_proxy")
                .cloned()
                .ok_or_else(|| anyhow!("failed to parse stored codex_proxy state"))
        }
        _ => Err(anyhow!("stored codex_proxy state must be a TOML table")),
    }
}

fn read_codex_switch_state() -> Result<Option<CodexSwitchState>> {
    let path = codex_switch_state_path();
    if !path.exists() {
        return Ok(None);
    }
    let text = read_config_text(&path)?;
    let state = serde_json::from_str::<CodexSwitchState>(&text)
        .with_context(|| format!("parse {:?}", path))?;
    Ok(Some(state))
}

fn write_codex_switch_state(state: &CodexSwitchState) -> Result<()> {
    let path = codex_switch_state_path();
    let text = serde_json::to_string_pretty(state)?;
    atomic_write(&path, &text)
}

pub fn codex_switch_state_exists() -> bool {
    codex_switch_state_path().exists()
}

fn bool_is_false(value: &bool) -> bool {
    !*value
}

enum CodexSwitchOffEdit {
    Write(String),
    RemoveFile,
}

struct CodexAuthPatch {
    original_absent: bool,
    original_text: Option<String>,
    patched_text: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum CodexAuthEdit {
    None,
    Write(String),
    RemoveFile,
}

fn auth_json_matches_helper_patch(current_text: Option<&str>, patched_auth_json: &str) -> bool {
    let Some(current_text) = current_text else {
        return false;
    };
    if current_text == patched_auth_json {
        return true;
    }

    let Ok(current_value) = serde_json::from_str::<serde_json::Value>(current_text) else {
        return false;
    };
    let Ok(patched_value) = serde_json::from_str::<serde_json::Value>(patched_auth_json) else {
        return false;
    };
    current_value == patched_value
}

fn apply_codex_auth_edit(edit: CodexAuthEdit) -> Result<()> {
    match edit {
        CodexAuthEdit::None => Ok(()),
        CodexAuthEdit::Write(text) => atomic_write(&codex_auth_path(), &text)
            .with_context(|| format!("patch {:?}", codex_auth_path())),
        CodexAuthEdit::RemoveFile => {
            let path = codex_auth_path();
            if path.exists() {
                fs::remove_file(&path).with_context(|| format!("remove {:?}", path))?;
            }
            Ok(())
        }
    }
}

fn read_current_codex_auth_text() -> Result<Option<String>> {
    let path = codex_auth_path();
    if path.exists() {
        read_config_text(&path).map(Some)
    } else {
        Ok(None)
    }
}

fn auth_restore_edit_from_state(state: &mut CodexSwitchState) -> Result<CodexAuthEdit> {
    let current_text = read_current_codex_auth_text()?;
    Ok(auth_restore_edit_from_state_and_current(
        state,
        current_text.as_deref(),
    ))
}

fn auth_restore_edit_from_state_and_current(
    state: &mut CodexSwitchState,
    current_text: Option<&str>,
) -> CodexAuthEdit {
    let Some(patched_auth_json) = state.patched_auth_json.as_deref() else {
        return CodexAuthEdit::None;
    };

    let edit = if auth_json_matches_helper_patch(current_text, patched_auth_json) {
        if state.original_auth_json_absent {
            CodexAuthEdit::RemoveFile
        } else if let Some(original) = state.original_auth_json.clone() {
            CodexAuthEdit::Write(original)
        } else {
            CodexAuthEdit::None
        }
    } else {
        CodexAuthEdit::None
    };

    state.clear_auth_patch();
    edit
}

fn auth_baseline_for_patch_from_current(
    state: &CodexSwitchState,
    current_text: Option<String>,
) -> (bool, Option<String>) {
    if let Some(patched_auth_json) = state.patched_auth_json.as_deref()
        && auth_json_matches_helper_patch(current_text.as_deref(), patched_auth_json)
    {
        return (
            state.original_auth_json_absent,
            state.original_auth_json.clone(),
        );
    }

    (current_text.is_none(), current_text)
}

fn switch_off_codex_toml(
    current_text: &str,
    original: &CodexSwitchState,
) -> Result<CodexSwitchOffEdit> {
    let mut doc = if current_text.trim().is_empty() {
        EditableTomlDocument::new()
    } else {
        current_text.parse::<EditableTomlDocument>()?
    };
    let root = doc.as_table_mut();

    let current_model_provider = toml_string(root, "model_provider");
    let proxy_is_helper = root
        .get("model_providers")
        .and_then(EditableTomlItem::as_table)
        .and_then(|table| table.get("codex_proxy"))
        .map(|item| local_helper_proxy_item(Some(item)))
        .unwrap_or(current_model_provider.as_deref() == Some("codex_proxy"));

    if current_model_provider.as_deref() == Some("codex_proxy") && proxy_is_helper {
        if let Some(provider) = original.original_model_provider.as_deref() {
            set_toml_string(root, "model_provider", provider);
        } else {
            root.remove("model_provider");
        }
    }

    let mut remove_model_providers = false;
    if let Some(providers_table) = root
        .get_mut("model_providers")
        .and_then(EditableTomlItem::as_table_mut)
    {
        let proxy_is_helper = local_helper_proxy_item(providers_table.get("codex_proxy"));
        if proxy_is_helper {
            if let Some(original_proxy) = original.original_codex_proxy.as_ref() {
                providers_table.insert(
                    "codex_proxy",
                    editable_item_from_toml_value(original_proxy)?,
                );
            } else {
                providers_table.remove("codex_proxy");
            }
        }
        remove_model_providers = !original.had_model_providers && providers_table.is_empty();
    }
    if remove_model_providers {
        root.remove("model_providers");
    }

    if original.original_config_absent && root.is_empty() {
        Ok(CodexSwitchOffEdit::RemoveFile)
    } else {
        Ok(CodexSwitchOffEdit::Write(doc.to_string()))
    }
}

fn codex_config_text_with_switch_state(
    current_text: &str,
    state: &CodexSwitchState,
) -> Result<String> {
    let mut doc = if current_text.trim().is_empty() {
        EditableTomlDocument::new()
    } else {
        current_text.parse::<EditableTomlDocument>()?
    };
    let root = doc.as_table_mut();
    let current_model_provider = toml_string(root, "model_provider");
    let proxy_is_helper = root
        .get("model_providers")
        .and_then(EditableTomlItem::as_table)
        .and_then(|table| table.get("codex_proxy"))
        .map(|item| local_helper_proxy_item(Some(item)))
        .unwrap_or(current_model_provider.as_deref() == Some("codex_proxy"));

    if current_model_provider.as_deref() != Some("codex_proxy") || !proxy_is_helper {
        return Ok(current_text.to_string());
    }

    if let Some(provider) = state.original_model_provider.as_deref() {
        set_toml_string(root, "model_provider", provider);
    } else {
        root.remove("model_provider");
    }

    let mut remove_model_providers = false;
    if let Some(providers_table) = root
        .get_mut("model_providers")
        .and_then(EditableTomlItem::as_table_mut)
    {
        if let Some(original_proxy) = state.original_codex_proxy.as_ref() {
            providers_table.insert(
                "codex_proxy",
                editable_item_from_toml_value(original_proxy)?,
            );
        } else {
            providers_table.remove("codex_proxy");
        }
        remove_model_providers = !state.had_model_providers && providers_table.is_empty();
    }
    if remove_model_providers {
        root.remove("model_providers");
    }

    Ok(doc.to_string())
}

pub fn codex_config_text_for_import() -> Result<Option<String>> {
    let cfg_path = codex_config_path();
    if !cfg_path.exists() {
        return Ok(None);
    }
    let current_text = read_config_text(&cfg_path)?;
    let Some(state) = read_codex_switch_state()? else {
        return Ok(Some(current_text));
    };
    codex_config_text_with_switch_state(&current_text, &state).map(Some)
}

#[cfg(test)]
fn switch_on_codex_toml_with_mode(text: &str, port: u16, mode: CodexPatchMode) -> Result<String> {
    switch_on_codex_toml_with_options(text, port, mode, CodexSwitchOptions::default())
}

#[cfg(test)]
fn switch_on_codex_toml_with_options(
    text: &str,
    port: u16,
    mode: CodexPatchMode,
    options: CodexSwitchOptions,
) -> Result<String> {
    let plan = CodexPatchPlan::for_switch_on(mode, options)?;
    switch_on_codex_toml_with_plan(text, port, plan)
}

fn switch_on_codex_toml_with_plan(text: &str, port: u16, plan: CodexPatchPlan) -> Result<String> {
    let mut doc = if text.trim().is_empty() {
        EditableTomlDocument::new()
    } else {
        text.parse::<EditableTomlDocument>()?
    };
    let root = doc.as_table_mut();

    if !root.contains_key("model_providers") {
        root.insert(
            "model_providers",
            EditableTomlItem::Table(EditableTomlTable::new()),
        );
    }
    let providers_table = root
        .get_mut("model_providers")
        .and_then(EditableTomlItem::as_table_mut)
        .ok_or_else(|| anyhow!("model_providers must be a table"))?;

    if !providers_table.contains_key("codex_proxy") {
        providers_table.insert(
            "codex_proxy",
            EditableTomlItem::Table(EditableTomlTable::new()),
        );
    }
    let proxy_table = providers_table
        .get_mut("codex_proxy")
        .and_then(EditableTomlItem::as_table_mut)
        .ok_or_else(|| anyhow!("model_providers.codex_proxy must be a table"))?;

    let provider = plan.provider();
    set_toml_string(proxy_table, "name", provider.provider_name());
    set_toml_string(proxy_table, "base_url", format!("http://127.0.0.1:{port}"));
    set_toml_string(proxy_table, "wire_api", "responses");
    if !proxy_table.contains_key("request_max_retries") {
        proxy_table.insert("request_max_retries", editable_toml_value(0));
    }
    match provider.requires_openai_auth() {
        CodexTomlBoolPatch::Remove => {
            proxy_table.remove("requires_openai_auth");
        }
        CodexTomlBoolPatch::Set(value) => {
            proxy_table.insert("requires_openai_auth", editable_toml_value(value));
        }
    }
    match provider.supports_websockets() {
        CodexTomlBoolPatch::Remove => {
            proxy_table.remove("supports_websockets");
        }
        CodexTomlBoolPatch::Set(value) => {
            proxy_table.insert("supports_websockets", editable_toml_value(value));
        }
    }

    set_toml_string(root, "model_provider", "codex_proxy");
    Ok(doc.to_string())
}

fn ensure_codex_remote_connections_feature_in_toml(text: &str) -> Result<String> {
    let mut doc = if text.trim().is_empty() {
        EditableTomlDocument::new()
    } else {
        text.parse::<EditableTomlDocument>()?
    };
    let root = doc.as_table_mut();

    if !root.contains_key("features") {
        root.insert(
            "features",
            EditableTomlItem::Table(EditableTomlTable::new()),
        );
    }
    let features = root
        .get_mut("features")
        .and_then(EditableTomlItem::as_table_mut)
        .ok_or_else(|| anyhow!("features must be a table"))?;
    features.insert("remote_connections", editable_toml_value(true));
    features.remove("remote_control");

    Ok(doc.to_string())
}

fn codex_remote_connections_feature_enabled_from_toml(text: &str) -> Result<bool> {
    if text.trim().is_empty() {
        return Ok(false);
    }
    let value = text.parse::<Value>()?;
    Ok(value
        .as_table()
        .and_then(|root| root.get("features"))
        .and_then(Value::as_table)
        .and_then(|features| features.get("remote_connections"))
        .and_then(Value::as_bool)
        .unwrap_or(false))
}

fn codex_remote_control_feature_present_in_toml(text: &str) -> Result<bool> {
    if text.trim().is_empty() {
        return Ok(false);
    }
    let value = text.parse::<Value>()?;
    Ok(value
        .as_table()
        .and_then(|root| root.get("features"))
        .and_then(Value::as_table)
        .is_some_and(|features| features.contains_key("remote_control")))
}

fn codex_remote_compaction_v2_feature_enabled_from_toml(text: &str) -> Result<bool> {
    if text.trim().is_empty() {
        return Ok(false);
    }
    let value = text.parse::<Value>()?;
    Ok(value
        .as_table()
        .and_then(|root| root.get("features"))
        .and_then(Value::as_table)
        .and_then(|features| features.get("remote_compaction_v2"))
        .and_then(Value::as_bool)
        .unwrap_or(false))
}

fn json_string_at_path<'a>(value: &'a serde_json::Value, path: &[&str]) -> Option<&'a str> {
    let mut current = value;
    for key in path {
        current = current.get(*key)?;
    }
    current.as_str().filter(|text| !text.trim().is_empty())
}

fn decode_jwt_payload(jwt: &str) -> Result<serde_json::Value> {
    use base64::Engine as _;

    let mut parts = jwt.split('.');
    let (_header, payload, _signature) = match (parts.next(), parts.next(), parts.next()) {
        (Some(header), Some(payload), Some(signature))
            if !header.is_empty() && !payload.is_empty() && !signature.is_empty() =>
        {
            (header, payload, signature)
        }
        _ => return Err(anyhow!("invalid JWT format")),
    };
    let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
        .decode(payload)
        .or_else(|_| base64::engine::general_purpose::URL_SAFE.decode(payload))
        .context("decode JWT payload")?;
    serde_json::from_slice(&bytes).context("parse JWT payload JSON")
}

fn chatgpt_bridge_auth_requirements_missing(
    value: &serde_json::Value,
) -> Result<Vec<&'static str>> {
    let obj = value
        .as_object()
        .ok_or_else(|| anyhow!("Codex auth.json root must be a JSON object"))?;
    let tokens = obj.get("tokens").and_then(serde_json::Value::as_object);
    let mut missing = Vec::new();

    let id_token = match tokens.and_then(|tokens| tokens.get("id_token")) {
        Some(value) => value.as_str().filter(|text| !text.trim().is_empty()),
        None => None,
    };
    let id_token_payload = match id_token {
        Some(id_token) => Some(decode_jwt_payload(id_token).context("decode tokens.id_token")?),
        None => {
            missing.push("tokens.id_token");
            None
        }
    };

    if tokens
        .and_then(|tokens| tokens.get("access_token"))
        .and_then(serde_json::Value::as_str)
        .is_none_or(|text| text.trim().is_empty())
    {
        missing.push("tokens.access_token");
    }
    if tokens
        .and_then(|tokens| tokens.get("refresh_token"))
        .and_then(serde_json::Value::as_str)
        .is_none_or(|text| text.trim().is_empty())
    {
        missing.push("tokens.refresh_token");
    }
    if obj
        .get("last_refresh")
        .is_none_or(serde_json::Value::is_null)
    {
        missing.push("last_refresh");
    }

    if let Some(payload) = id_token_payload.as_ref() {
        let has_email = json_string_at_path(payload, &["email"])
            .or_else(|| json_string_at_path(payload, &["https://api.openai.com/profile", "email"]))
            .is_some();
        if !has_email {
            missing.push("tokens.id_token.email");
        }

        let has_account_id = tokens
            .and_then(|tokens| tokens.get("account_id"))
            .and_then(serde_json::Value::as_str)
            .is_some_and(|text| !text.trim().is_empty())
            || json_string_at_path(
                payload,
                &["https://api.openai.com/auth", "chatgpt_account_id"],
            )
            .is_some();
        if !has_account_id {
            missing.push("tokens.account_id or tokens.id_token.chatgpt_account_id");
        }
    }

    Ok(missing)
}

fn ensure_chatgpt_bridge_auth_ready(value: &serde_json::Value) -> Result<()> {
    let missing = chatgpt_bridge_auth_requirements_missing(value)?;
    if missing.is_empty() {
        return Ok(());
    }

    Err(anyhow!(
        "Codex auth.json does not contain a complete ChatGPT login state required for chatgpt-bridge (missing: {}). Open Codex and sign in with ChatGPT first, then run `codex-helper switch on --mode chatgpt-bridge` again.",
        missing.join(", ")
    ))
}

fn chatgpt_bridge_auth_json_value(mut value: serde_json::Value) -> Result<serde_json::Value> {
    ensure_chatgpt_bridge_auth_ready(&value)?;
    let obj = value
        .as_object_mut()
        .ok_or_else(|| anyhow!("Codex auth.json root must be a JSON object"))?;
    obj.insert(
        "auth_mode".to_string(),
        serde_json::Value::String("chatgpt".to_string()),
    );
    obj.insert("OPENAI_API_KEY".to_string(), serde_json::Value::Null);
    Ok(value)
}

fn chatgpt_bridge_auth_json_text(text: &str) -> Result<String> {
    let mut value: serde_json::Value =
        serde_json::from_str(text).context("parse Codex auth.json as JSON")?;
    value = chatgpt_bridge_auth_json_value(value)?;
    Ok(serde_json::to_string_pretty(&value)?)
}

fn imagegen_bridge_auth_json_text() -> Result<String> {
    Ok(serde_json::to_string_pretty(&serde_json::json!({}))?)
}

fn auth_json_is_empty_chatgpt_facade_text(text: Option<&str>) -> bool {
    let Some(text) = text else {
        return false;
    };
    serde_json::from_str::<serde_json::Value>(text)
        .ok()
        .and_then(|value| value.as_object().cloned())
        .is_some_and(|object| object.is_empty())
}

fn current_auth_json_is_empty_chatgpt_facade() -> bool {
    let path = codex_auth_path();
    if !path.exists() {
        return false;
    }
    let Ok(text) = read_config_text(&path) else {
        return false;
    };
    auth_json_is_empty_chatgpt_facade_text(Some(&text))
}

fn current_auth_json_facade_state() -> Result<Option<bool>> {
    let path = codex_auth_path();
    if !path.exists() {
        return Ok(None);
    }
    let text = read_config_text(&path).with_context(|| format!("read {:?}", path))?;
    Ok(Some(auth_json_is_empty_chatgpt_facade_text(Some(&text))))
}

fn prepare_chatgpt_bridge_auth_patch_from_baseline(
    original_absent: bool,
    original_text: Option<String>,
) -> Result<CodexAuthPatch> {
    let auth_path = codex_auth_path();
    let Some(original_text) = original_text else {
        return Err(anyhow!(
            "Codex auth.json not found at {:?}; run `codex login` first, then enable chatgpt-bridge preset.",
            auth_path
        ));
    };
    if original_absent {
        return Err(anyhow!(
            "Codex auth.json not found at {:?}; run `codex login` first, then enable chatgpt-bridge preset.",
            auth_path
        ));
    }
    let patched_text = chatgpt_bridge_auth_json_text(&original_text)?;
    Ok(CodexAuthPatch {
        original_absent: false,
        original_text: Some(original_text),
        patched_text,
    })
}

fn prepare_imagegen_bridge_auth_patch_from_baseline(
    original_absent: bool,
    original_text: Option<String>,
) -> Result<CodexAuthPatch> {
    Ok(CodexAuthPatch {
        original_absent,
        original_text,
        patched_text: imagegen_bridge_auth_json_text()?,
    })
}

fn auth_edit_for_switch_on_plan(
    plan: CodexPatchPlan,
    state: &mut CodexSwitchState,
) -> Result<CodexAuthEdit> {
    match plan.auth() {
        CodexAuthPatchPlan::RestoreOriginalIfHelperPatched => auth_restore_edit_from_state(state),
        CodexAuthPatchPlan::PatchChatGptBridge | CodexAuthPatchPlan::PatchImagegenFacade => {
            let current_auth = read_current_codex_auth_text()?;
            let (original_absent, original_text) =
                auth_baseline_for_patch_from_current(state, current_auth.clone());
            let patch = match plan.auth() {
                CodexAuthPatchPlan::PatchChatGptBridge => {
                    prepare_chatgpt_bridge_auth_patch_from_baseline(original_absent, original_text)?
                }
                CodexAuthPatchPlan::PatchImagegenFacade => {
                    prepare_imagegen_bridge_auth_patch_from_baseline(
                        original_absent,
                        original_text,
                    )?
                }
                CodexAuthPatchPlan::RestoreOriginalIfHelperPatched => {
                    unreachable!("handled above")
                }
            };
            let auth_edit = if auth_json_matches_helper_patch(
                current_auth.as_deref(),
                patch.patched_text.as_str(),
            ) {
                CodexAuthEdit::None
            } else {
                CodexAuthEdit::Write(patch.patched_text.clone())
            };
            state.set_auth_patch(&patch);
            Ok(auth_edit)
        }
    }
}

fn apply_switch_on_effects(
    plan: CodexPatchPlan,
    cfg_path: &Path,
    new_text: &str,
    state: &CodexSwitchState,
    auth_edit: CodexAuthEdit,
) -> Result<()> {
    match plan.effect_order() {
        CodexSwitchOnEffectOrder::ConfigAuthState => {
            atomic_write(cfg_path, new_text)?;
            apply_codex_auth_edit(auth_edit)?;
            write_codex_switch_state(state)?;
        }
        CodexSwitchOnEffectOrder::StateConfigAuth => {
            write_codex_switch_state(state)?;
            atomic_write(cfg_path, new_text)?;
            apply_codex_auth_edit(auth_edit)?;
        }
    }
    Ok(())
}

fn auth_env_is_set(env_name: &str) -> bool {
    let env_name = env_name.trim();
    !env_name.is_empty() && std::env::var(env_name).is_ok_and(|value| !value.trim().is_empty())
}

fn upstream_auth_has_resolved_credential(auth: &crate::config::UpstreamAuth) -> bool {
    auth.auth_token
        .as_deref()
        .is_some_and(|token| !token.trim().is_empty())
        || auth
            .api_key
            .as_deref()
            .is_some_and(|key| !key.trim().is_empty())
        || auth.auth_token_env.as_deref().is_some_and(auth_env_is_set)
        || auth.api_key_env.as_deref().is_some_and(auth_env_is_set)
}

fn upstream_has_resolved_auth(upstream: &crate::config::UpstreamConfig) -> bool {
    upstream_auth_has_resolved_credential(&upstream.auth)
}

fn upstream_auth_env_names(upstream: &crate::config::UpstreamConfig) -> impl Iterator<Item = &str> {
    upstream
        .auth
        .auth_token_env
        .as_deref()
        .into_iter()
        .chain(upstream.auth.api_key_env.as_deref())
        .map(str::trim)
        .filter(|value| !value.is_empty())
}

fn config_toml_schema_version_or_shape(text: &str) -> Option<u32> {
    let value = toml::from_str::<toml::Value>(text).ok()?;
    if let Some(version) = value
        .get("version")
        .and_then(|value| value.as_integer())
        .map(|value| value as u32)
    {
        return Some(version);
    }

    let has_v4_routing = ["codex", "claude"].iter().any(|service| {
        value
            .get(*service)
            .and_then(|service| service.get("routing"))
            .and_then(|routing| routing.get("entry").or_else(|| routing.get("routes")))
            .is_some()
    });
    if has_v4_routing {
        return Some(4);
    }

    let has_legacy_routing = ["codex", "claude"].iter().any(|service| {
        value
            .get(*service)
            .and_then(|service| service.get("routing"))
            .is_some()
    });
    if has_legacy_routing { Some(3) } else { None }
}

fn load_runtime_config_for_bridge_check() -> Result<ProxyConfig> {
    let path = crate::config::config_file_path();
    if !path.exists() {
        return Ok(ProxyConfig::default());
    }

    let text = read_config_text(&path).with_context(|| format!("read {:?}", path))?;
    if path.extension().and_then(|ext| ext.to_str()) == Some("toml") {
        let version = config_toml_schema_version_or_shape(&text);
        if version.is_some_and(crate::config::is_supported_route_graph_config_version) {
            let cfg = toml::from_str::<ProxyConfigV4>(&text)
                .with_context(|| format!("parse {:?} as route graph config", path))?;
            return crate::config::compile_v4_to_runtime(&cfg);
        }
        if version == Some(3) {
            let cfg = toml::from_str::<crate::config::legacy::ProxyConfigV3Legacy>(&text)
                .with_context(|| format!("parse {:?} as legacy route config", path))?;
            let migrated = crate::config::legacy::migrate_v3_legacy_to_v4(&cfg)?;
            return crate::config::compile_v4_to_runtime(&migrated.config);
        }
        if version == Some(2) {
            let cfg = toml::from_str::<ProxyConfigV2>(&text)
                .with_context(|| format!("parse {:?} as v2 config", path))?;
            return crate::config::compile_v2_to_runtime(&cfg);
        }
        return toml::from_str::<ProxyConfig>(&text)
            .with_context(|| format!("parse {:?} as runtime config", path));
    }

    serde_json::from_str::<ProxyConfig>(&text).with_context(|| format!("parse {:?}", path))
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CodexBridgeRuntimeAuthSnapshot {
    pub routable_upstreams: usize,
    pub authed_upstreams: usize,
    pub missing_env: Vec<String>,
}

fn codex_bridge_runtime_auth_snapshot_from_config(
    cfg: &ProxyConfig,
) -> CodexBridgeRuntimeAuthSnapshot {
    let mut snapshot = CodexBridgeRuntimeAuthSnapshot::default();
    let mut missing_env = BTreeSet::new();
    for station in cfg
        .codex
        .stations()
        .values()
        .filter(|station| station.enabled)
    {
        for upstream in &station.upstreams {
            snapshot.routable_upstreams += 1;
            if upstream_has_resolved_auth(upstream) {
                snapshot.authed_upstreams += 1;
            } else {
                for env_name in upstream_auth_env_names(upstream) {
                    missing_env.insert(env_name.to_string());
                }
            }
        }
    }
    snapshot.missing_env = missing_env.into_iter().collect();
    snapshot
}

pub fn codex_bridge_runtime_auth_snapshot() -> Result<CodexBridgeRuntimeAuthSnapshot> {
    let cfg = load_runtime_config_for_bridge_check()
        .context("load codex-helper config for bridge diagnostics")?;
    Ok(codex_bridge_runtime_auth_snapshot_from_config(&cfg))
}

fn ensure_bridge_runtime_ready(mode: CodexPatchMode) -> Result<()> {
    let cfg = load_runtime_config_for_bridge_check().with_context(|| {
        format!(
            "load codex-helper config before enabling {}",
            mode.as_preset_str()
        )
    })?;
    let snapshot = codex_bridge_runtime_auth_snapshot_from_config(&cfg);

    if snapshot.routable_upstreams == 0 {
        anyhow::bail!(
            "{} requires at least one enabled Codex upstream in codex-helper config; run `codex-helper config init` or add a [codex.providers.*] entry first",
            mode.as_preset_str()
        );
    }
    if snapshot.authed_upstreams == 0 {
        if snapshot.missing_env.is_empty() {
            anyhow::bail!(
                "{} strips Codex client auth, but no enabled Codex upstream has auth_token/auth_token_env/api_key/api_key_env configured; configure an upstream credential before enabling it",
                mode.as_preset_str()
            );
        }
        anyhow::bail!(
            "{} strips Codex client auth, but no enabled Codex upstream credential is available in this process; set one of these env vars first: {}",
            mode.as_preset_str(),
            snapshot.missing_env.join(", ")
        );
    }

    Ok(())
}

#[cfg(test)]
fn ensure_imagegen_bridge_runtime_ready() -> Result<()> {
    ensure_bridge_runtime_ready(CodexPatchMode::ImagegenBridge)
}

pub fn patch_codex_auth_for_chatgpt_bridge() -> Result<()> {
    let auth_path = codex_auth_path();
    if !auth_path.exists() {
        return Err(anyhow!(
            "Codex auth.json not found at {:?}; run `codex login` first, then enable chatgpt-bridge preset.",
            auth_path
        ));
    }
    let text = read_config_text(&auth_path)?;
    let new_text = chatgpt_bridge_auth_json_text(&text)?;
    atomic_write(&auth_path, &new_text)?;
    Ok(())
}

#[derive(Debug, Clone)]
pub struct CodexSwitchStatus {
    /// Whether Codex currently appears to be configured to use the local codex-helper proxy.
    pub enabled: bool,
    /// Current `model_provider` value (if any).
    pub model_provider: Option<String>,
    /// Current `model_providers.codex_proxy.name` value (if any).
    pub provider_name: Option<String>,
    /// Current `model_providers.codex_proxy.base_url` (if any).
    pub base_url: Option<String>,
    /// Current codex-helper Codex preset inferred from `model_providers.codex_proxy`.
    pub patch_mode: Option<CodexPatchMode>,
    /// Current `model_providers.codex_proxy.requires_openai_auth` value (if any).
    pub requires_openai_auth: Option<bool>,
    /// Current `model_providers.codex_proxy.supports_websockets` value (if any).
    pub supports_websockets: Option<bool>,
    /// Whether `[features].remote_compaction_v2 = true` is present in Codex config.
    pub remote_compaction_v2_enabled: bool,
    /// Whether original switch metadata exists for disabling the local proxy patch.
    pub has_switch_state: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum CodexBridgeDiagnosticStatus {
    Ok,
    Info,
    Warn,
    Fail,
}

impl CodexBridgeDiagnosticStatus {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Ok => "ok",
            Self::Info => "info",
            Self::Warn => "warn",
            Self::Fail => "fail",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct CodexBridgeDiagnosticCheck {
    pub id: &'static str,
    pub status: CodexBridgeDiagnosticStatus,
    pub message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub action: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct CodexBridgeDiagnostics {
    pub patch_mode: Option<CodexPatchMode>,
    pub enabled: bool,
    pub remote_compaction_v1_ready: bool,
    pub imagegen_facade_ready: bool,
    pub upstream_auth_ready: bool,
    pub remote_compaction_v2_enabled: bool,
    pub checks: Vec<CodexBridgeDiagnosticCheck>,
}

impl CodexBridgeDiagnostics {
    pub fn worst_status(&self) -> CodexBridgeDiagnosticStatus {
        if self
            .checks
            .iter()
            .any(|check| check.status == CodexBridgeDiagnosticStatus::Fail)
        {
            return CodexBridgeDiagnosticStatus::Fail;
        }
        if self
            .checks
            .iter()
            .any(|check| check.status == CodexBridgeDiagnosticStatus::Warn)
        {
            return CodexBridgeDiagnosticStatus::Warn;
        }
        if self
            .checks
            .iter()
            .any(|check| check.status == CodexBridgeDiagnosticStatus::Info)
        {
            return CodexBridgeDiagnosticStatus::Info;
        }
        CodexBridgeDiagnosticStatus::Ok
    }
}

fn push_bridge_check(
    checks: &mut Vec<CodexBridgeDiagnosticCheck>,
    id: &'static str,
    status: CodexBridgeDiagnosticStatus,
    message: impl Into<String>,
    action: Option<String>,
) {
    checks.push(CodexBridgeDiagnosticCheck {
        id,
        status,
        message: message.into(),
        action,
    });
}

fn bridge_mode_expects_remote_compaction_v1(mode: Option<CodexPatchMode>) -> bool {
    mode.is_some_and(CodexPatchMode::enables_official_relay_features)
}

fn bridge_mode_expects_imagegen_facade(mode: Option<CodexPatchMode>) -> bool {
    mode.is_some_and(CodexPatchMode::enables_imagegen_facade)
}

pub fn codex_bridge_diagnostics() -> CodexBridgeDiagnostics {
    let status_result = codex_switch_status();
    let mut checks = Vec::new();
    let mut enabled = false;
    let mut patch_mode = None;
    let mut remote_compaction_v2_enabled = false;
    let mut remote_compaction_v1_ready = false;
    let mut imagegen_facade_ready = false;

    match status_result {
        Ok(status) => {
            enabled = status.enabled;
            patch_mode = status.patch_mode;
            remote_compaction_v2_enabled = status.remote_compaction_v2_enabled;

            if !status.enabled {
                push_bridge_check(
                    &mut checks,
                    "codex_bridge.switch",
                    CodexBridgeDiagnosticStatus::Info,
                    format!(
                        "Codex is not currently routed through codex-helper (model_provider={}).",
                        status.model_provider.as_deref().unwrap_or("<unset>")
                    ),
                    Some(
                        "Run `codex-helper switch on --preset official-imagegen` after starting helper if you want relay + remote compact + imagegen.".to_string(),
                    ),
                );
            } else {
                push_bridge_check(
                    &mut checks,
                    "codex_bridge.switch",
                    CodexBridgeDiagnosticStatus::Ok,
                    format!(
                        "Codex is routed through codex-helper on {} with preset={}.",
                        status.base_url.as_deref().unwrap_or("<missing base_url>"),
                        patch_mode
                            .map(|mode| mode.as_preset_str())
                            .unwrap_or("<unknown>")
                    ),
                    None,
                );
            }

            if bridge_mode_expects_remote_compaction_v1(patch_mode) {
                let provider_ok = status.provider_name.as_deref() == Some("OpenAI");
                remote_compaction_v1_ready = status.enabled && provider_ok;
                let status_label = if remote_compaction_v1_ready {
                    CodexBridgeDiagnosticStatus::Ok
                } else {
                    CodexBridgeDiagnosticStatus::Fail
                };
                push_bridge_check(
                    &mut checks,
                    "codex_bridge.remote_compaction_v1",
                    status_label,
                    format!(
                        "Remote compaction v1 requires provider name OpenAI; current name={}, supports_websockets={}.",
                        status.provider_name.as_deref().unwrap_or("<missing>"),
                        status
                            .supports_websockets
                            .map(|value| value.to_string())
                            .unwrap_or_else(|| "<missing>".to_string())
                    ),
                    (!remote_compaction_v1_ready).then(|| {
                        "Run `codex-helper switch on --preset official-imagegen` or `--preset official-relay`, then fully restart Codex clients.".to_string()
                    }),
                );
            } else {
                push_bridge_check(
                    &mut checks,
                    "codex_bridge.remote_compaction_v1",
                    CodexBridgeDiagnosticStatus::Info,
                    format!(
                        "Current preset {} does not advertise the local relay as the official OpenAI provider.",
                        patch_mode
                            .map(|mode| mode.as_preset_str())
                            .unwrap_or("<unknown>")
                    ),
                    Some(
                        "Use official-relay or official-imagegen preset when you need Codex remote compaction v1 through relay.".to_string(),
                    ),
                );
            }

            if status.supports_websockets == Some(true) {
                let provider_ok = status.provider_name.as_deref() == Some("OpenAI");
                let ws_ready = status.enabled && provider_ok;
                let status_label = if ws_ready {
                    CodexBridgeDiagnosticStatus::Ok
                } else {
                    CodexBridgeDiagnosticStatus::Fail
                };
                push_bridge_check(
                    &mut checks,
                    "codex_bridge.responses_websocket",
                    status_label,
                    format!(
                        "Responses WebSocket requires provider name OpenAI and supports_websockets=true; current name={}, supports_websockets={}.",
                        status.provider_name.as_deref().unwrap_or("<missing>"),
                        status
                            .supports_websockets
                            .map(|value| value.to_string())
                            .unwrap_or_else(|| "<missing>".to_string())
                    ),
                    (!ws_ready).then(|| {
                        "Run `codex-helper switch on --preset official-relay --responses-websocket` or `--preset official-imagegen --responses-websocket`, then fully restart Codex clients.".to_string()
                    }),
                );
            } else {
                let ws_status =
                    if patch_mode.is_some_and(CodexPatchMode::enables_official_relay_features) {
                        CodexBridgeDiagnosticStatus::Ok
                    } else {
                        CodexBridgeDiagnosticStatus::Info
                    };
                push_bridge_check(
                    &mut checks,
                    "codex_bridge.responses_websocket",
                    ws_status,
                    "Current preset does not advertise Responses WebSocket transport."
                        .to_string(),
                    Some(
                        "Use `--responses-websocket` only when helper and the selected relay both support Responses WebSocket v2.".to_string(),
                    ),
                );
            }

            if bridge_mode_expects_imagegen_facade(patch_mode) {
                match current_auth_json_facade_state() {
                    Ok(Some(true)) => {
                        imagegen_facade_ready = status.enabled;
                        push_bridge_check(
                            &mut checks,
                            "codex_bridge.imagegen_facade",
                            CodexBridgeDiagnosticStatus::Ok,
                            "Codex auth.json is the empty ChatGPT facade used to expose hosted image generation.".to_string(),
                            None,
                        );
                    }
                    Ok(Some(false)) => {
                        push_bridge_check(
                            &mut checks,
                            "codex_bridge.imagegen_facade",
                            CodexBridgeDiagnosticStatus::Fail,
                            "Codex auth.json is not the empty ChatGPT facade expected by imagegen bridge preset.".to_string(),
                            Some(
                                "Run `codex-helper switch on --preset official-imagegen`, then fully restart Codex clients.".to_string(),
                            ),
                        );
                    }
                    Ok(None) => {
                        push_bridge_check(
                            &mut checks,
                            "codex_bridge.imagegen_facade",
                            CodexBridgeDiagnosticStatus::Fail,
                            format!("Codex auth.json is missing at {:?}.", codex_auth_path()),
                            Some(
                                "Run `codex-helper switch on --preset official-imagegen` so helper can write the temporary facade.".to_string(),
                            ),
                        );
                    }
                    Err(err) => {
                        push_bridge_check(
                            &mut checks,
                            "codex_bridge.imagegen_facade",
                            CodexBridgeDiagnosticStatus::Warn,
                            format!("Could not inspect Codex auth.json facade state: {err}"),
                            Some("Inspect ~/.codex/auth.json and rerun `codex-helper switch status`.".to_string()),
                        );
                    }
                }
            } else {
                push_bridge_check(
                    &mut checks,
                    "codex_bridge.imagegen_facade",
                    CodexBridgeDiagnosticStatus::Info,
                    format!(
                        "Current preset {} does not install the imagegen auth facade.",
                        patch_mode
                            .map(|mode| mode.as_preset_str())
                            .unwrap_or("<unknown>")
                    ),
                    Some("Use official-imagegen preset when you need relay + remote compact + hosted image generation.".to_string()),
                );
            }

            if status.remote_compaction_v2_enabled {
                push_bridge_check(
                    &mut checks,
                    "codex_bridge.remote_compaction_v2",
                    CodexBridgeDiagnosticStatus::Warn,
                    "Codex remote_compaction_v2 is enabled; helper will detect compaction_trigger requests, but relay compatibility is still less stable than v1 /responses/compact.".to_string(),
                    Some(
                        "Only keep [features].remote_compaction_v2 = true when your relay explicitly supports compaction_trigger requests and compaction response items.".to_string(),
                    ),
                );
            } else {
                push_bridge_check(
                    &mut checks,
                    "codex_bridge.remote_compaction_v2",
                    CodexBridgeDiagnosticStatus::Ok,
                    "Codex remote_compaction_v2 is not enabled; remote compaction stays on the v1 /responses/compact path for official bridge presets.".to_string(),
                    None,
                );
            }
        }
        Err(err) => {
            push_bridge_check(
                &mut checks,
                "codex_bridge.switch",
                CodexBridgeDiagnosticStatus::Fail,
                format!("Could not inspect Codex switch status: {err}"),
                Some(
                    "Run `codex-helper switch status` and fix ~/.codex/config.toml parsing issues."
                        .to_string(),
                ),
            );
        }
    }

    let runtime_auth = match codex_bridge_runtime_auth_snapshot() {
        Ok(snapshot) => {
            let auth_ready = snapshot.authed_upstreams > 0;
            let status = if auth_ready {
                CodexBridgeDiagnosticStatus::Ok
            } else {
                CodexBridgeDiagnosticStatus::Fail
            };
            let action = if auth_ready {
                None
            } else if snapshot.missing_env.is_empty() {
                Some(
                    "Configure auth_token/auth_token_env/api_key/api_key_env for an enabled Codex upstream in codex-helper config.".to_string(),
                )
            } else {
                Some(format!(
                    "Set one of these env vars before starting codex-helper: {}.",
                    snapshot.missing_env.join(", ")
                ))
            };
            push_bridge_check(
                &mut checks,
                "codex_bridge.upstream_auth",
                status,
                format!(
                    "codex-helper has {} enabled Codex upstream(s), {} with usable credentials in this process.",
                    snapshot.routable_upstreams, snapshot.authed_upstreams
                ),
                action,
            );
            auth_ready
        }
        Err(err) => {
            push_bridge_check(
                &mut checks,
                "codex_bridge.upstream_auth",
                CodexBridgeDiagnosticStatus::Warn,
                format!("Could not inspect codex-helper upstream credentials: {err}"),
                Some("Check ~/.codex-helper/config.toml and rerun doctor.".to_string()),
            );
            false
        }
    };

    CodexBridgeDiagnostics {
        patch_mode,
        enabled,
        remote_compaction_v1_ready,
        imagegen_facade_ready,
        upstream_auth_ready: runtime_auth,
        remote_compaction_v2_enabled,
        checks,
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CodexStartupReadinessSeverity {
    Info,
    Warning,
}

impl CodexStartupReadinessSeverity {
    pub fn label(self) -> &'static str {
        match self {
            Self::Info => "info",
            Self::Warning => "warning",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CodexStartupReadinessIssueKind {
    ClientStateChanged,
    SwitchFailed,
    SwitchDisabled,
    SwitchPortMismatch,
    PatchModeMismatch,
    MissingSwitchState,
    RemoteControlRemovedKeyPresent,
    RemoteControlIncomplete,
    RemoteControlLogUnconfirmed,
    OfficialRelayAffinityPolicy,
    DiagnosticError,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CodexStartupReadinessIssue {
    pub kind: CodexStartupReadinessIssueKind,
    pub severity: CodexStartupReadinessSeverity,
    pub title: String,
    pub detail: String,
    pub action: String,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CodexStartupReadiness {
    pub issues: Vec<CodexStartupReadinessIssue>,
}

impl CodexStartupReadiness {
    pub fn has_issues(&self) -> bool {
        !self.issues.is_empty()
    }

    fn push(
        &mut self,
        kind: CodexStartupReadinessIssueKind,
        severity: CodexStartupReadinessSeverity,
        title: impl Into<String>,
        detail: impl Into<String>,
        action: impl Into<String>,
    ) {
        self.issues.push(CodexStartupReadinessIssue {
            kind,
            severity,
            title: title.into(),
            detail: detail.into(),
            action: action.into(),
        });
    }
}

#[derive(Debug, Clone)]
pub struct CodexStartupReadinessInput {
    pub expected_port: u16,
    pub expected_patch_mode: CodexPatchMode,
    pub expected_responses_websocket: bool,
    pub client_state_changed_this_startup: bool,
    pub switch_error: Option<String>,
}

pub fn codex_tui_startup_readiness(input: CodexStartupReadinessInput) -> CodexStartupReadiness {
    let mut report = CodexStartupReadiness::default();

    if input.client_state_changed_this_startup {
        report.push(
            CodexStartupReadinessIssueKind::ClientStateChanged,
            CodexStartupReadinessSeverity::Warning,
            "Codex client config changed on startup",
            "codex-helper updated ~/.codex/config.toml or ~/.codex/auth.json for the local bridge.",
            "Fully restart any already running Codex App, Codex TUI, or codex exec session so it rereads the client config.",
        );
    }

    if let Some(err) = input
        .switch_error
        .as_deref()
        .filter(|err| !err.trim().is_empty())
    {
        report.push(
            CodexStartupReadinessIssueKind::SwitchFailed,
            CodexStartupReadinessSeverity::Warning,
            "Codex local proxy patch failed",
            err,
            "Run `codex-helper switch status` and fix the reported Codex client config issue before relying on the bridge.",
        );
    }

    match codex_switch_status() {
        Ok(status) => collect_switch_startup_issues(&mut report, &input, &status),
        Err(err) => report.push(
            CodexStartupReadinessIssueKind::DiagnosticError,
            CodexStartupReadinessSeverity::Warning,
            "Could not inspect Codex switch status",
            err.to_string(),
            "Run `codex-helper switch status` from a normal shell to inspect the client config.",
        ),
    }

    match codex_remote_control_status() {
        Ok(status) => collect_remote_control_startup_issues(&mut report, &status),
        Err(err) => report.push(
            CodexStartupReadinessIssueKind::DiagnosticError,
            CodexStartupReadinessSeverity::Warning,
            "Could not inspect Codex remote-control status",
            err.to_string(),
            "Run `codex-helper switch remote-control status` from a normal shell to inspect the desktop state.",
        ),
    }

    report
}

fn collect_switch_startup_issues(
    report: &mut CodexStartupReadiness,
    input: &CodexStartupReadinessInput,
    status: &CodexSwitchStatus,
) {
    if !status.enabled {
        report.push(
            CodexStartupReadinessIssueKind::SwitchDisabled,
            CodexStartupReadinessSeverity::Warning,
            "Codex is not using the local helper",
            format!(
                "Current model_provider is {}.",
                status.model_provider.as_deref().unwrap_or("<unset>")
            ),
            format!(
                "Run `codex-helper switch on --port {}` or restart codex-helper so the client patch can be applied.",
                input.expected_port
            ),
        );
        return;
    }

    if !status.has_switch_state {
        report.push(
            CodexStartupReadinessIssueKind::MissingSwitchState,
            CodexStartupReadinessSeverity::Warning,
            "Codex local proxy patch has no switch state",
            "Codex points at the local helper, but codex-helper cannot find its restore metadata.",
            "Inspect ~/.codex/config.toml before running switch-off operations.",
        );
    }

    if !base_url_points_to_expected_local_port(status.base_url.as_deref(), input.expected_port) {
        report.push(
            CodexStartupReadinessIssueKind::SwitchPortMismatch,
            CodexStartupReadinessSeverity::Warning,
            "Codex local proxy port does not match this TUI",
            format!(
                "codex_proxy.base_url is {}; this TUI is serving port {}.",
                status.base_url.as_deref().unwrap_or("<missing>"),
                input.expected_port
            ),
            format!(
                "Run `codex-helper switch on --port {}` or restart this helper instance on the configured port.",
                input.expected_port
            ),
        );
    }

    if status.patch_mode != Some(input.expected_patch_mode) {
        let actual = status
            .patch_mode
            .map(|mode| mode.as_preset_str())
            .unwrap_or("<unknown>");
        report.push(
            CodexStartupReadinessIssueKind::PatchModeMismatch,
            CodexStartupReadinessSeverity::Warning,
            "Codex bridge preset does not match helper config",
            format!(
                "Expected preset {}, but Codex currently reports {}.",
                input.expected_patch_mode.as_preset_str(),
                actual
            ),
            "Run `codex-helper switch status`; if this changed recently, fully restart Codex clients after switching.",
        );
    }

    if status.supports_websockets.unwrap_or(false) != input.expected_responses_websocket {
        report.push(
            CodexStartupReadinessIssueKind::PatchModeMismatch,
            CodexStartupReadinessSeverity::Warning,
            "Codex WebSocket transport flag does not match helper config",
            format!(
                "Expected supports_websockets={}, but Codex currently reports {}.",
                input.expected_responses_websocket,
                status
                    .supports_websockets
                    .map(|value| value.to_string())
                    .unwrap_or_else(|| "<missing>".to_string())
            ),
            "Run `codex-helper switch status`; if this changed recently, fully restart Codex clients after switching.",
        );
    }

    if status
        .patch_mode
        .is_some_and(CodexPatchMode::enables_official_relay_features)
    {
        match official_relay_affinity_policy_warning() {
            Ok(Some(detail)) => report.push(
                CodexStartupReadinessIssueKind::OfficialRelayAffinityPolicy,
                CodexStartupReadinessSeverity::Warning,
                "Official relay preset can route a session across providers",
                detail,
                "For the most official-like remote compaction behavior, set [codex.routing].affinity_policy = \"fallback-sticky\" or \"hard\" when using multiple authenticated upstreams.",
            ),
            Ok(None) => {}
            Err(err) => report.push(
                CodexStartupReadinessIssueKind::DiagnosticError,
                CodexStartupReadinessSeverity::Warning,
                "Could not inspect codex-helper routing affinity",
                err.to_string(),
                "Inspect ~/.codex-helper/config.toml and choose an affinity policy appropriate for official relay features.",
            ),
        }
    }
}

fn base_url_points_to_expected_local_port(base_url: Option<&str>, port: u16) -> bool {
    let Some(base_url) = base_url else {
        return false;
    };
    let port_marker = format!(":{port}");
    (base_url.contains("127.0.0.1") || base_url.contains("localhost") || base_url.contains("[::1]"))
        && base_url.contains(&port_marker)
}

fn official_relay_affinity_policy_warning() -> Result<Option<String>> {
    let path = crate::config::config_file_path();
    if !path.exists() {
        return Ok(None);
    }
    let text = read_config_text(&path).with_context(|| format!("read {:?}", path))?;
    if text.trim().is_empty() {
        return Ok(None);
    }
    if path.extension().and_then(|ext| ext.to_str()) != Some("toml") {
        return Ok(None);
    }

    let version = config_toml_schema_version_or_shape(&text);
    if !version.is_some_and(crate::config::is_supported_route_graph_config_version) {
        return Ok(None);
    }

    let cfg = toml::from_str::<ProxyConfigV4>(&text)
        .with_context(|| format!("parse {:?} as route graph config", path))?;
    let Some(routing) = cfg.codex.routing.as_ref() else {
        return Ok(None);
    };
    if routing.affinity_policy != RoutingAffinityPolicyV5::PreferredGroup {
        return Ok(None);
    }

    let authed_provider_count = cfg
        .codex
        .providers
        .values()
        .filter(|provider| provider.enabled && provider_v4_has_resolved_auth(provider))
        .count();
    if authed_provider_count <= 1 {
        return Ok(None);
    }

    Ok(Some(format!(
        "codex-helper has {authed_provider_count} authenticated Codex providers and [codex.routing].affinity_policy is \"preferred-group\". Remote compaction v1 may include encrypted conversation state, so /responses and /responses/compact should stay on the same upstream account when a session has failed over."
    )))
}

fn provider_v4_has_resolved_auth(provider: &crate::config::ProviderConfigV4) -> bool {
    upstream_auth_has_resolved_credential(&provider.auth)
        || upstream_auth_has_resolved_credential(&provider.inline_auth)
}

fn collect_remote_control_startup_issues(
    report: &mut CodexStartupReadiness,
    status: &CodexRemoteControlStatus,
) {
    if status.remote_control_config_present {
        report.push(
            CodexStartupReadinessIssueKind::RemoteControlRemovedKeyPresent,
            CodexStartupReadinessSeverity::Warning,
            "Removed remote_control config key is present",
            format!(
                "{:?} contains [features].remote_control, which current Codex builds do not use for this enablement path.",
                status.config_path
            ),
            "Remove remote_control and keep [features].remote_connections = true instead.",
        );
    }

    let remote_requested = status.remote_connections_enabled
        || status.remote_control_config_present
        || status.db_enabled == Some(true);
    if !remote_requested {
        return;
    }

    if !remote_control_status_is_fully_enabled(status) {
        report.push(
            CodexStartupReadinessIssueKind::RemoteControlIncomplete,
            CodexStartupReadinessSeverity::Warning,
            "Codex App remote-control state is incomplete",
            format!(
                "remote_connections={}, db_exists={}, table_exists={}, db_enabled={}.",
                status.remote_connections_enabled,
                status.db_exists,
                status.db_table_exists,
                status
                    .db_enabled
                    .map(|value| value.to_string())
                    .unwrap_or_else(|| "<missing>".to_string())
            ),
            "Run `codex-helper switch remote-control enable`, then fully restart Codex App.",
        );
        return;
    }

    match codex_remote_control_successful_enablement_log_seen() {
        Ok(true) => {}
        Ok(false) => report.push(
            CodexStartupReadinessIssueKind::RemoteControlLogUnconfirmed,
            CodexStartupReadinessSeverity::Warning,
            "Remote-control enablement is not confirmed in Codex logs",
            "The config and SQLite state look enabled, but no experimentalFeature/enablement/set success log was found.",
            "Fully restart Codex App, then run `codex-helper switch remote-control check-logs`.",
        ),
        Err(err) => report.push(
            CodexStartupReadinessIssueKind::DiagnosticError,
            CodexStartupReadinessSeverity::Warning,
            "Could not inspect Codex remote-control logs",
            err.to_string(),
            "Run `codex-helper switch remote-control check-logs` from a normal shell after restarting Codex App.",
        ),
    }
}

fn remote_control_status_is_fully_enabled(status: &CodexRemoteControlStatus) -> bool {
    status.remote_connections_enabled
        && !status.remote_control_config_present
        && status.db_exists
        && status.db_table_exists
        && status.db_enabled == Some(true)
}

pub fn codex_switch_status() -> Result<CodexSwitchStatus> {
    let cfg_path = codex_config_path();
    let state_path = codex_switch_state_path();

    if !cfg_path.exists() {
        return Ok(CodexSwitchStatus {
            enabled: false,
            model_provider: None,
            provider_name: None,
            base_url: None,
            patch_mode: None,
            requires_openai_auth: None,
            supports_websockets: None,
            remote_compaction_v2_enabled: false,
            has_switch_state: state_path.exists(),
        });
    }

    let text = read_config_text(&cfg_path)?;
    let remote_compaction_v2_enabled =
        codex_remote_compaction_v2_feature_enabled_from_toml(&text).unwrap_or(false);
    if text.trim().is_empty() {
        return Ok(CodexSwitchStatus {
            enabled: false,
            model_provider: None,
            provider_name: None,
            base_url: None,
            patch_mode: None,
            requires_openai_auth: None,
            supports_websockets: None,
            remote_compaction_v2_enabled,
            has_switch_state: state_path.exists(),
        });
    }

    let value: Value = match text.parse() {
        Ok(v) => v,
        Err(_) => {
            return Ok(CodexSwitchStatus {
                enabled: false,
                model_provider: None,
                provider_name: None,
                base_url: None,
                patch_mode: None,
                requires_openai_auth: None,
                supports_websockets: None,
                remote_compaction_v2_enabled,
                has_switch_state: state_path.exists(),
            });
        }
    };
    let table = match value.as_table() {
        Some(t) => t,
        None => {
            return Ok(CodexSwitchStatus {
                enabled: false,
                model_provider: None,
                provider_name: None,
                base_url: None,
                patch_mode: None,
                requires_openai_auth: None,
                supports_websockets: None,
                remote_compaction_v2_enabled,
                has_switch_state: state_path.exists(),
            });
        }
    };

    let model_provider = table
        .get("model_provider")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());

    if model_provider.as_deref() != Some("codex_proxy") {
        return Ok(CodexSwitchStatus {
            enabled: false,
            model_provider,
            provider_name: None,
            base_url: None,
            patch_mode: None,
            requires_openai_auth: None,
            supports_websockets: None,
            remote_compaction_v2_enabled,
            has_switch_state: state_path.exists(),
        });
    }

    let empty_map = toml::map::Map::new();
    let providers_table = table
        .get("model_providers")
        .and_then(|v| v.as_table())
        .unwrap_or(&empty_map);
    let empty_provider = toml::map::Map::new();
    let proxy_table = providers_table
        .get("codex_proxy")
        .and_then(|v| v.as_table())
        .unwrap_or(&empty_provider);

    let base_url = proxy_table
        .get("base_url")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());
    let name = proxy_table
        .get("name")
        .and_then(|v| v.as_str())
        .unwrap_or_default();
    let provider_name = (!name.is_empty()).then(|| name.to_string());
    let requires_openai_auth = proxy_table
        .get("requires_openai_auth")
        .and_then(|v| v.as_bool());
    let supports_websockets = proxy_table
        .get("supports_websockets")
        .and_then(|v| v.as_bool());

    let is_local = base_url
        .as_deref()
        .is_some_and(|u| u.contains("127.0.0.1") || u.contains("localhost"));
    let is_helper_name = name == "codex-helper";
    let enabled = is_local || is_helper_name;

    let stored_patch_mode = read_codex_switch_state()?.and_then(|state| state.patch_mode);
    let inferred_patch_mode = if requires_openai_auth == Some(true) {
        CodexPatchMode::ChatGptBridge
    } else if name == "OpenAI" {
        if current_auth_json_is_empty_chatgpt_facade() {
            CodexPatchMode::OfficialImagegenBridge
        } else {
            CodexPatchMode::OfficialRelayBridge
        }
    } else {
        CodexPatchMode::Default
    };

    Ok(CodexSwitchStatus {
        enabled,
        model_provider,
        provider_name,
        base_url,
        patch_mode: enabled.then_some(stored_patch_mode.unwrap_or(inferred_patch_mode)),
        requires_openai_auth,
        supports_websockets,
        remote_compaction_v2_enabled,
        has_switch_state: state_path.exists(),
    })
}

/// Switch Codex to use the local codex-helper model provider.
pub fn switch_on(port: u16) -> Result<()> {
    switch_on_with_mode(port, CodexPatchMode::Default)
}

/// Switch Codex to use the local codex-helper model provider using the preset configured in
/// `~/.codex-helper/config.toml`.
pub fn switch_on_with_configured_preset(port: u16) -> Result<()> {
    let client_patch = crate::config::codex_client_patch_config_from_config_file()
        .context("read codex.client_patch from codex-helper config before switch on")?;
    switch_on_with_options(port, client_patch.preset, client_patch.options)
}

/// Switch Codex to use the local codex-helper model provider with an explicit client preset.
pub fn switch_on_with_mode(port: u16, mode: CodexPatchMode) -> Result<()> {
    switch_on_with_options(port, mode, CodexSwitchOptions::default())
}

/// Switch Codex to use the local codex-helper model provider with an explicit client preset and
/// transport options.
pub fn switch_on_with_options(
    port: u16,
    mode: CodexPatchMode,
    options: CodexSwitchOptions,
) -> Result<()> {
    let plan = CodexPatchPlan::for_switch_on(mode, options)?;
    if plan.requires_bridge_runtime_ready() {
        ensure_bridge_runtime_ready(plan.mode())?;
    }

    let cfg_path = codex_config_path();
    let state_path = codex_switch_state_path();
    let text = read_config_text(&cfg_path)?;
    if !state_path.exists() && codex_text_points_to_local_helper(&text)? {
        return Err(anyhow!(
            "Codex already points to the local codex-helper proxy, but no switch state was found at {:?}; refusing to treat the local proxy as the original provider. Please inspect ~/.codex/config.toml manually or run `codex-helper switch off` only if a switch state exists.",
            state_path
        ));
    }
    let mut state = if state_path.exists() {
        read_codex_switch_state()?.ok_or_else(|| {
            anyhow!(
                "missing Codex switch state at {:?}",
                codex_switch_state_path()
            )
        })?
    } else {
        CodexSwitchState::from_codex_config_text(&text, !cfg_path.exists())?
    };
    state.patch_mode = Some(plan.mode());
    state.responses_websocket = plan.options().responses_websocket;

    let auth_edit = auth_edit_for_switch_on_plan(plan, &mut state)?;
    let new_text = switch_on_codex_toml_with_plan(&text, port, plan)?;
    apply_switch_on_effects(plan, &cfg_path, &new_text, &state, auth_edit)?;
    Ok(())
}

/// Undo the local Codex proxy patch while preserving config edits made during the run.
pub fn switch_off() -> Result<()> {
    let cfg_path = codex_config_path();
    let state_path = codex_switch_state_path();
    if state_path.exists() {
        let mut state = read_codex_switch_state()?.ok_or_else(|| {
            anyhow!(
                "missing Codex switch state at {:?}",
                codex_switch_state_path()
            )
        })?;
        let auth_edit = auth_restore_edit_from_state(&mut state)?;
        if !cfg_path.exists() {
            apply_codex_auth_edit(auth_edit)?;
            fs::remove_file(&state_path)
                .with_context(|| format!("remove stale switch state {:?}", state_path))?;
            return Ok(());
        }
        let current_text = read_config_text(&cfg_path)?;
        match switch_off_codex_toml(&current_text, &state)? {
            CodexSwitchOffEdit::RemoveFile => {
                if cfg_path.exists() {
                    fs::remove_file(&cfg_path)
                        .with_context(|| format!("remove {:?} (restore absent)", cfg_path))?;
                }
            }
            CodexSwitchOffEdit::Write(text) => {
                atomic_write(&cfg_path, &text)
                    .with_context(|| format!("patch {:?} to disable local proxy", cfg_path))?;
            }
        }
        apply_codex_auth_edit(auth_edit)?;
        fs::remove_file(&state_path)
            .with_context(|| format!("remove stale switch state {:?}", state_path))?;
    }
    Ok(())
}

#[derive(Debug, Clone)]
pub struct CodexRemoteControlStatus {
    pub config_path: PathBuf,
    pub remote_connections_enabled: bool,
    pub remote_control_config_present: bool,
    pub db_path: PathBuf,
    pub db_exists: bool,
    pub db_table_exists: bool,
    pub db_enabled: Option<bool>,
    pub db_updated_at: Option<i64>,
}

#[derive(Debug, Clone)]
pub struct CodexRemoteControlEnablement {
    pub status: CodexRemoteControlStatus,
    pub backup_path: PathBuf,
}

pub fn codex_remote_control_enable() -> Result<CodexRemoteControlEnablement> {
    let cfg_path = codex_config_path();
    let config_text = read_config_text(&cfg_path)?;
    let updated_config = ensure_codex_remote_connections_feature_in_toml(&config_text)?;
    let db_path = codex_app_db_path();

    validate_codex_remote_control_feature_enablement_schema(&db_path)?;
    let backup_path = backup_codex_app_db(&db_path)?;

    if updated_config != config_text {
        atomic_write(&cfg_path, &updated_config)
            .with_context(|| format!("patch {:?} for Codex remote connections", cfg_path))?;
    }

    upsert_codex_remote_control_feature_enablement(&db_path)?;
    let status = codex_remote_control_status()?;

    Ok(CodexRemoteControlEnablement {
        status,
        backup_path,
    })
}

pub fn codex_remote_control_status() -> Result<CodexRemoteControlStatus> {
    let config_path = codex_config_path();
    let config_text = read_config_text(&config_path)?;
    let remote_connections_enabled =
        codex_remote_connections_feature_enabled_from_toml(&config_text)?;
    let remote_control_config_present = codex_remote_control_feature_present_in_toml(&config_text)?;

    let db_path = codex_app_db_path();
    let db_exists = db_path.exists();
    let db_status = if db_exists {
        read_codex_remote_control_db_status(&db_path)?
    } else {
        CodexRemoteControlDbStatus {
            table_exists: false,
            enabled: None,
            updated_at: None,
        }
    };

    Ok(CodexRemoteControlStatus {
        config_path,
        remote_connections_enabled,
        remote_control_config_present,
        db_path,
        db_exists,
        db_table_exists: db_status.table_exists,
        db_enabled: db_status.enabled,
        db_updated_at: db_status.updated_at,
    })
}

fn backup_codex_app_db(db_path: &Path) -> Result<PathBuf> {
    if !db_path.exists() {
        return Err(anyhow!(
            "Codex App SQLite database not found at {:?}; open Codex App once so it creates the local database, then retry",
            db_path
        ));
    }

    let timestamp = timestamp_for_backup_filename();
    let file_name = db_path
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or("codex-dev.db");
    let backup_path = db_path.with_file_name(format!("{file_name}.{timestamp}.bak"));
    fs::copy(db_path, &backup_path)
        .with_context(|| format!("backup {:?} -> {:?}", db_path, backup_path))?;
    Ok(backup_path)
}

fn validate_codex_remote_control_feature_enablement_schema(db_path: &Path) -> Result<()> {
    if !db_path.exists() {
        return Err(anyhow!(
            "Codex App SQLite database not found at {:?}; open Codex App once so it creates the local database, then retry",
            db_path
        ));
    }

    let conn = rusqlite::Connection::open(db_path)
        .with_context(|| format!("open Codex App SQLite database {:?}", db_path))?;
    let columns = local_app_server_feature_enablement_columns(&conn)?;
    if columns.is_empty() {
        return Err(anyhow!(
            "SQLite table local_app_server_feature_enablement not found in {:?}; this Codex App build may use a different desktop state schema",
            db_path
        ));
    }
    ensure_required_enablement_columns(&columns)
}

fn timestamp_for_backup_filename() -> String {
    use std::time::{SystemTime, UNIX_EPOCH};

    let millis = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|duration| duration.as_millis())
        .unwrap_or(0);
    millis.to_string()
}

fn current_unix_millis_i64() -> i64 {
    use std::time::{SystemTime, UNIX_EPOCH};

    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|duration| duration.as_millis().min(i64::MAX as u128) as i64)
        .unwrap_or(0)
}

fn upsert_codex_remote_control_feature_enablement(db_path: &Path) -> Result<()> {
    let conn = rusqlite::Connection::open(db_path)
        .with_context(|| format!("open Codex App SQLite database {:?}", db_path))?;
    let columns = local_app_server_feature_enablement_columns(&conn)?;
    if columns.is_empty() {
        return Err(anyhow!(
            "SQLite table local_app_server_feature_enablement not found in {:?}; this Codex App build may use a different desktop state schema",
            db_path
        ));
    }
    ensure_required_enablement_columns(&columns)?;

    let updated_at = current_unix_millis_i64();
    let column_names = columns
        .iter()
        .map(|column| column.name.as_str())
        .collect::<Vec<_>>();
    let has_created_at = column_names.contains(&"created_at");

    let updated_rows = conn
        .execute(
            "UPDATE local_app_server_feature_enablement \
             SET enabled = ?1, updated_at = ?2 \
             WHERE feature_name = ?3",
            rusqlite::params![1_i64, updated_at, "remote_control"],
        )
        .with_context(|| {
            format!(
                "update remote_control in local_app_server_feature_enablement in {:?}",
                db_path
            )
        })?;
    if updated_rows > 0 {
        return Ok(());
    }

    let mut insert_columns = vec!["feature_name", "enabled", "updated_at"];
    let mut insert_values = vec!["?1", "?2", "?3"];
    if has_created_at {
        insert_columns.push("created_at");
        insert_values.push("?3");
    }

    let sql = format!(
        "INSERT INTO local_app_server_feature_enablement ({}) VALUES ({})",
        insert_columns.join(", "),
        insert_values.join(", ")
    );
    conn.execute(
        sql.as_str(),
        rusqlite::params!["remote_control", 1_i64, updated_at],
    )
    .with_context(|| {
        format!(
            "upsert remote_control into local_app_server_feature_enablement in {:?}",
            db_path
        )
    })?;

    Ok(())
}

#[derive(Debug)]
struct SqliteColumnInfo {
    name: String,
    not_null: bool,
    pk: i32,
}

fn local_app_server_feature_enablement_columns(
    conn: &rusqlite::Connection,
) -> Result<Vec<SqliteColumnInfo>> {
    let mut stmt = conn
        .prepare("PRAGMA table_info(local_app_server_feature_enablement)")
        .context("prepare table_info(local_app_server_feature_enablement)")?;
    let rows = stmt
        .query_map([], |row| {
            Ok(SqliteColumnInfo {
                name: row.get(1)?,
                not_null: row.get::<_, i64>(3)? != 0,
                pk: row.get(5)?,
            })
        })
        .context("query table_info(local_app_server_feature_enablement)")?;

    let mut columns = Vec::new();
    for row in rows {
        columns.push(row?);
    }
    Ok(columns)
}

fn ensure_required_enablement_columns(columns: &[SqliteColumnInfo]) -> Result<()> {
    for required in ["feature_name", "enabled", "updated_at"] {
        if !columns.iter().any(|column| column.name == required) {
            return Err(anyhow!(
                "SQLite table local_app_server_feature_enablement is missing required column `{required}`"
            ));
        }
    }

    let optional_supported = ["id", "created_at", "feature_name", "enabled", "updated_at"];
    let unsupported_required = columns
        .iter()
        .filter(|column| column.not_null && column.pk == 0)
        .filter(|column| {
            !optional_supported
                .iter()
                .any(|supported| *supported == column.name)
        })
        .map(|column| column.name.as_str())
        .collect::<Vec<_>>();
    if !unsupported_required.is_empty() {
        return Err(anyhow!(
            "SQLite table local_app_server_feature_enablement has unsupported NOT NULL columns without known values: {}",
            unsupported_required.join(", ")
        ));
    }

    Ok(())
}

#[derive(Debug)]
struct CodexRemoteControlDbStatus {
    table_exists: bool,
    enabled: Option<bool>,
    updated_at: Option<i64>,
}

fn read_codex_remote_control_db_status(db_path: &Path) -> Result<CodexRemoteControlDbStatus> {
    let conn = rusqlite::Connection::open(db_path)
        .with_context(|| format!("open Codex App SQLite database {:?}", db_path))?;
    let columns = local_app_server_feature_enablement_columns(&conn)?;
    if columns.is_empty() {
        return Ok(CodexRemoteControlDbStatus {
            table_exists: false,
            enabled: None,
            updated_at: None,
        });
    }

    ensure_required_enablement_columns(&columns)?;
    let mut stmt = conn
        .prepare(
            "SELECT enabled, updated_at \
             FROM local_app_server_feature_enablement \
             WHERE feature_name = ?1 \
             ORDER BY updated_at DESC \
             LIMIT 1",
        )
        .context("prepare local_app_server_feature_enablement status query")?;
    let mut rows = stmt
        .query(rusqlite::params!["remote_control"])
        .context("query local_app_server_feature_enablement status")?;

    if let Some(row) = rows.next()? {
        Ok(CodexRemoteControlDbStatus {
            table_exists: true,
            enabled: Some(row.get::<_, i64>(0)? != 0),
            updated_at: row.get(1)?,
        })
    } else {
        Ok(CodexRemoteControlDbStatus {
            table_exists: true,
            enabled: None,
            updated_at: None,
        })
    }
}

pub fn codex_remote_control_successful_enablement_log_seen() -> Result<bool> {
    let base_dir = codex_config_path()
        .parent()
        .map(Path::to_path_buf)
        .unwrap_or_else(|| PathBuf::from("."));
    for candidate in [base_dir.join("log"), base_dir.join("logs")] {
        if codex_remote_control_successful_enablement_log_seen_in_dir(candidate.as_path())? {
            return Ok(true);
        }
    }
    Ok(false)
}

fn codex_remote_control_successful_enablement_log_seen_in_dir(log_dir: &Path) -> Result<bool> {
    if !log_dir.exists() {
        return Ok(false);
    }

    let mut files = Vec::new();
    collect_regular_files(log_dir, &mut files)?;
    files.sort_by_key(|path| {
        fs::metadata(path)
            .and_then(|metadata| metadata.modified())
            .ok()
    });

    for path in files.into_iter().rev().take(20) {
        if file_contains_remote_control_success(path.as_path())? {
            return Ok(true);
        }
    }
    Ok(false)
}

fn collect_regular_files(dir: &Path, out: &mut Vec<PathBuf>) -> Result<()> {
    for entry in fs::read_dir(dir).with_context(|| format!("read_dir {:?}", dir))? {
        let entry = entry.with_context(|| format!("read entry in {:?}", dir))?;
        let path = entry.path();
        let file_type = entry
            .file_type()
            .with_context(|| format!("read file type for {:?}", path))?;
        if file_type.is_dir() {
            collect_regular_files(&path, out)?;
        } else if file_type.is_file() {
            out.push(path);
        }
    }
    Ok(())
}

fn file_contains_remote_control_success(path: &Path) -> Result<bool> {
    const MAX_BYTES: u64 = 2 * 1024 * 1024;
    let mut file = fs::File::open(path).with_context(|| format!("open log {:?}", path))?;
    let len = file.metadata()?.len();
    if len > MAX_BYTES {
        file.seek(SeekFrom::End(-(MAX_BYTES as i64)))
            .with_context(|| format!("seek log {:?}", path))?;
    }
    let mut bytes = Vec::new();
    file.read_to_end(&mut bytes)
        .with_context(|| format!("read log {:?}", path))?;
    let text = String::from_utf8_lossy(&bytes);
    Ok(text.contains("experimentalFeature/enablement/set")
        && (text.contains("errorCode=null")
            || text.contains("\"errorCode\":null")
            || text.contains("'errorCode':null")))
}

#[derive(Debug, Clone)]
pub struct ClaudeSwitchStatus {
    /// Whether Claude Code currently appears to be configured to use the local codex-helper proxy.
    pub enabled: bool,
    /// Current `env.ANTHROPIC_BASE_URL` value (if any).
    pub base_url: Option<String>,
    /// Whether a backup file exists for safe restore.
    pub has_backup: bool,
    /// The resolved settings file path (settings.json or legacy claude.json).
    pub settings_path: PathBuf,
}

pub fn claude_switch_status() -> Result<ClaudeSwitchStatus> {
    let settings_path = claude_settings_path();
    let backup_path = claude_settings_backup_path(&settings_path);

    if !settings_path.exists() {
        return Ok(ClaudeSwitchStatus {
            enabled: false,
            base_url: None,
            has_backup: backup_path.exists(),
            settings_path,
        });
    }

    let text = read_settings_text(&settings_path)?;
    if text.trim().is_empty() {
        return Ok(ClaudeSwitchStatus {
            enabled: false,
            base_url: None,
            has_backup: backup_path.exists(),
            settings_path,
        });
    }

    let value: serde_json::Value = match serde_json::from_str(&text) {
        Ok(v) => v,
        Err(_) => {
            return Ok(ClaudeSwitchStatus {
                enabled: false,
                base_url: None,
                has_backup: backup_path.exists(),
                settings_path,
            });
        }
    };

    let env_obj = value
        .as_object()
        .and_then(|o| o.get("env"))
        .and_then(|v| v.as_object());

    let base_url = env_obj
        .and_then(|e| e.get("ANTHROPIC_BASE_URL"))
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());

    let enabled = base_url
        .as_deref()
        .is_some_and(|u| u.contains("127.0.0.1") || u.contains("localhost"));

    Ok(ClaudeSwitchStatus {
        enabled,
        base_url,
        has_backup: backup_path.exists(),
        settings_path,
    })
}

/// Warn before replacing an existing local Codex proxy patch.
pub fn guard_codex_config_before_switch_on_interactive() -> Result<()> {
    use std::io::{self, Write};

    let cfg_path = codex_config_path();
    let state_path = codex_switch_state_path();

    if !cfg_path.exists() {
        return Ok(());
    }

    let text = read_config_text(&cfg_path)?;
    if text.trim().is_empty() {
        return Ok(());
    }

    let value: Value = match text.parse() {
        Ok(value) => value,
        Err(_) => return Ok(()),
    };
    let table = match value.as_table() {
        Some(table) => table,
        None => return Ok(()),
    };

    let current_provider = table
        .get("model_provider")
        .and_then(|value| value.as_str())
        .unwrap_or_default();
    if current_provider != "codex_proxy" {
        return Ok(());
    }

    let empty_map = toml::map::Map::new();
    let providers_table = table
        .get("model_providers")
        .and_then(|value| value.as_table())
        .unwrap_or(&empty_map);
    let empty_provider = toml::map::Map::new();
    let proxy_table = providers_table
        .get("codex_proxy")
        .and_then(|value| value.as_table())
        .unwrap_or(&empty_provider);

    let base_url = proxy_table
        .get("base_url")
        .and_then(|value| value.as_str())
        .unwrap_or_default();
    let name = proxy_table
        .get("name")
        .and_then(|value| value.as_str())
        .unwrap_or_default();

    let is_local = base_url.contains("127.0.0.1") || base_url.contains("localhost");
    let is_helper_name = name == "codex-helper";
    if !is_local && !is_helper_name {
        return Ok(());
    }

    if !state_path.exists() {
        eprintln!(
            "Warning: Codex currently points to the local proxy ({base_url}), but no codex-helper switch state {:?} was found; please inspect ~/.codex/config.toml manually if this is unexpected.",
            state_path
        );
        return Ok(());
    }

    let is_tty = atty::is(atty::Stream::Stdin) && atty::is(atty::Stream::Stdout);
    if !is_tty {
        eprintln!(
            "Notice: Codex currently points to local codex-helper ({base_url}) and switch state {:?} exists; run `codex-helper switch off` to disable the local proxy patch while preserving other config edits.",
            state_path
        );
        return Ok(());
    }

    eprintln!(
        "Codex currently points to local codex-helper ({base_url}), and switch state {:?} exists.\nThis usually means the previous run did not switch off cleanly.\nDisable the local proxy patch now while preserving other config edits? [Y/n] ",
        state_path
    );
    eprint!("> ");
    io::stdout().flush().ok();

    let mut input = String::new();
    if let Err(err) = io::stdin().read_line(&mut input) {
        eprintln!("Failed to read input: {err}");
        return Ok(());
    }
    let answer = input.trim();
    let yes =
        answer.is_empty() || answer.eq_ignore_ascii_case("y") || answer.eq_ignore_ascii_case("yes");

    if yes {
        if let Err(err) = switch_off() {
            eprintln!("Failed to disable local Codex proxy patch: {err}");
        } else {
            eprintln!("Disabled local Codex proxy patch.");
        }
    } else {
        eprintln!("Keeping current Codex config unchanged.");
    }

    Ok(())
}

fn read_settings_text(path: &Path) -> Result<String> {
    if !path.exists() {
        return Ok(String::new());
    }
    let mut file = fs::File::open(path).with_context(|| format!("open {:?}", path))?;
    let mut buf = String::new();
    file.read_to_string(&mut buf)
        .with_context(|| format!("read {:?}", path))?;
    Ok(buf)
}

pub fn claude_switch_on(port: u16) -> Result<()> {
    let settings_path = claude_settings_path();
    let backup_path = claude_settings_backup_path(&settings_path);

    if settings_path.exists() && !backup_path.exists() {
        fs::copy(&settings_path, &backup_path).with_context(|| {
            format!(
                "backup Claude settings {:?} -> {:?}",
                settings_path, backup_path
            )
        })?;
    } else if !settings_path.exists() && !backup_path.exists() {
        // If Claude Code has no settings yet, create a sentinel backup so we can restore
        // to the "absent" state on claude_switch_off.
        if let Some(parent) = backup_path.parent() {
            fs::create_dir_all(parent).with_context(|| format!("create_dir_all {:?}", parent))?;
        }
        fs::write(&backup_path, CLAUDE_ABSENT_BACKUP_SENTINEL)
            .with_context(|| format!("write {:?}", backup_path))?;
    }

    let text = read_settings_text(&settings_path)?;
    let mut value: serde_json::Value = if text.trim().is_empty() {
        serde_json::json!({})
    } else {
        serde_json::from_str(&text).with_context(|| format!("parse {:?} as JSON", settings_path))?
    };

    let obj = value
        .as_object_mut()
        .ok_or_else(|| anyhow!("Claude settings root must be an object"))?;

    let env_val = obj
        .entry("env".to_string())
        .or_insert_with(|| serde_json::json!({}));
    let env_obj = env_val
        .as_object_mut()
        .ok_or_else(|| anyhow!("Claude settings env must be an object"))?;

    let base_url = format!("http://127.0.0.1:{}", port);
    env_obj.insert(
        "ANTHROPIC_BASE_URL".to_string(),
        serde_json::Value::String(base_url),
    );

    let new_text = serde_json::to_string_pretty(&value)?;
    write_text_file(&settings_path, &new_text)
        .with_context(|| format!("write {:?}", settings_path))?;

    eprintln!(
        "[EXPERIMENTAL] Updated {:?} to use local Claude proxy via codex-helper",
        settings_path
    );
    Ok(())
}

pub fn claude_switch_off() -> Result<()> {
    let settings_path = claude_settings_path();
    let backup_path = claude_settings_backup_path(&settings_path);
    if backup_path.exists() {
        let text = read_settings_text(&backup_path)?;
        if text.trim() == CLAUDE_ABSENT_BACKUP_SENTINEL {
            if settings_path.exists() {
                fs::remove_file(&settings_path)
                    .with_context(|| format!("remove {:?} (restore absent)", settings_path))?;
            }
        } else {
            atomic_write(&settings_path, &text)
                .with_context(|| format!("restore {:?} -> {:?}", backup_path, settings_path))?;
            eprintln!(
                "[EXPERIMENTAL] Restored Claude settings from backup {:?}",
                backup_path
            );
        }
        fs::remove_file(&backup_path)
            .with_context(|| format!("remove stale backup {:?}", backup_path))?;
    }
    Ok(())
}

#[cfg(test)]
#[allow(clippy::items_after_test_module)]
mod tests {
    use super::*;
    use base64::Engine as _;
    use serde_json::json;
    use std::path::Path;
    use std::sync::{Mutex, OnceLock};

    struct ScopedEnv {
        saved: Vec<(String, Option<String>)>,
    }

    impl ScopedEnv {
        fn new() -> Self {
            Self { saved: Vec::new() }
        }

        unsafe fn set_path(&mut self, key: &str, value: &Path) {
            self.saved.push((key.to_string(), std::env::var(key).ok()));
            unsafe { std::env::set_var(key, value) };
        }

        unsafe fn set_str(&mut self, key: &str, value: &str) {
            self.saved.push((key.to_string(), std::env::var(key).ok()));
            unsafe { std::env::set_var(key, value) };
        }
    }

    impl Drop for ScopedEnv {
        fn drop(&mut self) {
            for (key, old) in self.saved.drain(..).rev() {
                unsafe {
                    match old {
                        Some(value) => std::env::set_var(&key, value),
                        None => std::env::remove_var(&key),
                    }
                }
            }
        }
    }

    fn env_lock() -> std::sync::MutexGuard<'static, ()> {
        static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
        match LOCK.get_or_init(|| Mutex::new(())).lock() {
            Ok(guard) => guard,
            Err(err) => err.into_inner(),
        }
    }

    struct TestEnv {
        _lock: std::sync::MutexGuard<'static, ()>,
        _env: ScopedEnv,
        codex_home: PathBuf,
        claude_home: PathBuf,
    }

    fn setup_temp_env() -> TestEnv {
        let lock = env_lock();
        let root =
            std::env::temp_dir().join(format!("codex-helper-switch-test-{}", uuid::Uuid::new_v4()));
        std::fs::create_dir_all(&root).expect("create temp root");

        let codex_home = root.join(".codex");
        let claude_home = root.join(".claude");
        let proxy_home = root.join(".codex-helper");
        std::fs::create_dir_all(&codex_home).expect("create temp codex home");
        std::fs::create_dir_all(&claude_home).expect("create temp claude home");
        std::fs::create_dir_all(&proxy_home).expect("create temp proxy home");

        let mut scoped = ScopedEnv::new();
        unsafe {
            scoped.set_path("CODEX_HOME", &codex_home);
            scoped.set_path("CLAUDE_HOME", &claude_home);
            scoped.set_path("CODEX_HELPER_HOME", &proxy_home);
            scoped.set_path("HOME", &root);
            scoped.set_path("USERPROFILE", &root);
            scoped.set_str("CODEX_HELPER_IMAGEGEN_TEST_KEY", "sk-relay-test");
            scoped.set_str("CODEX_HELPER_MISSING_IMAGEGEN_KEY", "");
        }

        TestEnv {
            _lock: lock,
            _env: scoped,
            codex_home,
            claude_home,
        }
    }

    fn write_file(path: &Path, content: &str) {
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).expect("create parent directories");
        }
        std::fs::write(path, content).expect("write test file");
    }

    fn read_file(path: &Path) -> String {
        std::fs::read_to_string(path).expect("read test file")
    }

    fn write_helper_codex_config(env: &TestEnv, content: &str) {
        let proxy_home = env.codex_home.parent().unwrap().join(".codex-helper");
        write_file(&proxy_home.join("config.toml"), content.trim_start());
    }

    fn write_helper_codex_config_with_env_auth(env: &TestEnv) {
        write_helper_codex_config(
            env,
            r#"
version = 5

[codex.providers.relay]
base_url = "https://relay.example/v1"
auth_token_env = "CODEX_HELPER_IMAGEGEN_TEST_KEY"

[codex.routing]
entry = "main"

[codex.routing.routes.main]
strategy = "ordered-failover"
children = ["relay"]
"#,
        );
    }

    fn fake_chatgpt_jwt(email: &str, account_id: &str, plan_type: &str) -> String {
        let header = json!({
            "alg": "none",
            "typ": "JWT",
        });
        let payload = json!({
            "email": email,
            "https://api.openai.com/auth": {
                "chatgpt_account_id": account_id,
                "chatgpt_plan_type": plan_type,
            },
        });
        let encode = |value: serde_json::Value| {
            let bytes = serde_json::to_vec(&value).expect("serialize JWT part");
            base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes)
        };
        format!("{}.{}.sig", encode(header), encode(payload))
    }

    fn chatgpt_auth_json(email: &str, account_id: &str, plan_type: &str) -> String {
        let id_token = fake_chatgpt_jwt(email, account_id, plan_type);
        serde_json::to_string_pretty(&json!({
            "auth_mode": "chatgpt",
            "OPENAI_API_KEY": "sk-platform-onboarding",
            "tokens": {
                "id_token": id_token,
                "access_token": "chatgpt-access-token",
                "refresh_token": "chatgpt-refresh-token",
                "account_id": account_id,
            },
            "last_refresh": "2026-05-17T00:00:00Z",
        }))
        .expect("serialize chatgpt auth fixture")
    }

    fn chatgpt_auth_json_without_plan(email: &str, account_id: &str) -> String {
        let header = json!({
            "alg": "none",
            "typ": "JWT",
        });
        let payload = json!({
            "email": email,
            "https://api.openai.com/auth": {
                "chatgpt_account_id": account_id,
            },
        });
        let encode = |value: serde_json::Value| {
            let bytes = serde_json::to_vec(&value).expect("serialize JWT part");
            base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes)
        };
        let id_token = format!("{}.{}.sig", encode(header), encode(payload));
        serde_json::to_string_pretty(&json!({
            "auth_mode": "chatgpt",
            "OPENAI_API_KEY": null,
            "tokens": {
                "id_token": id_token,
                "access_token": "chatgpt-access-token",
                "refresh_token": "chatgpt-refresh-token",
                "account_id": account_id,
            },
            "last_refresh": "2026-05-17T00:00:00Z",
        }))
        .expect("serialize chatgpt auth fixture")
    }

    #[test]
    fn codex_switch_on_preserves_unrelated_toml_comments_and_fields() {
        let env = setup_temp_env();
        let cfg_path = env.codex_home.join("config.toml");

        let original = r#"# top comment
model_provider = "openai"

[model_providers.openai]
# keep this comment
name = "OpenAI"
base_url = "https://api.openai.com/v1"
request_max_retries = 3

[projects."D:\\Work"]
trust_level = "trusted"
"#;

        write_file(&cfg_path, original);
        switch_on(3211).expect("switch_on should preserve editable TOML structure");

        let updated = read_file(&cfg_path);
        assert!(updated.contains("# top comment"));
        assert!(updated.contains("# keep this comment"));
        assert!(updated.contains("[model_providers.openai]"));
        assert!(updated.contains("[projects."));
        assert!(updated.contains("model_provider = \"codex_proxy\""));
        assert!(updated.contains("[model_providers.codex_proxy]"));
        assert!(updated.contains("base_url = \"http://127.0.0.1:3211\""));
    }

    #[test]
    fn codex_switch_on_keeps_existing_proxy_retry_setting() {
        let text = r#"
model_provider = "codex_proxy"

[model_providers.codex_proxy]
name = "custom"
base_url = "http://127.0.0.1:1111"
request_max_retries = 5
"#;

        let updated = switch_on_codex_toml_with_mode(text, 3333, CodexPatchMode::Default)
            .expect("switch_on should update the local proxy provider in place");

        assert!(updated.contains("request_max_retries = 5"));
        assert!(updated.contains("base_url = \"http://127.0.0.1:3333\""));
        assert!(updated.contains("name = \"codex-helper\""));
    }

    #[test]
    fn codex_patch_plan_chatgpt_bridge_keeps_account_auth_shape_and_safe_write_order() {
        let plan = CodexPatchPlan::for_switch_on(
            CodexPatchMode::ChatGptBridge,
            CodexSwitchOptions::default(),
        )
        .expect("chatgpt bridge patch plan");

        assert_eq!(plan.provider().provider_name(), "codex-helper");
        assert_eq!(plan.provider().requires_openai_auth().value(), Some(true));
        assert_eq!(plan.provider().supports_websockets().value(), Some(false));
        assert_eq!(plan.auth(), CodexAuthPatchPlan::PatchChatGptBridge);
        assert_eq!(
            plan.effect_order(),
            CodexSwitchOnEffectOrder::StateConfigAuth
        );
        assert!(
            !plan.requires_bridge_runtime_ready(),
            "chatgpt bridge validates the existing Codex auth.json instead of helper upstream auth"
        );
    }

    #[test]
    fn codex_patch_plan_official_relay_uses_openai_identity_without_auth_facade() {
        let plan = CodexPatchPlan::for_switch_on(
            CodexPatchMode::OfficialRelayBridge,
            CodexSwitchOptions {
                responses_websocket: true,
            },
        )
        .expect("official relay patch plan");

        assert_eq!(plan.provider().provider_name(), "OpenAI");
        assert_eq!(plan.provider().requires_openai_auth().value(), None);
        assert_eq!(plan.provider().supports_websockets().value(), Some(true));
        assert_eq!(
            plan.auth(),
            CodexAuthPatchPlan::RestoreOriginalIfHelperPatched
        );
        assert_eq!(
            plan.effect_order(),
            CodexSwitchOnEffectOrder::ConfigAuthState
        );
        assert!(plan.requires_bridge_runtime_ready());
    }

    #[test]
    fn codex_patch_plan_official_imagegen_combines_openai_identity_and_auth_facade() {
        let plan = CodexPatchPlan::for_switch_on(
            CodexPatchMode::OfficialImagegenBridge,
            CodexSwitchOptions::default(),
        )
        .expect("official imagegen patch plan");

        assert_eq!(plan.provider().provider_name(), "OpenAI");
        assert_eq!(plan.provider().requires_openai_auth().value(), None);
        assert_eq!(plan.provider().supports_websockets().value(), Some(false));
        assert_eq!(plan.auth(), CodexAuthPatchPlan::PatchImagegenFacade);
        assert_eq!(
            plan.effect_order(),
            CodexSwitchOnEffectOrder::StateConfigAuth
        );
        assert!(plan.requires_bridge_runtime_ready());
    }

    #[test]
    fn codex_patch_plan_rejects_websocket_transport_without_official_identity() {
        let err = CodexPatchPlan::for_switch_on(
            CodexPatchMode::ImagegenBridge,
            CodexSwitchOptions {
                responses_websocket: true,
            },
        )
        .expect_err("websocket transport should be official identity only");

        assert!(
            err.to_string()
                .contains("requires --preset official-relay or --preset official-imagegen")
        );
    }

    #[test]
    fn codex_switch_on_toml_is_driven_by_patch_plan() {
        let text = r#"
model_provider = "codex_proxy"

[model_providers.codex_proxy]
name = "codex-helper"
base_url = "http://127.0.0.1:1111"
wire_api = "responses"
requires_openai_auth = true
supports_websockets = false
"#;
        let plan = CodexPatchPlan::for_switch_on(
            CodexPatchMode::OfficialRelayBridge,
            CodexSwitchOptions {
                responses_websocket: true,
            },
        )
        .expect("official relay patch plan");

        let updated =
            switch_on_codex_toml_with_plan(text, 3333, plan).expect("plan-driven TOML patch");

        assert!(updated.contains("name = \"OpenAI\""));
        assert!(updated.contains("base_url = \"http://127.0.0.1:3333\""));
        assert!(updated.contains("supports_websockets = true"));
        assert!(!updated.contains("requires_openai_auth"));
    }

    #[test]
    fn codex_auth_edit_for_switch_on_plan_restores_prior_facade_from_current_text() {
        let original_auth = chatgpt_auth_json("user@example.com", "acct_1", "plus");
        let mut state = CodexSwitchState {
            version: 2,
            patch_mode: Some(CodexPatchMode::OfficialImagegenBridge),
            responses_websocket: false,
            original_config_absent: false,
            original_model_provider: None,
            original_codex_proxy: None,
            had_model_providers: false,
            original_auth_json_absent: false,
            original_auth_json: Some(original_auth.clone()),
            patched_auth_json: Some("{}".to_string()),
        };
        let plan = CodexPatchPlan::for_switch_on(
            CodexPatchMode::OfficialRelayBridge,
            CodexSwitchOptions::default(),
        )
        .expect("official relay patch plan");

        let edit = auth_restore_edit_from_state_and_current(&mut state, Some("{}"));

        assert_eq!(
            plan.auth(),
            CodexAuthPatchPlan::RestoreOriginalIfHelperPatched
        );
        assert_eq!(edit, CodexAuthEdit::Write(original_auth));
        assert_eq!(state.patched_auth_json, None);
    }

    #[test]
    fn codex_switch_on_chatgpt_bridge_sets_openai_auth_flags() {
        let updated = switch_on_codex_toml_with_mode("", 3333, CodexPatchMode::ChatGptBridge)
            .expect("switch_on should write chatgpt bridge fields");

        assert!(updated.contains("model_provider = \"codex_proxy\""));
        assert!(updated.contains("base_url = \"http://127.0.0.1:3333\""));
        assert!(updated.contains("requires_openai_auth = true"));
        assert!(updated.contains("supports_websockets = false"));
    }

    #[test]
    fn codex_switch_on_imagegen_bridge_uses_default_proxy_flags() {
        let updated = switch_on_codex_toml_with_mode("", 3333, CodexPatchMode::ImagegenBridge)
            .expect("switch_on should write imagegen bridge fields");

        assert!(updated.contains("model_provider = \"codex_proxy\""));
        assert!(updated.contains("name = \"codex-helper\""));
        assert!(updated.contains("base_url = \"http://127.0.0.1:3333\""));
        assert!(!updated.contains("requires_openai_auth"));
        assert!(!updated.contains("supports_websockets"));
    }

    #[test]
    fn codex_switch_on_official_relay_bridge_sets_openai_name_and_disables_websockets() {
        let updated = switch_on_codex_toml_with_mode("", 3333, CodexPatchMode::OfficialRelayBridge)
            .expect("switch_on should write official relay preset fields");

        assert!(updated.contains("model_provider = \"codex_proxy\""));
        assert!(updated.contains("name = \"OpenAI\""));
        assert!(updated.contains("base_url = \"http://127.0.0.1:3333\""));
        assert!(updated.contains("wire_api = \"responses\""));
        assert!(updated.contains("supports_websockets = false"));
        assert!(!updated.contains("requires_openai_auth"));
    }

    #[test]
    fn codex_switch_on_official_relay_bridge_can_enable_responses_websocket() {
        let updated = switch_on_codex_toml_with_options(
            "",
            3333,
            CodexPatchMode::OfficialRelayBridge,
            CodexSwitchOptions {
                responses_websocket: true,
            },
        )
        .expect("switch_on should write official relay preset fields with websocket transport");

        assert!(updated.contains("model_provider = \"codex_proxy\""));
        assert!(updated.contains("name = \"OpenAI\""));
        assert!(updated.contains("base_url = \"http://127.0.0.1:3333\""));
        assert!(updated.contains("wire_api = \"responses\""));
        assert!(updated.contains("supports_websockets = true"));
        assert!(!updated.contains("requires_openai_auth"));
    }

    #[test]
    fn codex_switch_on_official_imagegen_bridge_sets_openai_name_and_disables_websockets() {
        let updated =
            switch_on_codex_toml_with_mode("", 3333, CodexPatchMode::OfficialImagegenBridge)
                .expect("switch_on should write official imagegen preset fields");

        assert!(updated.contains("model_provider = \"codex_proxy\""));
        assert!(updated.contains("name = \"OpenAI\""));
        assert!(updated.contains("base_url = \"http://127.0.0.1:3333\""));
        assert!(updated.contains("wire_api = \"responses\""));
        assert!(updated.contains("supports_websockets = false"));
        assert!(!updated.contains("requires_openai_auth"));
    }

    #[test]
    fn codex_switch_on_official_imagegen_bridge_can_enable_responses_websocket() {
        let updated = switch_on_codex_toml_with_options(
            "",
            3333,
            CodexPatchMode::OfficialImagegenBridge,
            CodexSwitchOptions {
                responses_websocket: true,
            },
        )
        .expect("switch_on should write official imagegen preset fields with websocket transport");

        assert!(updated.contains("model_provider = \"codex_proxy\""));
        assert!(updated.contains("name = \"OpenAI\""));
        assert!(updated.contains("base_url = \"http://127.0.0.1:3333\""));
        assert!(updated.contains("wire_api = \"responses\""));
        assert!(updated.contains("supports_websockets = true"));
        assert!(!updated.contains("requires_openai_auth"));
    }

    #[test]
    fn empty_auth_json_facade_detection_uses_json_semantics() {
        assert!(auth_json_is_empty_chatgpt_facade_text(Some("{}")));
        assert!(auth_json_is_empty_chatgpt_facade_text(Some("{\n}\n")));
        assert!(!auth_json_is_empty_chatgpt_facade_text(Some(
            r#"{"auth_mode":"chatgpt"}"#
        )));
        assert!(!auth_json_is_empty_chatgpt_facade_text(None));
        assert!(!auth_json_is_empty_chatgpt_facade_text(Some("not-json")));
    }

    #[test]
    fn codex_switch_on_default_removes_bridge_only_flags() {
        let text = r#"
model_provider = "codex_proxy"

[model_providers.codex_proxy]
name = "codex-helper"
base_url = "http://127.0.0.1:1111"
wire_api = "responses"
requires_openai_auth = true
supports_websockets = false
"#;

        let updated = switch_on_codex_toml_with_mode(text, 3333, CodexPatchMode::Default)
            .expect("switch_on should switch local proxy back to default mode");

        assert!(updated.contains("base_url = \"http://127.0.0.1:3333\""));
        assert!(!updated.contains("requires_openai_auth"));
        assert!(!updated.contains("supports_websockets"));
    }

    #[test]
    fn remote_control_config_patch_sets_remote_connections_and_removes_removed_key() {
        let text = r#"
[features]
remote_control = true
apps = true
"#;

        let updated = ensure_codex_remote_connections_feature_in_toml(text)
            .expect("remote-control config patch should parse");

        assert!(updated.contains("remote_connections = true"));
        assert!(updated.contains("apps = true"));
        assert!(!updated.contains("remote_control = true"));
        assert!(
            codex_remote_connections_feature_enabled_from_toml(&updated)
                .expect("remote_connections should parse")
        );
        assert!(
            !codex_remote_control_feature_present_in_toml(&updated)
                .expect("remote_control should parse")
        );
    }

    #[test]
    fn codex_remote_control_enable_patches_config_backs_up_db_and_writes_sqlite() {
        let env = setup_temp_env();
        let cfg_path = env.codex_home.join("config.toml");
        let db_dir = env.codex_home.join("sqlite");
        let db_path = db_dir.join("codex-dev.db");
        std::fs::create_dir_all(&db_dir).expect("create sqlite dir");
        write_file(
            &cfg_path,
            r#"
[features]
remote_control = true
"#
            .trim_start(),
        );

        {
            let conn = rusqlite::Connection::open(&db_path).expect("open test sqlite");
            conn.execute(
                "CREATE TABLE local_app_server_feature_enablement (
                    feature_name TEXT PRIMARY KEY,
                    enabled INTEGER NOT NULL,
                    updated_at INTEGER NOT NULL
                )",
                [],
            )
            .expect("create feature table");
            conn.execute(
                "INSERT INTO local_app_server_feature_enablement (feature_name, enabled, updated_at)
                 VALUES (?1, ?2, ?3)",
                rusqlite::params!["remote_control", 0_i64, 7_i64],
            )
            .expect("seed feature row");
        }

        let result =
            codex_remote_control_enable().expect("remote-control enablement should succeed");

        assert!(result.backup_path.exists(), "backup should be created");
        assert!(result.status.remote_connections_enabled);
        assert!(!result.status.remote_control_config_present);
        assert_eq!(result.status.db_enabled, Some(true));
        assert!(result.status.db_updated_at.unwrap_or_default() > 7);

        let updated_cfg = read_file(&cfg_path);
        assert!(updated_cfg.contains("remote_connections = true"));
        assert!(!updated_cfg.contains("remote_control = true"));
    }

    #[test]
    fn codex_remote_control_enable_does_not_patch_config_when_db_schema_is_missing() {
        let env = setup_temp_env();
        let cfg_path = env.codex_home.join("config.toml");
        let db_dir = env.codex_home.join("sqlite");
        let db_path = db_dir.join("codex-dev.db");
        std::fs::create_dir_all(&db_dir).expect("create sqlite dir");
        write_file(
            &cfg_path,
            r#"
[features]
apps = true
"#
            .trim_start(),
        );
        {
            let _conn = rusqlite::Connection::open(&db_path).expect("open empty test sqlite");
        }
        let original = read_file(&cfg_path);

        let err = codex_remote_control_enable()
            .expect_err("remote-control enablement should reject missing feature table");

        assert!(
            err.to_string()
                .contains("local_app_server_feature_enablement")
        );
        assert_eq!(read_file(&cfg_path), original);
    }

    #[test]
    fn remote_control_log_scan_detects_successful_enablement_set() {
        let env = setup_temp_env();
        let log_dir = env.codex_home.join("log");
        std::fs::create_dir_all(&log_dir).expect("create log dir");
        write_file(
            &log_dir.join("codex-app.log"),
            r#"{"method":"experimentalFeature/enablement/set","errorCode":null}"#,
        );

        assert!(
            codex_remote_control_successful_enablement_log_seen_in_dir(&log_dir)
                .expect("scan logs")
        );
    }

    fn startup_readiness_input(changed: bool) -> CodexStartupReadinessInput {
        CodexStartupReadinessInput {
            expected_port: 3211,
            expected_patch_mode: CodexPatchMode::Default,
            expected_responses_websocket: false,
            client_state_changed_this_startup: changed,
            switch_error: None,
        }
    }

    fn has_startup_issue(
        report: &CodexStartupReadiness,
        kind: CodexStartupReadinessIssueKind,
    ) -> bool {
        report.issues.iter().any(|issue| issue.kind == kind)
    }

    #[test]
    fn codex_tui_startup_readiness_is_quiet_when_switch_is_ready() {
        let env = setup_temp_env();
        let cfg_path = env.codex_home.join("config.toml");
        write_file(
            &cfg_path,
            r#"
model_provider = "openai"

[model_providers.openai]
name = "openai"
base_url = "https://api.openai.com/v1"
"#
            .trim_start(),
        );
        switch_on(3211).expect("switch_on should create a valid local proxy patch");

        let report = codex_tui_startup_readiness(startup_readiness_input(false));

        assert_eq!(report.issues, Vec::new());
    }

    #[test]
    fn codex_tui_startup_readiness_reports_client_state_changed() {
        let env = setup_temp_env();
        let cfg_path = env.codex_home.join("config.toml");
        write_file(
            &cfg_path,
            r#"
model_provider = "openai"

[model_providers.openai]
name = "openai"
base_url = "https://api.openai.com/v1"
"#
            .trim_start(),
        );
        switch_on(3211).expect("switch_on should create a valid local proxy patch");

        let report = codex_tui_startup_readiness(startup_readiness_input(true));

        assert!(has_startup_issue(
            &report,
            CodexStartupReadinessIssueKind::ClientStateChanged
        ));
        assert_eq!(report.issues.len(), 1);
    }

    #[test]
    fn codex_tui_startup_readiness_warns_for_local_proxy_without_switch_state() {
        let env = setup_temp_env();
        let cfg_path = env.codex_home.join("config.toml");
        write_file(
            &cfg_path,
            r#"
model_provider = "codex_proxy"

[model_providers.codex_proxy]
name = "codex-helper"
base_url = "http://127.0.0.1:3211"
wire_api = "responses"
"#
            .trim_start(),
        );

        let report = codex_tui_startup_readiness(startup_readiness_input(false));

        assert!(has_startup_issue(
            &report,
            CodexStartupReadinessIssueKind::MissingSwitchState
        ));
    }

    #[test]
    fn codex_tui_startup_readiness_warns_official_bridge_with_preferred_group_multi_provider() {
        let env = setup_temp_env();
        write_helper_codex_config(
            &env,
            r#"
version = 5

[codex.providers.a]
base_url = "https://a.example/v1"
auth_token_env = "CODEX_HELPER_IMAGEGEN_TEST_KEY"

[codex.providers.b]
base_url = "https://b.example/v1"
auth_token_env = "CODEX_HELPER_IMAGEGEN_TEST_KEY"

[codex.routing]
entry = "main"
affinity_policy = "preferred-group"

[codex.routing.routes.main]
strategy = "ordered-failover"
children = ["a", "b"]
"#,
        );
        let cfg_path = env.codex_home.join("config.toml");
        write_file(
            &cfg_path,
            r#"
model_provider = "codex_proxy"

[model_providers.codex_proxy]
name = "OpenAI"
base_url = "http://127.0.0.1:3211"
wire_api = "responses"
supports_websockets = false
"#
            .trim_start(),
        );

        let mut input = startup_readiness_input(false);
        input.expected_patch_mode = CodexPatchMode::OfficialRelayBridge;
        let report = codex_tui_startup_readiness(input);

        assert!(has_startup_issue(
            &report,
            CodexStartupReadinessIssueKind::OfficialRelayAffinityPolicy
        ));
    }

    #[test]
    fn codex_tui_startup_readiness_accepts_official_bridge_with_fallback_sticky() {
        let env = setup_temp_env();
        write_helper_codex_config(
            &env,
            r#"
version = 5

[codex.providers.a]
base_url = "https://a.example/v1"
auth_token_env = "CODEX_HELPER_IMAGEGEN_TEST_KEY"

[codex.providers.b]
base_url = "https://b.example/v1"
auth_token_env = "CODEX_HELPER_IMAGEGEN_TEST_KEY"

[codex.routing]
entry = "main"
affinity_policy = "fallback-sticky"

[codex.routing.routes.main]
strategy = "ordered-failover"
children = ["a", "b"]
"#,
        );
        let cfg_path = env.codex_home.join("config.toml");
        write_file(
            &cfg_path,
            r#"
model_provider = "codex_proxy"

[model_providers.codex_proxy]
name = "OpenAI"
base_url = "http://127.0.0.1:3211"
wire_api = "responses"
supports_websockets = false
"#
            .trim_start(),
        );

        let mut input = startup_readiness_input(false);
        input.expected_patch_mode = CodexPatchMode::OfficialRelayBridge;
        let report = codex_tui_startup_readiness(input);

        assert!(!has_startup_issue(
            &report,
            CodexStartupReadinessIssueKind::OfficialRelayAffinityPolicy
        ));
    }

    #[test]
    fn codex_tui_startup_readiness_warns_when_remote_control_log_is_unconfirmed() {
        let env = setup_temp_env();
        let cfg_path = env.codex_home.join("config.toml");
        let db_dir = env.codex_home.join("sqlite");
        let db_path = db_dir.join("codex-dev.db");
        std::fs::create_dir_all(&db_dir).expect("create sqlite dir");
        write_file(
            &cfg_path,
            r#"
model_provider = "openai"

[features]
remote_connections = true

[model_providers.openai]
name = "openai"
base_url = "https://api.openai.com/v1"
"#
            .trim_start(),
        );
        {
            let conn = rusqlite::Connection::open(&db_path).expect("open test sqlite");
            conn.execute(
                "CREATE TABLE local_app_server_feature_enablement (
                    feature_name TEXT PRIMARY KEY,
                    enabled INTEGER NOT NULL,
                    updated_at INTEGER NOT NULL
                )",
                [],
            )
            .expect("create feature table");
            conn.execute(
                "INSERT INTO local_app_server_feature_enablement (feature_name, enabled, updated_at)
                 VALUES (?1, ?2, ?3)",
                rusqlite::params!["remote_control", 1_i64, 7_i64],
            )
            .expect("seed feature row");
        }
        switch_on(3211).expect("switch_on should preserve features");

        let report = codex_tui_startup_readiness(startup_readiness_input(false));

        assert!(has_startup_issue(
            &report,
            CodexStartupReadinessIssueKind::RemoteControlLogUnconfirmed
        ));
    }

    #[test]
    fn chatgpt_bridge_auth_patch_preserves_other_auth_json_fields() {
        let mut input: serde_json::Value =
            serde_json::from_str(&chatgpt_auth_json("user@example.com", "account-1", "plus"))
                .expect("valid fixture");
        input["last_refresh"] = json!(123);
        input["unrelated"] = json!("keep");

        let updated = chatgpt_bridge_auth_json_text(&serde_json::to_string_pretty(&input).unwrap())
            .expect("auth json patch should preserve unrelated fields");
        let value: serde_json::Value = serde_json::from_str(&updated).expect("valid json");
        let object = value.as_object().expect("root object");

        assert_eq!(
            object.get("auth_mode").and_then(|value| value.as_str()),
            Some("chatgpt")
        );
        assert!(
            object
                .get("OPENAI_API_KEY")
                .is_some_and(|value| value.is_null())
        );
        assert_eq!(
            object
                .get("tokens")
                .and_then(|value| value.get("access_token"))
                .and_then(|value| value.as_str()),
            Some("chatgpt-access-token")
        );
        assert_eq!(
            object
                .get("tokens")
                .and_then(|value| value.get("account_id"))
                .and_then(|value| value.as_str()),
            Some("account-1")
        );
        assert_eq!(
            object.get("last_refresh").and_then(|value| value.as_i64()),
            Some(123)
        );
        assert_eq!(
            object.get("unrelated").and_then(|value| value.as_str()),
            Some("keep")
        );
    }

    #[test]
    fn chatgpt_bridge_auth_patch_rejects_incomplete_login_state() {
        let err = chatgpt_bridge_auth_json_text(r#"{"auth_mode":"chatgpt","OPENAI_API_KEY":null}"#)
            .expect_err("empty ChatGPT auth state should be rejected");

        let message = err.to_string();
        assert!(message.contains("complete ChatGPT login state"));
        assert!(message.contains("tokens.id_token"));
        assert!(message.contains("tokens.access_token"));
        assert!(message.contains("last_refresh"));
    }

    #[test]
    fn chatgpt_bridge_auth_patch_rejects_api_key_only_auth() {
        let err = chatgpt_bridge_auth_json_text(
            r#"{"auth_mode":"apikey","OPENAI_API_KEY":"sk-old","account_id":"acct_1"}"#,
        )
        .expect_err("API key auth should not be converted into fake ChatGPT auth");

        assert!(
            err.to_string()
                .contains("Open Codex and sign in with ChatGPT first")
        );
    }

    #[test]
    fn chatgpt_bridge_auth_patch_accepts_chatgpt_auth_without_plan_claim() {
        let input = chatgpt_auth_json_without_plan("user@example.com", "acct_1");

        let updated = chatgpt_bridge_auth_json_text(&input)
            .expect("Codex maps missing ChatGPT plan claims to unknown");
        let value: serde_json::Value = serde_json::from_str(&updated).expect("valid json");

        assert_eq!(
            value.get("auth_mode").and_then(|value| value.as_str()),
            Some("chatgpt")
        );
        assert!(
            value
                .get("OPENAI_API_KEY")
                .is_some_and(|value| value.is_null())
        );
    }

    #[test]
    fn imagegen_bridge_auth_patch_writes_empty_chatgpt_facade() {
        let updated = imagegen_bridge_auth_json_text().expect("serialize facade auth");
        let value: serde_json::Value = serde_json::from_str(&updated).expect("valid json");

        assert!(
            value.as_object().is_some_and(serde_json::Map::is_empty),
            "imagegen bridge must rely on Codex's default ChatGPT mode fallback, not an explicit auth_mode field"
        );
    }

    #[test]
    fn helper_auth_patch_match_uses_json_semantics() {
        assert!(auth_json_matches_helper_patch(
            Some(r#"{"auth_mode":"chatgpt"}"#),
            "{\n  \"auth_mode\": \"chatgpt\"\n}"
        ));
        assert!(!auth_json_matches_helper_patch(
            Some(r#"{"auth_mode":"apikey"}"#),
            "{\n  \"auth_mode\": \"chatgpt\"\n}"
        ));
    }

    #[test]
    fn imagegen_bridge_ready_check_rejects_missing_codex_upstreams() {
        let _env = setup_temp_env();

        let err = ensure_imagegen_bridge_runtime_ready()
            .expect_err("imagegen bridge should require codex-helper upstreams");

        assert!(
            err.to_string()
                .contains("requires at least one enabled Codex upstream")
        );
    }

    #[test]
    fn imagegen_bridge_ready_check_rejects_unresolved_upstream_env() {
        let env = setup_temp_env();
        write_helper_codex_config(
            &env,
            r#"
version = 5

[codex.providers.relay]
base_url = "https://relay.example/v1"
auth_token_env = "CODEX_HELPER_MISSING_IMAGEGEN_KEY"

[codex.routing]
entry = "main"

[codex.routing.routes.main]
strategy = "ordered-failover"
children = ["relay"]
"#,
        );

        let err = ensure_imagegen_bridge_runtime_ready()
            .expect_err("imagegen bridge should require resolved upstream auth");

        let message = err.to_string();
        assert!(message.contains("no enabled Codex upstream credential is available"));
        assert!(message.contains("CODEX_HELPER_MISSING_IMAGEGEN_KEY"));
    }

    #[test]
    fn official_relay_bridge_ready_check_rejects_unresolved_upstream_env() {
        let env = setup_temp_env();
        write_helper_codex_config(
            &env,
            r#"
version = 5

[codex.providers.relay]
base_url = "https://relay.example/v1"
auth_token_env = "CODEX_HELPER_MISSING_IMAGEGEN_KEY"

[codex.routing]
entry = "main"

[codex.routing.routes.main]
strategy = "ordered-failover"
children = ["relay"]
"#,
        );

        let err = ensure_bridge_runtime_ready(CodexPatchMode::OfficialRelayBridge)
            .expect_err("official relay preset should require resolved upstream auth");

        let message = err.to_string();
        assert!(message.contains("official-relay"));
        assert!(message.contains("no enabled Codex upstream credential is available"));
        assert!(message.contains("CODEX_HELPER_MISSING_IMAGEGEN_KEY"));
    }

    #[test]
    fn official_imagegen_bridge_ready_check_rejects_unresolved_upstream_env() {
        let env = setup_temp_env();
        write_helper_codex_config(
            &env,
            r#"
version = 5

[codex.providers.relay]
base_url = "https://relay.example/v1"
auth_token_env = "CODEX_HELPER_MISSING_IMAGEGEN_KEY"

[codex.routing]
entry = "main"

[codex.routing.routes.main]
strategy = "ordered-failover"
children = ["relay"]
"#,
        );

        let err = ensure_bridge_runtime_ready(CodexPatchMode::OfficialImagegenBridge)
            .expect_err("official imagegen preset should require resolved upstream auth");

        let message = err.to_string();
        assert!(message.contains("official-imagegen"));
        assert!(message.contains("no enabled Codex upstream credential is available"));
        assert!(message.contains("CODEX_HELPER_MISSING_IMAGEGEN_KEY"));
    }

    #[test]
    fn official_relay_bridge_with_responses_websocket_ready_check_rejects_unresolved_upstream_env()
    {
        let env = setup_temp_env();
        write_helper_codex_config(
            &env,
            r#"
version = 5

[codex.providers.relay]
base_url = "https://relay.example/v1"
auth_token_env = "CODEX_HELPER_MISSING_IMAGEGEN_KEY"

[codex.routing]
entry = "main"

[codex.routing.routes.main]
strategy = "ordered-failover"
children = ["relay"]
"#,
        );

        let err = switch_on_with_options(
            3211,
            CodexPatchMode::OfficialRelayBridge,
            CodexSwitchOptions {
                responses_websocket: true,
            },
        )
        .expect_err("official relay preset with websocket should require resolved upstream auth");

        let message = err.to_string();
        assert!(message.contains("official-relay"));
        assert!(message.contains("no enabled Codex upstream credential is available"));
        assert!(message.contains("CODEX_HELPER_MISSING_IMAGEGEN_KEY"));
    }

    #[test]
    fn codex_switch_on_chatgpt_bridge_patches_auth_json() {
        let env = setup_temp_env();
        let cfg_path = env.codex_home.join("config.toml");
        let auth_path = env.codex_home.join("auth.json");

        write_file(
            &cfg_path,
            r#"
model_provider = "openai"

[model_providers.openai]
name = "openai"
base_url = "https://api.openai.com/v1"
"#
            .trim_start(),
        );
        write_file(
            &auth_path,
            &chatgpt_auth_json("user@example.com", "acct_1", "plus"),
        );

        switch_on_with_mode(3211, CodexPatchMode::ChatGptBridge)
            .expect("switch_on bridge should patch config and auth");

        let updated_cfg = read_file(&cfg_path);
        assert!(updated_cfg.contains("requires_openai_auth = true"));
        assert!(updated_cfg.contains("supports_websockets = false"));

        let updated_auth: serde_json::Value =
            serde_json::from_str(&read_file(&auth_path)).expect("valid auth json");
        assert_eq!(
            updated_auth
                .get("auth_mode")
                .and_then(|value| value.as_str()),
            Some("chatgpt")
        );
        assert!(
            updated_auth
                .get("OPENAI_API_KEY")
                .is_some_and(|value| value.is_null())
        );
        assert_eq!(
            updated_auth
                .get("tokens")
                .and_then(|value| value.get("account_id"))
                .and_then(|value| value.as_str()),
            Some("acct_1")
        );
    }

    #[test]
    fn codex_switch_on_imagegen_bridge_patches_auth_json_and_records_mode() {
        let env = setup_temp_env();
        write_helper_codex_config_with_env_auth(&env);
        let cfg_path = env.codex_home.join("config.toml");
        let auth_path = env.codex_home.join("auth.json");
        let state_path = env.codex_home.join("codex-helper-switch-state.json");
        let original_auth = chatgpt_auth_json("user@example.com", "acct_1", "plus");

        write_file(
            &cfg_path,
            r#"
model_provider = "openai"

[model_providers.openai]
name = "openai"
base_url = "https://api.openai.com/v1"
"#
            .trim_start(),
        );
        write_file(&auth_path, &original_auth);

        switch_on_with_mode(3211, CodexPatchMode::ImagegenBridge)
            .expect("switch_on imagegen bridge should patch config and auth");

        let updated_cfg = read_file(&cfg_path);
        assert!(updated_cfg.contains("model_provider = \"codex_proxy\""));
        assert!(!updated_cfg.contains("requires_openai_auth"));

        let updated_auth: serde_json::Value =
            serde_json::from_str(&read_file(&auth_path)).expect("valid auth json");
        assert!(
            updated_auth
                .as_object()
                .is_some_and(serde_json::Map::is_empty)
        );

        let state_text = read_file(&state_path);
        let state: serde_json::Value = serde_json::from_str(&state_text).expect("valid state");
        assert_eq!(
            state.get("patch_mode").and_then(|value| value.as_str()),
            Some("imagegen-bridge")
        );
        assert_eq!(
            state
                .get("original_auth_json")
                .and_then(|value| value.as_str()),
            Some(original_auth.as_str())
        );
        assert_eq!(
            state
                .get("patched_auth_json")
                .and_then(|value| value.as_str()),
            Some("{}")
        );
    }

    #[test]
    fn codex_switch_on_official_relay_bridge_records_mode_without_auth_json_patch() {
        let env = setup_temp_env();
        write_helper_codex_config_with_env_auth(&env);
        let cfg_path = env.codex_home.join("config.toml");
        let auth_path = env.codex_home.join("auth.json");
        let state_path = env.codex_home.join("codex-helper-switch-state.json");
        let original_auth = chatgpt_auth_json("user@example.com", "acct_1", "plus");

        write_file(
            &cfg_path,
            r#"
model_provider = "openai"

[model_providers.openai]
name = "openai"
base_url = "https://api.openai.com/v1"
"#
            .trim_start(),
        );
        write_file(&auth_path, &original_auth);

        switch_on_with_mode(3211, CodexPatchMode::OfficialRelayBridge)
            .expect("switch_on official relay preset should patch config");

        let updated_cfg = read_file(&cfg_path);
        assert!(updated_cfg.contains("model_provider = \"codex_proxy\""));
        assert!(updated_cfg.contains("name = \"OpenAI\""));
        assert!(updated_cfg.contains("supports_websockets = false"));
        assert!(!updated_cfg.contains("requires_openai_auth"));
        assert_eq!(read_file(&auth_path), original_auth);

        let state_text = read_file(&state_path);
        let state: serde_json::Value = serde_json::from_str(&state_text).expect("valid state");
        assert_eq!(
            state.get("patch_mode").and_then(|value| value.as_str()),
            Some("official-relay-bridge")
        );
        assert!(state.get("patched_auth_json").is_none());

        let status = codex_switch_status().expect("status should load");
        assert_eq!(status.patch_mode, Some(CodexPatchMode::OfficialRelayBridge));
        assert_eq!(status.requires_openai_auth, None);
        assert_eq!(status.supports_websockets, Some(false));
    }

    #[test]
    fn codex_switch_on_official_relay_bridge_records_transport_option_without_auth_json_patch() {
        let env = setup_temp_env();
        write_helper_codex_config_with_env_auth(&env);
        let cfg_path = env.codex_home.join("config.toml");
        let auth_path = env.codex_home.join("auth.json");
        let state_path = env.codex_home.join("codex-helper-switch-state.json");
        let original_auth = chatgpt_auth_json("user@example.com", "acct_1", "plus");

        write_file(
            &cfg_path,
            r#"
model_provider = "openai"

[model_providers.openai]
name = "openai"
base_url = "https://api.openai.com/v1"
"#
            .trim_start(),
        );
        write_file(&auth_path, &original_auth);

        switch_on_with_options(
            3211,
            CodexPatchMode::OfficialRelayBridge,
            CodexSwitchOptions {
                responses_websocket: true,
            },
        )
        .expect("switch_on official relay preset should patch config with websocket transport");

        let updated_cfg = read_file(&cfg_path);
        assert!(updated_cfg.contains("model_provider = \"codex_proxy\""));
        assert!(updated_cfg.contains("name = \"OpenAI\""));
        assert!(updated_cfg.contains("supports_websockets = true"));
        assert!(!updated_cfg.contains("requires_openai_auth"));
        assert_eq!(read_file(&auth_path), original_auth);

        let state_text = read_file(&state_path);
        let state: serde_json::Value = serde_json::from_str(&state_text).expect("valid state");
        assert_eq!(
            state.get("patch_mode").and_then(|value| value.as_str()),
            Some("official-relay-bridge")
        );
        assert_eq!(
            state
                .get("responses_websocket")
                .and_then(|value| value.as_bool()),
            Some(true)
        );
        assert!(state.get("patched_auth_json").is_none());

        let status = codex_switch_status().expect("status should load");
        assert_eq!(status.patch_mode, Some(CodexPatchMode::OfficialRelayBridge));
        assert_eq!(status.requires_openai_auth, None);
        assert_eq!(status.supports_websockets, Some(true));
    }

    #[test]
    fn codex_switch_on_official_imagegen_bridge_records_mode_and_patches_auth_json() {
        let env = setup_temp_env();
        write_helper_codex_config_with_env_auth(&env);
        let cfg_path = env.codex_home.join("config.toml");
        let auth_path = env.codex_home.join("auth.json");
        let state_path = env.codex_home.join("codex-helper-switch-state.json");
        let original_auth = chatgpt_auth_json("user@example.com", "acct_1", "plus");

        write_file(
            &cfg_path,
            r#"
model_provider = "openai"

[model_providers.openai]
name = "openai"
base_url = "https://api.openai.com/v1"
"#
            .trim_start(),
        );
        write_file(&auth_path, &original_auth);

        switch_on_with_mode(3211, CodexPatchMode::OfficialImagegenBridge)
            .expect("switch_on official imagegen preset should patch config and auth");

        let updated_cfg = read_file(&cfg_path);
        assert!(updated_cfg.contains("model_provider = \"codex_proxy\""));
        assert!(updated_cfg.contains("name = \"OpenAI\""));
        assert!(updated_cfg.contains("supports_websockets = false"));
        assert!(!updated_cfg.contains("requires_openai_auth"));

        let updated_auth: serde_json::Value =
            serde_json::from_str(&read_file(&auth_path)).expect("valid auth json");
        assert!(
            updated_auth
                .as_object()
                .is_some_and(serde_json::Map::is_empty)
        );

        let state_text = read_file(&state_path);
        let state: serde_json::Value = serde_json::from_str(&state_text).expect("valid state");
        assert_eq!(
            state.get("patch_mode").and_then(|value| value.as_str()),
            Some("official-imagegen-bridge")
        );
        assert_eq!(
            state
                .get("original_auth_json")
                .and_then(|value| value.as_str()),
            Some(original_auth.as_str())
        );
        assert_eq!(
            state
                .get("patched_auth_json")
                .and_then(|value| value.as_str()),
            Some("{}")
        );

        let status = codex_switch_status().expect("status should load");
        assert_eq!(
            status.patch_mode,
            Some(CodexPatchMode::OfficialImagegenBridge)
        );
        assert_eq!(status.requires_openai_auth, None);
        assert_eq!(status.supports_websockets, Some(false));
    }

    #[test]
    fn codex_switch_on_official_imagegen_bridge_records_transport_option_and_patches_auth_json() {
        let env = setup_temp_env();
        write_helper_codex_config_with_env_auth(&env);
        let cfg_path = env.codex_home.join("config.toml");
        let auth_path = env.codex_home.join("auth.json");
        let state_path = env.codex_home.join("codex-helper-switch-state.json");
        let original_auth = chatgpt_auth_json("user@example.com", "acct_1", "plus");

        write_file(
            &cfg_path,
            r#"
model_provider = "openai"

[model_providers.openai]
name = "openai"
base_url = "https://api.openai.com/v1"
"#
            .trim_start(),
        );
        write_file(&auth_path, &original_auth);

        switch_on_with_options(
            3211,
            CodexPatchMode::OfficialImagegenBridge,
            CodexSwitchOptions {
                responses_websocket: true,
            },
        )
        .expect("switch_on official imagegen preset should patch config and auth with websocket transport");

        let updated_cfg = read_file(&cfg_path);
        assert!(updated_cfg.contains("model_provider = \"codex_proxy\""));
        assert!(updated_cfg.contains("name = \"OpenAI\""));
        assert!(updated_cfg.contains("supports_websockets = true"));
        assert!(!updated_cfg.contains("requires_openai_auth"));

        let updated_auth: serde_json::Value =
            serde_json::from_str(&read_file(&auth_path)).expect("valid auth json");
        assert!(
            updated_auth
                .as_object()
                .is_some_and(serde_json::Map::is_empty)
        );

        let state_text = read_file(&state_path);
        let state: serde_json::Value = serde_json::from_str(&state_text).expect("valid state");
        assert_eq!(
            state.get("patch_mode").and_then(|value| value.as_str()),
            Some("official-imagegen-bridge")
        );
        assert_eq!(
            state
                .get("responses_websocket")
                .and_then(|value| value.as_bool()),
            Some(true)
        );
        assert_eq!(
            state
                .get("original_auth_json")
                .and_then(|value| value.as_str()),
            Some(original_auth.as_str())
        );
        assert_eq!(
            state
                .get("patched_auth_json")
                .and_then(|value| value.as_str()),
            Some("{}")
        );

        let status = codex_switch_status().expect("status should load");
        assert_eq!(
            status.patch_mode,
            Some(CodexPatchMode::OfficialImagegenBridge)
        );
        assert_eq!(status.requires_openai_auth, None);
        assert_eq!(status.supports_websockets, Some(true));
    }

    #[test]
    fn codex_switch_on_with_configured_preset_uses_helper_client_patch() {
        let env = setup_temp_env();
        write_helper_codex_config(
            &env,
            r#"
version = 5

[codex.client_patch]
preset = "official-imagegen"
responses_websocket = true

[codex.providers.relay]
base_url = "https://relay.example/v1"
auth_token_env = "CODEX_HELPER_IMAGEGEN_TEST_KEY"

[codex.routing]
entry = "main"

[codex.routing.routes.main]
strategy = "ordered-failover"
children = ["relay"]
"#,
        );
        let cfg_path = env.codex_home.join("config.toml");
        let auth_path = env.codex_home.join("auth.json");
        let original_auth = chatgpt_auth_json("user@example.com", "acct_1", "plus");

        write_file(
            &cfg_path,
            r#"
model_provider = "openai"

[model_providers.openai]
name = "openai"
base_url = "https://api.openai.com/v1"
"#
            .trim_start(),
        );
        write_file(&auth_path, &original_auth);

        switch_on_with_configured_preset(3211)
            .expect("configured official-imagegen preset should patch config and auth");

        let updated_cfg = read_file(&cfg_path);
        assert!(updated_cfg.contains("model_provider = \"codex_proxy\""));
        assert!(updated_cfg.contains("name = \"OpenAI\""));
        assert!(updated_cfg.contains("base_url = \"http://127.0.0.1:3211\""));
        assert!(updated_cfg.contains("supports_websockets = true"));
        assert!(!updated_cfg.contains("requires_openai_auth"));

        let updated_auth: serde_json::Value =
            serde_json::from_str(&read_file(&auth_path)).expect("valid auth json");
        assert!(
            updated_auth
                .as_object()
                .is_some_and(serde_json::Map::is_empty)
        );

        let status = codex_switch_status().expect("status should load");
        assert_eq!(
            status.patch_mode,
            Some(CodexPatchMode::OfficialImagegenBridge)
        );
        assert_eq!(status.provider_name.as_deref(), Some("OpenAI"));
        assert_eq!(status.supports_websockets, Some(true));
    }

    #[test]
    fn codex_switch_status_infers_official_relay_bridge_without_state() {
        let env = setup_temp_env();
        let cfg_path = env.codex_home.join("config.toml");
        write_file(
            &cfg_path,
            r#"
model_provider = "codex_proxy"

[model_providers.codex_proxy]
name = "OpenAI"
base_url = "http://127.0.0.1:3211"
wire_api = "responses"
supports_websockets = false
"#
            .trim_start(),
        );

        let status = codex_switch_status().expect("status should load");

        assert!(status.enabled);
        assert_eq!(status.patch_mode, Some(CodexPatchMode::OfficialRelayBridge));
        assert_eq!(status.supports_websockets, Some(false));
        assert_eq!(status.requires_openai_auth, None);
        assert!(!status.has_switch_state);
    }

    #[test]
    fn codex_switch_status_keeps_websocket_as_transport_for_official_relay_without_state() {
        let env = setup_temp_env();
        let cfg_path = env.codex_home.join("config.toml");
        write_file(
            &cfg_path,
            r#"
model_provider = "codex_proxy"

[model_providers.codex_proxy]
name = "OpenAI"
base_url = "http://127.0.0.1:3211"
wire_api = "responses"
supports_websockets = true
"#
            .trim_start(),
        );

        let status = codex_switch_status().expect("status should load");

        assert!(status.enabled);
        assert_eq!(status.patch_mode, Some(CodexPatchMode::OfficialRelayBridge));
        assert_eq!(status.supports_websockets, Some(true));
        assert_eq!(status.requires_openai_auth, None);
        assert!(!status.has_switch_state);
    }

    #[test]
    fn codex_switch_status_infers_official_imagegen_bridge_from_empty_auth_facade_without_state() {
        let env = setup_temp_env();
        let cfg_path = env.codex_home.join("config.toml");
        let auth_path = env.codex_home.join("auth.json");
        write_file(
            &cfg_path,
            r#"
model_provider = "codex_proxy"

[model_providers.codex_proxy]
name = "OpenAI"
base_url = "http://127.0.0.1:3211"
wire_api = "responses"
supports_websockets = false
"#
            .trim_start(),
        );
        write_file(&auth_path, "{}");

        let status = codex_switch_status().expect("status should load");

        assert!(status.enabled);
        assert_eq!(
            status.patch_mode,
            Some(CodexPatchMode::OfficialImagegenBridge)
        );
        assert_eq!(status.supports_websockets, Some(false));
        assert_eq!(status.requires_openai_auth, None);
        assert!(!status.has_switch_state);
    }

    #[test]
    fn codex_switch_status_keeps_websocket_as_transport_for_official_imagegen_without_state() {
        let env = setup_temp_env();
        let cfg_path = env.codex_home.join("config.toml");
        let auth_path = env.codex_home.join("auth.json");
        write_file(
            &cfg_path,
            r#"
model_provider = "codex_proxy"

[model_providers.codex_proxy]
name = "OpenAI"
base_url = "http://127.0.0.1:3211"
wire_api = "responses"
supports_websockets = true
"#
            .trim_start(),
        );
        write_file(&auth_path, "{}");

        let status = codex_switch_status().expect("status should load");

        assert!(status.enabled);
        assert_eq!(
            status.patch_mode,
            Some(CodexPatchMode::OfficialImagegenBridge)
        );
        assert_eq!(status.supports_websockets, Some(true));
        assert_eq!(status.requires_openai_auth, None);
        assert!(!status.has_switch_state);
    }

    #[test]
    fn codex_bridge_diagnostics_reports_ready_official_imagegen_bridge() {
        let env = setup_temp_env();
        write_helper_codex_config_with_env_auth(&env);
        let cfg_path = env.codex_home.join("config.toml");
        let auth_path = env.codex_home.join("auth.json");
        write_file(
            &cfg_path,
            r#"
model_provider = "codex_proxy"

[model_providers.codex_proxy]
name = "OpenAI"
base_url = "http://127.0.0.1:3211"
wire_api = "responses"
supports_websockets = false
"#
            .trim_start(),
        );
        write_file(&auth_path, "{}");

        let diagnostics = codex_bridge_diagnostics();

        assert_eq!(
            diagnostics.patch_mode,
            Some(CodexPatchMode::OfficialImagegenBridge)
        );
        assert!(diagnostics.enabled);
        assert!(diagnostics.remote_compaction_v1_ready);
        assert!(diagnostics.imagegen_facade_ready);
        assert!(diagnostics.upstream_auth_ready);
        assert!(!diagnostics.remote_compaction_v2_enabled);
        assert_eq!(diagnostics.worst_status(), CodexBridgeDiagnosticStatus::Ok);
    }

    #[test]
    fn codex_bridge_diagnostics_reports_ready_official_relay_with_responses_websocket() {
        let env = setup_temp_env();
        write_helper_codex_config_with_env_auth(&env);
        let cfg_path = env.codex_home.join("config.toml");
        write_file(
            &cfg_path,
            r#"
model_provider = "codex_proxy"

[model_providers.codex_proxy]
name = "OpenAI"
base_url = "http://127.0.0.1:3211"
wire_api = "responses"
supports_websockets = true
"#
            .trim_start(),
        );

        let diagnostics = codex_bridge_diagnostics();

        assert_eq!(
            diagnostics.patch_mode,
            Some(CodexPatchMode::OfficialRelayBridge)
        );
        assert!(diagnostics.enabled);
        assert!(diagnostics.remote_compaction_v1_ready);
        assert!(!diagnostics.imagegen_facade_ready);
        assert!(diagnostics.upstream_auth_ready);
        let websocket_checks = diagnostics
            .checks
            .iter()
            .filter(|check| check.id == "codex_bridge.responses_websocket")
            .collect::<Vec<_>>();
        assert!(
            websocket_checks
                .iter()
                .any(|check| check.status == CodexBridgeDiagnosticStatus::Ok),
            "expected at least one ready websocket check: {websocket_checks:?}"
        );
        assert_eq!(
            diagnostics.worst_status(),
            CodexBridgeDiagnosticStatus::Info
        );
    }

    #[test]
    fn codex_bridge_diagnostics_warns_when_remote_compaction_v2_is_enabled() {
        let env = setup_temp_env();
        write_helper_codex_config_with_env_auth(&env);
        let cfg_path = env.codex_home.join("config.toml");
        let auth_path = env.codex_home.join("auth.json");
        write_file(
            &cfg_path,
            r#"
model_provider = "codex_proxy"

[features]
remote_compaction_v2 = true

[model_providers.codex_proxy]
name = "OpenAI"
base_url = "http://127.0.0.1:3211"
wire_api = "responses"
supports_websockets = false
"#
            .trim_start(),
        );
        write_file(&auth_path, "{}");

        let diagnostics = codex_bridge_diagnostics();

        assert!(diagnostics.remote_compaction_v2_enabled);
        assert_eq!(
            diagnostics.worst_status(),
            CodexBridgeDiagnosticStatus::Warn
        );
        let v2 = diagnostics
            .checks
            .iter()
            .find(|check| check.id == "codex_bridge.remote_compaction_v2")
            .expect("v2 check");
        assert_eq!(v2.status, CodexBridgeDiagnosticStatus::Warn);
        assert!(v2.message.contains("remote_compaction_v2 is enabled"));
    }

    #[test]
    fn codex_bridge_diagnostics_fails_imagegen_when_auth_facade_is_missing() {
        let env = setup_temp_env();
        write_helper_codex_config_with_env_auth(&env);
        let cfg_path = env.codex_home.join("config.toml");
        write_file(
            &cfg_path,
            r#"
model_provider = "codex_proxy"

[model_providers.codex_proxy]
name = "OpenAI"
base_url = "http://127.0.0.1:3211"
wire_api = "responses"
supports_websockets = false
"#
            .trim_start(),
        );
        let state = CodexSwitchState {
            patch_mode: Some(CodexPatchMode::OfficialImagegenBridge),
            ..CodexSwitchState::from_codex_config_text("", true).expect("state")
        };
        write_codex_switch_state(&state).expect("write state");

        let diagnostics = codex_bridge_diagnostics();

        assert_eq!(
            diagnostics.patch_mode,
            Some(CodexPatchMode::OfficialImagegenBridge)
        );
        assert!(!diagnostics.imagegen_facade_ready);
        let imagegen = diagnostics
            .checks
            .iter()
            .find(|check| check.id == "codex_bridge.imagegen_facade")
            .expect("imagegen check");
        assert_eq!(imagegen.status, CodexBridgeDiagnosticStatus::Fail);
    }

    #[test]
    fn codex_bridge_runtime_auth_snapshot_reports_missing_env_names() {
        let env = setup_temp_env();
        write_helper_codex_config(
            &env,
            r#"
version = 5

[codex.providers.relay]
base_url = "https://relay.example/v1"
auth_token_env = "CODEX_HELPER_MISSING_IMAGEGEN_KEY"

[codex.routing]
entry = "main"

[codex.routing.routes.main]
strategy = "ordered-failover"
children = ["relay"]
"#,
        );

        let snapshot = codex_bridge_runtime_auth_snapshot().expect("snapshot");

        assert_eq!(snapshot.routable_upstreams, 1);
        assert_eq!(snapshot.authed_upstreams, 0);
        assert_eq!(
            snapshot.missing_env,
            vec!["CODEX_HELPER_MISSING_IMAGEGEN_KEY".to_string()]
        );
    }

    #[test]
    fn codex_switch_default_restores_imagegen_bridge_auth_json() {
        let env = setup_temp_env();
        write_helper_codex_config_with_env_auth(&env);
        let cfg_path = env.codex_home.join("config.toml");
        let auth_path = env.codex_home.join("auth.json");
        let original_auth = chatgpt_auth_json("user@example.com", "acct_1", "plus");

        write_file(
            &cfg_path,
            r#"
model_provider = "openai"

[model_providers.openai]
name = "openai"
base_url = "https://api.openai.com/v1"
"#
            .trim_start(),
        );
        write_file(&auth_path, &original_auth);

        switch_on_with_mode(3211, CodexPatchMode::ImagegenBridge)
            .expect("switch_on imagegen bridge should patch auth");
        assert_ne!(read_file(&auth_path), original_auth);

        switch_on_with_mode(3211, CodexPatchMode::Default)
            .expect("switching to default should restore auth");

        assert_eq!(read_file(&auth_path), original_auth);
        let status = codex_switch_status().expect("status should load");
        assert_eq!(status.patch_mode, Some(CodexPatchMode::Default));
    }

    #[test]
    fn codex_switch_default_restores_official_imagegen_bridge_auth_json() {
        let env = setup_temp_env();
        write_helper_codex_config_with_env_auth(&env);
        let cfg_path = env.codex_home.join("config.toml");
        let auth_path = env.codex_home.join("auth.json");
        let original_auth = chatgpt_auth_json("user@example.com", "acct_1", "plus");

        write_file(
            &cfg_path,
            r#"
model_provider = "openai"

[model_providers.openai]
name = "openai"
base_url = "https://api.openai.com/v1"
"#
            .trim_start(),
        );
        write_file(&auth_path, &original_auth);

        switch_on_with_mode(3211, CodexPatchMode::OfficialImagegenBridge)
            .expect("switch_on official imagegen preset should patch auth");
        assert_ne!(read_file(&auth_path), original_auth);

        switch_on_with_mode(3211, CodexPatchMode::Default)
            .expect("switching to default should restore auth");

        assert_eq!(read_file(&auth_path), original_auth);
        let status = codex_switch_status().expect("status should load");
        assert_eq!(status.patch_mode, Some(CodexPatchMode::Default));
    }

    #[test]
    fn codex_switch_default_restores_official_imagegen_bridge_auth_json_with_responses_websocket() {
        let env = setup_temp_env();
        write_helper_codex_config_with_env_auth(&env);
        let cfg_path = env.codex_home.join("config.toml");
        let auth_path = env.codex_home.join("auth.json");
        let original_auth = chatgpt_auth_json("user@example.com", "acct_1", "plus");

        write_file(
            &cfg_path,
            r#"
model_provider = "openai"

[model_providers.openai]
name = "openai"
base_url = "https://api.openai.com/v1"
"#
            .trim_start(),
        );
        write_file(&auth_path, &original_auth);

        switch_on_with_options(
            3211,
            CodexPatchMode::OfficialImagegenBridge,
            CodexSwitchOptions {
                responses_websocket: true,
            },
        )
        .expect("switch_on official imagegen preset should patch auth with websocket transport");
        assert_ne!(read_file(&auth_path), original_auth);

        switch_on_with_mode(3211, CodexPatchMode::Default)
            .expect("switching to default should restore auth");

        assert_eq!(read_file(&auth_path), original_auth);
        let status = codex_switch_status().expect("status should load");
        assert_eq!(status.patch_mode, Some(CodexPatchMode::Default));
    }

    #[test]
    fn codex_switch_off_restores_imagegen_bridge_auth_json() {
        let env = setup_temp_env();
        write_helper_codex_config_with_env_auth(&env);
        let cfg_path = env.codex_home.join("config.toml");
        let auth_path = env.codex_home.join("auth.json");
        let original_auth = chatgpt_auth_json("user@example.com", "acct_1", "plus");

        write_file(
            &cfg_path,
            r#"
model_provider = "openai"

[model_providers.openai]
name = "openai"
base_url = "https://api.openai.com/v1"
"#
            .trim_start(),
        );
        write_file(&auth_path, &original_auth);

        switch_on_with_mode(3211, CodexPatchMode::ImagegenBridge)
            .expect("switch_on imagegen bridge should patch auth");
        switch_off().expect("switch_off should restore auth");

        assert_eq!(read_file(&auth_path), original_auth);
        assert!(read_file(&cfg_path).contains("model_provider = \"openai\""));
    }

    #[test]
    fn codex_switch_off_does_not_restore_auth_if_user_changed_it() {
        let env = setup_temp_env();
        write_helper_codex_config_with_env_auth(&env);
        let cfg_path = env.codex_home.join("config.toml");
        let auth_path = env.codex_home.join("auth.json");
        let user_auth = r#"{"auth_mode":"apikey","OPENAI_API_KEY":"sk-user"}"#;

        write_file(
            &cfg_path,
            r#"
model_provider = "openai"

[model_providers.openai]
name = "openai"
base_url = "https://api.openai.com/v1"
"#
            .trim_start(),
        );
        write_file(
            &auth_path,
            &chatgpt_auth_json("user@example.com", "acct_1", "plus"),
        );

        switch_on_with_mode(3211, CodexPatchMode::ImagegenBridge)
            .expect("switch_on imagegen bridge should patch auth");
        write_file(&auth_path, user_auth);
        switch_off().expect("switch_off should leave user auth alone");

        assert_eq!(read_file(&auth_path), user_auth);
    }

    #[test]
    fn codex_switch_imagegen_to_chatgpt_bridge_uses_original_auth_json() {
        let env = setup_temp_env();
        write_helper_codex_config_with_env_auth(&env);
        let cfg_path = env.codex_home.join("config.toml");
        let auth_path = env.codex_home.join("auth.json");
        let original_auth = chatgpt_auth_json("user@example.com", "acct_1", "plus");

        write_file(
            &cfg_path,
            r#"
model_provider = "openai"

[model_providers.openai]
name = "openai"
base_url = "https://api.openai.com/v1"
"#
            .trim_start(),
        );
        write_file(&auth_path, &original_auth);

        switch_on_with_mode(3211, CodexPatchMode::ImagegenBridge)
            .expect("switch_on imagegen bridge should patch auth");
        switch_on_with_mode(3211, CodexPatchMode::ChatGptBridge)
            .expect("switching to chatgpt bridge should use original auth snapshot");

        let updated_auth: serde_json::Value =
            serde_json::from_str(&read_file(&auth_path)).expect("valid auth json");
        assert_eq!(
            updated_auth
                .get("tokens")
                .and_then(|value| value.get("account_id"))
                .and_then(|value| value.as_str()),
            Some("acct_1")
        );
        assert!(
            updated_auth
                .get("OPENAI_API_KEY")
                .is_some_and(|value| value.is_null())
        );
    }

    #[test]
    fn codex_switch_official_imagegen_to_chatgpt_bridge_uses_original_auth_json() {
        let env = setup_temp_env();
        write_helper_codex_config_with_env_auth(&env);
        let cfg_path = env.codex_home.join("config.toml");
        let auth_path = env.codex_home.join("auth.json");
        let original_auth = chatgpt_auth_json("user@example.com", "acct_1", "plus");

        write_file(
            &cfg_path,
            r#"
model_provider = "openai"

[model_providers.openai]
name = "openai"
base_url = "https://api.openai.com/v1"
"#
            .trim_start(),
        );
        write_file(&auth_path, &original_auth);

        switch_on_with_mode(3211, CodexPatchMode::OfficialImagegenBridge)
            .expect("switch_on official imagegen preset should patch auth");
        switch_on_with_mode(3211, CodexPatchMode::ChatGptBridge)
            .expect("switching to chatgpt bridge should use original auth snapshot");

        let updated_cfg = read_file(&cfg_path);
        assert!(updated_cfg.contains("name = \"codex-helper\""));
        assert!(updated_cfg.contains("requires_openai_auth = true"));

        let updated_auth: serde_json::Value =
            serde_json::from_str(&read_file(&auth_path)).expect("valid auth json");
        assert_eq!(
            updated_auth
                .get("tokens")
                .and_then(|value| value.get("account_id"))
                .and_then(|value| value.as_str()),
            Some("acct_1")
        );
        assert!(
            updated_auth
                .get("OPENAI_API_KEY")
                .is_some_and(|value| value.is_null())
        );
    }

    #[test]
    fn codex_switch_on_chatgpt_bridge_does_not_rewrite_already_patched_auth_json() {
        let env = setup_temp_env();
        let cfg_path = env.codex_home.join("config.toml");
        let auth_path = env.codex_home.join("auth.json");

        write_file(
            &cfg_path,
            r#"
model_provider = "openai"

[model_providers.openai]
name = "openai"
base_url = "https://api.openai.com/v1"
"#
            .trim_start(),
        );
        write_file(
            &auth_path,
            &chatgpt_bridge_auth_json_text(&chatgpt_auth_json(
                "user@example.com",
                "acct_1",
                "plus",
            ))
            .expect("pre-patch auth fixture"),
        );
        let before = std::fs::metadata(&auth_path)
            .expect("auth metadata")
            .modified()
            .expect("auth modified time");

        switch_on_with_mode(3211, CodexPatchMode::ChatGptBridge)
            .expect("switch_on bridge should patch config without rewriting already-patched auth");

        let after = std::fs::metadata(&auth_path)
            .expect("auth metadata")
            .modified()
            .expect("auth modified time");
        assert_eq!(before, after);
    }

    #[test]
    fn codex_switch_on_chatgpt_bridge_refuses_incomplete_auth_without_writing_config() {
        let env = setup_temp_env();
        let cfg_path = env.codex_home.join("config.toml");
        let auth_path = env.codex_home.join("auth.json");
        let state_path = env.codex_home.join("codex-helper-switch-state.json");
        let original_config = r#"
model_provider = "openai"

[model_providers.openai]
name = "openai"
base_url = "https://api.openai.com/v1"
"#
        .trim_start();
        let original_auth = r#"{"auth_mode":"chatgpt","OPENAI_API_KEY":null}"#;

        write_file(&cfg_path, original_config);
        write_file(&auth_path, original_auth);

        let err = switch_on_with_mode(3211, CodexPatchMode::ChatGptBridge)
            .expect_err("incomplete ChatGPT auth should be rejected before writing config");

        assert!(err.to_string().contains("complete ChatGPT login state"));
        assert_eq!(read_file(&cfg_path), original_config);
        assert_eq!(read_file(&auth_path), original_auth);
        assert!(
            !state_path.exists(),
            "failed bridge switch must not create switch state"
        );
    }

    #[test]
    fn codex_switch_on_refuses_local_proxy_without_switch_state() {
        let env = setup_temp_env();
        let cfg_path = env.codex_home.join("config.toml");
        let state_path = env.codex_home.join("codex-helper-switch-state.json");

        write_file(
            &cfg_path,
            r#"
model_provider = "codex_proxy"

[model_providers.codex_proxy]
name = "codex-helper"
base_url = "http://127.0.0.1:3211"
"#
            .trim_start(),
        );

        let err = switch_on(3211).expect_err("switch_on should not snapshot a local proxy");
        assert!(err.to_string().contains("no switch state was found"));
        assert!(
            !state_path.exists(),
            "switch_on must not create state from an already-patched local proxy"
        );
    }

    #[test]
    fn codex_config_text_for_import_hides_proxy_created_from_absent_config() {
        let env = setup_temp_env();
        let cfg_path = env.codex_home.join("config.toml");

        switch_on(3211).expect("switch_on should create config");
        assert!(cfg_path.exists());

        let import_text = codex_config_text_for_import()
            .expect("read import view")
            .expect("config exists");
        assert!(
            import_text.trim().is_empty(),
            "import view should not expose helper proxy as a real upstream"
        );
    }

    #[test]
    fn codex_switch_off_clears_switch_state_and_refreshes_next_snapshot() {
        let env = setup_temp_env();
        let cfg_path = env.codex_home.join("config.toml");
        let state_path = env.codex_home.join("codex-helper-switch-state.json");

        let original = r#"
model_provider = "openai"

[model_providers.openai]
name = "openai"
base_url = "https://api.openai.com/v1"
"#;
        let updated = r#"
model_provider = "packycode"

[model_providers.packycode]
name = "packycode"
base_url = "https://codex-api.packycode.com/v1"
"#;

        write_file(&cfg_path, original.trim_start());
        switch_on(3211).expect("first switch_on should succeed");
        assert!(
            state_path.exists(),
            "switch state should exist while patched"
        );
        let state_text = read_file(&state_path);
        assert!(state_text.contains("\"original_model_provider\": \"openai\""));
        assert!(
            !state_text.contains("api.openai.com"),
            "switch state should not store the full Codex config"
        );

        switch_off().expect("first switch_off should succeed");
        assert_eq!(read_file(&cfg_path), original.trim_start());
        assert!(
            !state_path.exists(),
            "switch state should be removed after patch-off to avoid stale snapshots"
        );

        write_file(&cfg_path, updated.trim_start());
        switch_on(3211).expect("second switch_on should succeed");
        let state_text = read_file(&state_path);
        assert!(state_text.contains("\"original_model_provider\": \"packycode\""));

        switch_off().expect("second switch_off should succeed");
        assert_eq!(read_file(&cfg_path), updated.trim_start());
        assert!(
            !state_path.exists(),
            "switch state should be cleaned up after the second patch-off as well"
        );
    }

    #[test]
    fn codex_switch_off_preserves_codex_runtime_config_edits() {
        let env = setup_temp_env();
        let cfg_path = env.codex_home.join("config.toml");
        let state_path = env.codex_home.join("codex-helper-switch-state.json");

        let original = r#"
model_provider = "openai"

[model_providers.openai]
name = "openai"
base_url = "https://api.openai.com/v1"
"#;

        write_file(&cfg_path, original.trim_start());
        switch_on(3211).expect("switch_on should succeed");

        let mut during_run = read_file(&cfg_path);
        during_run.push_str(
            r#"
[projects."D:\\Projects\\rust\\codex-helper"]
trust_level = "trusted"
"#,
        );
        write_file(&cfg_path, &during_run);

        switch_off().expect("switch_off should patch rather than restore whole file");

        let updated = read_file(&cfg_path);
        assert!(updated.contains("model_provider = \"openai\""));
        assert!(updated.contains("[model_providers.openai]"));
        assert!(!updated.contains("[model_providers.codex_proxy]"));
        assert!(updated.contains("[projects."));
        assert!(updated.contains("trust_level = \"trusted\""));
        assert!(
            !state_path.exists(),
            "switch state should be removed after successful patch-off"
        );
    }

    #[test]
    fn codex_switch_off_keeps_user_provider_change_made_during_run() {
        let env = setup_temp_env();
        let cfg_path = env.codex_home.join("config.toml");

        let original = r#"
model_provider = "openai"

[model_providers.openai]
name = "openai"
base_url = "https://api.openai.com/v1"
"#;
        let user_changed = r#"
model_provider = "packycode"

[model_providers.openai]
name = "openai"
base_url = "https://api.openai.com/v1"

[model_providers.codex_proxy]
name = "codex-helper"
base_url = "http://127.0.0.1:3211"
wire_api = "responses"
request_max_retries = 0

[model_providers.packycode]
name = "packycode"
base_url = "https://codex-api.packycode.com/v1"
"#;

        write_file(&cfg_path, original.trim_start());
        switch_on(3211).expect("switch_on should succeed");
        write_file(&cfg_path, user_changed.trim_start());

        switch_off().expect("switch_off should not undo user's model_provider change");

        let updated = read_file(&cfg_path);
        assert!(updated.contains("model_provider = \"packycode\""));
        assert!(updated.contains("[model_providers.packycode]"));
        assert!(!updated.contains("[model_providers.codex_proxy]"));
    }

    #[test]
    fn codex_switch_off_preserves_new_config_when_original_was_absent() {
        let env = setup_temp_env();
        let cfg_path = env.codex_home.join("config.toml");

        switch_on(3211).expect("switch_on should create config");
        let mut during_run = read_file(&cfg_path);
        during_run.push_str(
            r#"
[projects."D:\\Projects\\rust\\codex-helper"]
trust_level = "trusted"
"#,
        );
        write_file(&cfg_path, &during_run);

        switch_off().expect("switch_off should remove only local proxy fields");

        let updated = read_file(&cfg_path);
        assert!(!updated.contains("model_provider = \"codex_proxy\""));
        assert!(!updated.contains("[model_providers.codex_proxy]"));
        assert!(updated.contains("[projects."));
        assert!(updated.contains("trust_level = \"trusted\""));
    }

    #[test]
    fn codex_switch_off_removes_empty_config_created_by_switch_on() {
        let env = setup_temp_env();
        let cfg_path = env.codex_home.join("config.toml");

        switch_on(3211).expect("switch_on should create config");
        assert!(cfg_path.exists());

        switch_off().expect("switch_off should restore absent config state");

        assert!(
            !cfg_path.exists(),
            "config created only for the local proxy should be removed"
        );
    }

    #[test]
    fn claude_switch_off_clears_backup_and_refreshes_next_snapshot() {
        let env = setup_temp_env();
        let settings_path = env.claude_home.join("settings.json");
        let backup_path = env.claude_home.join("settings.json.codex-helper-backup");

        let original = r#"{
  "env": {
    "ANTHROPIC_BASE_URL": "https://api.anthropic.com/v1",
    "ANTHROPIC_API_KEY": "sk-ant-1"
  }
}"#;
        let updated = r#"{
  "env": {
    "ANTHROPIC_BASE_URL": "https://anthropic-proxy.example/v1",
    "ANTHROPIC_API_KEY": "sk-ant-2"
  }
}"#;

        write_file(&settings_path, original);
        claude_switch_on(3211).expect("first claude_switch_on should succeed");
        assert!(
            backup_path.exists(),
            "backup should exist while switched on"
        );

        claude_switch_off().expect("first claude_switch_off should succeed");
        assert_eq!(read_file(&settings_path), original);
        assert!(
            !backup_path.exists(),
            "backup should be removed after Claude restore to avoid stale snapshots"
        );

        write_file(&settings_path, updated);
        claude_switch_on(3211).expect("second claude_switch_on should succeed");
        assert_eq!(read_file(&backup_path), updated);

        claude_switch_off().expect("second claude_switch_off should succeed");
        assert_eq!(read_file(&settings_path), updated);
        assert!(
            !backup_path.exists(),
            "backup should be cleaned up after the second Claude restore as well"
        );
    }
}

/// Warn before replacing an existing local Claude proxy patch.
pub fn guard_claude_settings_before_switch_on_interactive() -> Result<()> {
    use std::io::{self, Write};

    let settings_path = claude_settings_path();
    if !settings_path.exists() {
        return Ok(());
    }
    let backup_path = claude_settings_backup_path(&settings_path);

    let text = read_settings_text(&settings_path)?;
    if text.trim().is_empty() {
        return Ok(());
    }

    let value: serde_json::Value = match serde_json::from_str(&text) {
        Ok(value) => value,
        Err(_) => return Ok(()),
    };
    let obj = match value.as_object() {
        Some(obj) => obj,
        None => return Ok(()),
    };
    let env_obj = match obj.get("env").and_then(|value| value.as_object()) {
        Some(env_obj) => env_obj,
        None => return Ok(()),
    };

    let base_url = env_obj
        .get("ANTHROPIC_BASE_URL")
        .and_then(|value| value.as_str())
        .unwrap_or_default();

    let is_local = base_url.contains("127.0.0.1") || base_url.contains("localhost");
    if !is_local {
        return Ok(());
    }

    if !backup_path.exists() {
        eprintln!(
            "Warning: Claude settings {:?} points ANTHROPIC_BASE_URL to a local address ({base_url}), but no backup file {:?} was found; please inspect this config file manually if this is unexpected.",
            settings_path, backup_path
        );
        return Ok(());
    }

    let is_tty = atty::is(atty::Stream::Stdin) && atty::is(atty::Stream::Stdout);
    if !is_tty {
        eprintln!(
            "Notice: Claude settings {:?} already points to the local proxy ({base_url}), and backup {:?} exists; run `codex-helper switch off --claude` if you want to restore the original config.",
            settings_path, backup_path
        );
        return Ok(());
    }

    eprintln!(
        "Claude settings {:?} already points ANTHROPIC_BASE_URL to the local proxy ({base_url}), and backup {:?} exists.\nThis usually means the previous run did not switch off cleanly.\nRestore the original Claude settings now? [Y/n] ",
        settings_path, backup_path
    );
    eprint!("> ");
    io::stdout().flush().ok();

    let mut input = String::new();
    if let Err(err) = io::stdin().read_line(&mut input) {
        eprintln!("Failed to read input: {err}");
        return Ok(());
    }
    let answer = input.trim();
    let yes =
        answer.is_empty() || answer.eq_ignore_ascii_case("y") || answer.eq_ignore_ascii_case("yes");

    if yes {
        if let Err(err) = claude_switch_off() {
            eprintln!("Failed to restore Claude settings: {err}");
        } else {
            eprintln!("Restored Claude settings from backup.");
        }
    } else {
        eprintln!("Keeping current Claude settings unchanged.");
    }

    Ok(())
}