fundaia 0.53.0

Command line for the Fundaia deployment platform: projects, services, variables, deployments, logs and metrics
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
mod api;
mod changelog;
mod commands;
mod config;
mod exit;
mod output;
mod render;
mod update;

use anyhow::{Context, Result};
use clap::{Args, CommandFactory, Parser, Subcommand};
use owo_colors::OwoColorize;

use api::client::ApiClient;
use config::Config;
use output::Format;
use render::theme;

#[derive(Parser)]
#[command(
    name = "fundaia",
    version,
    about = "Proyectos, servicios, variables, despliegues, logs y métricas",
    long_about = None,
    propagate_version = true
)]
struct Cli {
    /// Which configured instance to talk to.
    #[arg(long, short, global = true, env = "FUNDAIA_PROFILE")]
    profile: Option<String>,

    /// Override the address, without saving it. Useful in CI.
    #[arg(long, global = true, env = "FUNDAIA_URL")]
    url: Option<String>,

    /// Override the token, without saving it. Useful in CI.
    #[arg(long, global = true, env = "FUNDAIA_TOKEN", hide_env_values = true)]
    token: Option<String>,

    /// Never colour the output, whatever the terminal says.
    #[arg(long, global = true)]
    no_color: bool,

    /// Answer in JSON: one compact value, or one object per line on a stream.
    /// For scripts and AI agents; `FUNDAIA_JSON=1` says the same thing.
    #[arg(long, global = true)]
    json: bool,

    /// Which environment of the project to work in, by name or slug. Every
    /// command that names a project or a service reads and changes that one;
    /// without it, the project's default environment (production).
    #[arg(
        long = "env",
        global = true,
        env = "FUNDAIA_ENV",
        value_name = "ENTORNO"
    )]
    environment: Option<String>,

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

#[derive(Subcommand)]
enum Command {
    /// Authorise this terminal through the browser.
    Login {
        /// The instance to sign in to.
        #[arg(long, default_value = "https://infrastructure.fundaia.com")]
        url: String,

        /// The name to save it under.
        #[arg(long, default_value = "default")]
        as_profile: String,

        /// Print the address instead of opening it.
        #[arg(long)]
        no_browser: bool,
    },

    /// Forget a profile on this machine.
    Logout {
        #[arg(long)]
        profile: Option<String>,
    },

    /// Replace this binary with the newest published release.
    ///
    /// Rarely needed: every command already checks once a day and installs what
    /// it finds. This is the same work without waiting for that, and the way to
    /// see what happened when the automatic one stayed quiet.
    Upgrade {
        /// Only say whether there is a newer one.
        #[arg(long)]
        check: bool,
    },

    /// What each version brought, and which ones this machine has run.
    ///
    /// The file travels inside the binary, so this answers with no instance, no
    /// token and no network. With no arguments it tells what the version you
    /// are running brought — which is the question the self-update leaves
    /// behind when it replaces the binary halfway through an afternoon.
    Changelog {
        /// One version, with or without its `v`. The running one by default.
        ///
        /// Positional, and named `release` in the code, because `--version` is
        /// clap's and `propagate_version` hands it to every subcommand: an
        /// argument called `version` collides with it before the parser is even
        /// built. The word somebody types is still a version.
        #[arg(value_name = "VERSION")]
        release: Option<String>,

        /// Every version, newest first.
        #[arg(long)]
        all: bool,

        /// What was published after a version: everything an upgrade brought.
        #[arg(long)]
        since: Option<String>,

        /// How many to show.
        #[arg(short = 'n', long)]
        count: Option<usize>,

        /// Which versions have run here, and since when.
        ///
        /// A different question from the changelog: that one says what was
        /// published, this says what was on this machine.
        #[arg(long)]
        history: bool,
    },

    /// Who this terminal is signed in as.
    Whoami,

    /// The completion script for a shell, on stdout.
    ///
    /// `fundaia completions zsh > "${fpath[1]}/_fundaia"`, or the bash and
    /// fish equivalents. Generated from the real argument definitions, so it
    /// can never disagree with what the parser accepts.
    Completions { shell: clap_complete::Shell },

    /// Every command, every argument and every exit code, as JSON.
    ///
    /// `completions` for a reader that is not a shell. An agent working out
    /// what it may do here had `--help` on sixty commands — prose, written for
    /// a person — or a guess; this is the parser describing itself, so it
    /// cannot disagree with what the parser accepts. Each command carries what
    /// it does to the platform (`reads`, `writes`, `starts`, `destroys`,
    /// `local`), which is the one thing to know before running it.
    ///
    /// No instance, no token and no network.
    Schema,

    /// What is true about this platform, in one page.
    ///
    /// The orientation under the commands: that creating a service deploys it,
    /// that a connection is a reference and never a copy, what each exit code
    /// means. `schema` is the surface, this is the briefing — the same words
    /// the instance serves at `/agent.md` and hands to an MCP client on
    /// connect.
    ///
    /// Travels inside the binary, so it answers with no instance and no token:
    /// a caller working out what it may do has not signed in yet.
    Guide,

    /// The Claude Code skill for this CLI, generated from its own commands.
    ///
    /// `fundaia skill` prints it; `fundaia skill install` writes it to
    /// `~/.claude/skills/fundaia/SKILL.md` (or `.claude/skills/` in this directory with
    /// `--project`). Run install again after an upgrade to pick up new commands.
    Skill {
        #[command(subcommand)]
        command: Option<SkillCommand>,
    },

    /// Everything, in one screen.
    Status,

    /// Projects on this instance.
    Projects,

    /// Make one, rename one, delete one, or hand one to another space.
    Project {
        #[command(subcommand)]
        command: ProjectCommand,
    },

    /// The environments of a project: production, staging…
    ///
    /// The default one first, each with its services counted. `--env <name>`
    /// on any other command works in one of them.
    Envs { project: String },

    /// Make an environment, rename one, delete one, copy a service or its
    /// data into one, promote one to another, compare two or make one expire.
    Env {
        #[command(subcommand)]
        command: EnvCommand,
    },

    /// The machines this instance deploys onto, and moving environments
    /// between them. `principal` is the one the platform runs on; the rest are
    /// driven through podman over SSH. Owner only.
    Servers {
        #[command(subcommand)]
        command: ServersCommand,
    },

    /// Where a project announces its deployments, crashes and failed workflows:
    /// Slack, Discord or any HTTPS endpoint.
    Webhooks { project: String },

    /// Add a webhook, change one, remove one, or send it a test.
    Webhook {
        #[command(subcommand)]
        command: WebhookCommand,
    },

    /// Services in a project.
    Services { project: String },

    /// One service in detail.
    Service { project: String, service: String },

    /// The picture of a project: where each service sits, and how to move it.
    Canvas {
        #[command(subcommand)]
        command: CanvasCommand,
    },

    /// Create a service.
    New(NewArgs),

    /// What a Claude Code component runs on, and changing it.
    ///
    /// With no option it prints the model, the effort and whether a token is
    /// configured — never the token. Each option changes one thing and only
    /// that; the container restarts to pick it up.
    Agent {
        project: String,
        service: String,

        /// A model from `fundaia templates`.
        #[arg(long)]
        model: Option<String>,

        /// low, medium, high, xhigh or max.
        #[arg(long)]
        effort: Option<String>,

        /// A new token from `claude setup-token`. Replaces the one it has.
        #[arg(long = "setup-token")]
        setup_token: Option<String>,
    },

    /// Rename a service.
    ///
    /// A contract change rather than a label: the expressions that name it and
    /// the internal addresses that call it are rewritten with it, and its public
    /// hostname follows on the next deployment.
    Rename {
        project: String,
        service: String,
        name: String,
    },

    /// The components on offer: databases, storage and Claude Code.
    ///
    /// What it lists is what *this account* may add. An instance offers some
    /// components to its owner only, and they are absent rather than shown and
    /// refused.
    Templates,

    /// Send the code in a directory and deploy it.
    ///
    /// For a service created with `--upload`: there is no repository to read, so
    /// this *is* the push. The directory is packed honouring `.gitignore` and
    /// `.fundaiaignore`, with `.git` and `node_modules` always left out.
    Up {
        project: String,
        service: String,

        /// Which directory to send. Default: the current one.
        #[arg(long, default_value = ".")]
        path: String,

        /// Store the code without deploying it.
        #[arg(long = "no-deploy")]
        no_deploy: bool,

        /// Send it and return, without watching the pipeline.
        #[arg(long)]
        detach: bool,
    },

    /// What has been uploaded to a service, newest first.
    Uploads { project: String, service: String },

    /// Deploy a service, and watch the pipeline.
    Deploy {
        project: String,
        service: String,

        /// Reuse the current image instead of building.
        #[arg(long)]
        restart: bool,

        /// Build every step again, without podman's layer cache: for a
        /// dependency that moved under the same lockfile. Only for a service
        /// built from code.
        #[arg(long = "no-cache", conflicts_with = "restart")]
        no_cache: bool,

        /// Start it and return, without watching.
        #[arg(long)]
        detach: bool,
    },

    /// Build one deployment's own commit again, with today's variables.
    ///
    /// Between `deploy`, which reads the branch and ships whatever landed on it
    /// since, and `rollback`, which reuses the image and never builds.
    Redeploy {
        project: String,
        service: String,
        /// The number shown by `history`.
        number: u32,
    },

    /// Put a previous deployment back, by its number.
    Rollback {
        project: String,
        service: String,
        /// The number shown by `history`.
        number: u32,
    },

    /// Stop a deployment that has not finished.
    ///
    /// The one in flight, unless `--deployment` names another. Whatever was
    /// serving before it keeps serving; a deployment that already went live
    /// cannot be cancelled, and `rollback` is the verb for that.
    Cancel {
        project: String,
        service: String,

        /// Which deployment, by the number `history` shows. The one in flight
        /// by default.
        #[arg(long)]
        deployment: Option<u32>,
    },

    /// Put a service to sleep. The next request wakes it.
    Stop { project: String, service: String },

    /// Deploy, restart, sleep or wake several services at once, or all of an
    /// environment.
    ///
    /// Without service names, every service of the environment (`--env`, or
    /// the default one). Deploying goes providers first, through the same
    /// checks as one deployment; each refusal comes back with its reason and
    /// never stops the rest. It does not wait: `history` follows each one.
    Bulk {
        /// What to do to each of them.
        #[arg(value_parser = ["deploy", "restart", "sleep", "wake"])]
        action: String,

        project: String,

        /// The services, by name, slug or id. All of them when omitted.
        services: Vec<String>,
    },

    /// Secret URLs that deploy a service from outside: a CI job, a CMS, a cron.
    Hooks {
        #[command(subcommand)]
        command: HookCommand,
    },

    /// The deployments of a service, newest first.
    History {
        project: String,
        service: String,

        #[arg(long, default_value_t = 15)]
        limit: usize,

        /// Only the deployments of one commit: the build, a retry, a rollback
        /// back to it. A hash, or its first seven characters.
        #[arg(long)]
        commit: Option<String>,
    },

    /// The code one commit changed, file by file.
    ///
    /// Without a hash, the commit the newest deployment shipped — which is what
    /// answers "what went out". `--stat` stops before the patches when the list
    /// of files is all you wanted, and `--file` prints one of them.
    #[command(alias = "show")]
    Commit {
        project: String,
        service: String,

        /// The commit hash, abbreviated or whole.
        commit: Option<String>,

        /// One file, by the path the list reports.
        #[arg(long)]
        file: Option<String>,

        /// The list of files and nothing else.
        #[arg(long)]
        stat: bool,
    },

    /// What has been done in a project, newest first.
    ///
    /// Deployments, variables, domains and who read which logs — manual and
    /// through this tool alike, because both go through the same services.
    Activity {
        project: String,

        #[arg(long, default_value_t = 30)]
        limit: usize,
    },

    /// Who has been getting into your account, and from where.
    ///
    /// The failed attempts are in the list on purpose: a successful sign-in
    /// nobody recognises is normally preceded by attempts nobody recognises.
    /// Always your own account — the token decides whose, and there is nowhere
    /// else to point it.
    #[command(alias = "logins")]
    SignIns {
        #[arg(long, short = 'n', default_value_t = 50)]
        limit: usize,
    },

    /// The sessions open right now, and closing one.
    ///
    /// A different question from `sign-ins`, which is history: this is the
    /// present tense, and the only one of the two with anything to press.
    Sessions {
        #[command(subcommand)]
        command: Option<SessionCommand>,
    },

    /// Follow what the platform is doing, live.
    ///
    /// The terminal half of the notices the web interface shows: a deployment
    /// somebody else started, a push that deployed on its own, a variable that
    /// changed under you. With no arguments it is everything this account can
    /// reach; name a project — or a project and a service — to narrow it.
    Watch {
        project: Option<String>,
        service: Option<String>,
    },

    /// A service's log.
    Logs(LogsArgs),

    /// Everything that is not fine, across every project you reach, worst first.
    ///
    /// Each item says what to call next, arguments filled in.
    #[command(alias = "inbox")]
    Attention,

    /// One verdict for a project, and one line per service.
    Health { project: String },

    /// What is wrong with one service, and what to run next.
    Diagnose { project: String, service: String },

    /// Log lines containing a text, in any service of a project, newest first.
    ///
    /// For an error message whose service you do not know. A sibling of `logs`
    /// rather than a subcommand of it: `logs <project> <service>` is positional.
    Grep(GrepArgs),

    /// What a service reads from, what reads from it, and what to redeploy after it changes.
    #[command(alias = "dependencies")]
    Deps { project: String, service: String },

    /// The whole project as one JSON manifest. Secrets are named, never valued.
    Export {
        project: String,

        /// Write it to a file instead of standard output.
        #[arg(long = "output", short = 'o', value_name = "FILE")]
        file: Option<String>,
    },

    /// A project made from a manifest `export` wrote, here or on another
    /// instance, or from a docker-compose.yml. Secrets and unresolved variables
    /// come back empty and are listed with the command that sets each; nothing
    /// deploys unless `--deploy`.
    ///
    /// A `.yml` or `.yaml` file is read as a docker-compose: one service per
    /// compose service, its image or, with `--repo`, its build directory; its
    /// variables, first port, named volumes, command and memory. `--project`
    /// adds them to a project that exists, in `--env`.
    Import(ImportArgs),

    /// Ready-made stacks of several services, made in one go: WordPress, Ghost,
    /// Metabase, Umami, n8n, Directus, Plausible, Gitea, Uptime Kuma, Listmonk…
    Stack {
        #[command(subcommand)]
        command: StackCommand,
    },

    /// A second service made from one that exists, in the same environment:
    /// same source, settings and variables (secrets encrypted again,
    /// references kept), new empty volumes at the same paths and no hostname.
    /// It deploys unless `--no-deploy`.
    Duplicate {
        project: String,
        service: String,

        /// What the copy is called.
        name: String,

        /// Make the copy without deploying it.
        #[arg(long = "no-deploy")]
        no_deploy: bool,
    },

    /// Two deployments of a service side by side: code, variables, configuration.
    ///
    /// Without numbers, the newest against the one before it.
    Compare {
        project: String,
        service: String,
        /// The older one, by the number `history` shows.
        from: Option<u32>,
        /// The newer one. The newest by default.
        to: Option<u32>,
    },

    /// A GET to the service's own container: status, latency, content type, body.
    ///
    /// Never wakes a sleeping service and never leaves the machine.
    Probe {
        project: String,
        service: String,
        /// Path and query.
        #[arg(default_value = "/")]
        path: String,
    },

    /// Start a sleeping or crashed service now, and wait for its health check.
    Wake { project: String, service: String },

    /// Dependency audits by Claude Code, and the pull request that fixes them.
    Security {
        #[command(subcommand)]
        command: SecurityCommand,
    },

    /// Open a GitHub issue about an incident, a failed deployment or a security scan.
    ///
    /// Asking twice about the same thing answers the first issue.
    Issue {
        #[arg(value_parser = ["incident", "deployment", "security-scan"])]
        kind: String,
        /// The incident, deployment or scan id.
        id: String,
    },

    /// The pipelines of a project: `.fundaia/workflows/*.yml`, run here.
    ///
    /// GitHub Actions' file format without GitHub Actions: a push, a schedule
    /// or `workflows run` makes a run, each job is one container of the image
    /// it names, and the log is read back per step.
    Workflows {
        #[command(subcommand)]
        command: WorkflowCommand,
    },

    /// What a service keeps getting wrong, folded and counted.
    Incidents {
        project: String,
        service: String,

        /// Include the ones already resolved or ignored.
        #[arg(long)]
        decided: bool,
    },

    /// Commits waiting for somebody to say they may deploy.
    ///
    /// A push from outside the workspace is held rather than deployed, the way
    /// Railway holds one from outside the team. Whoever pushed is not a member
    /// here — or GitHub matched no account to their commit at all, which is
    /// almost always a `git config user.email` nobody added to their account.
    Approvals {
        project: String,

        /// One service. Omit for everything waiting in the project.
        service: Option<String>,
    },

    /// Approve a held commit and deploy it.
    Approve {
        /// The id `approvals` prints.
        id: String,
    },

    /// Refuse a held commit. It is never offered again.
    Reject {
        /// The id `approvals` prints.
        id: String,
    },

    /// Ask the platform to fix an incident now, or a failed deployment.
    ///
    /// `fix <id>` for an incident; `fix deployment <project> <service> [N]` for
    /// a deployment.
    #[command(args_conflicts_with_subcommands = true, subcommand_negates_reqs = true)]
    Fix {
        /// The id `incidents` prints.
        #[arg(required = true)]
        id: Option<String>,

        #[command(subcommand)]
        command: Option<FixCommand>,
    },

    /// Record what you concluded about an incident.
    Incident {
        /// The id `incidents` prints.
        id: String,

        /// `resolved` if it is fixed, `ignored` to stop hearing about it, or
        /// `open` to put it back in play.
        #[arg(value_parser = ["resolved", "ignored", "open"])]
        status: String,
    },

    /// What the platform has tried to fix on its own, and how it is configured.
    Autofix(AutofixArgs),

    /// CPU and memory, now and over a window.
    Metrics {
        project: String,
        service: String,

        #[arg(long, default_value_t = 60)]
        minutes: u32,
    },

    /// Tokens and dollars an agent component has spent.
    #[command(alias = "usage")]
    Consumption {
        project: String,
        service: String,

        /// The window: 24h, 7d, 30d or 90d.
        #[arg(long, default_value = "7d")]
        range: String,
    },

    /// Every prompt an agent has been asked, and what it is doing now.
    ///
    /// `prompts` is the alias because that is what somebody types when they
    /// want this and `activity` is already the project history.
    #[command(name = "agent-activity", alias = "prompts")]
    AgentActivity {
        project: String,
        service: String,

        /// The window: 24h, 7d, 30d or 90d.
        #[arg(long, default_value = "24h")]
        range: String,

        /// Narrows the list: answered, failed or rejected. The counts do not move.
        #[arg(long)]
        outcome: Option<String>,
    },

    /// A service's environment variables.
    #[command(alias = "vars")]
    Variables {
        #[command(subcommand)]
        command: VariableCommand,
    },

    /// Variables written once that every service of a project receives. A
    /// service's own key of the same name wins; `--env` picks the environment.
    Shared {
        #[command(subcommand)]
        command: SharedCommand,
    },

    /// The rows inside a database component: its tables, a query, a change.
    ///
    /// PostgreSQL, MySQL, SQLite and ClickHouse components take SQL; MongoDB
    /// takes a JSON command document (`{"find": "users", "filter": {…}}`). `query` is
    /// read-only and the database itself refuses any write; `run` is the one
    /// path that writes, and `--preview` runs the statement and undoes it so
    /// the count says what a real run would touch, or says the engine cannot.
    #[command(alias = "sql")]
    Data {
        #[command(subcommand)]
        command: DataCommand,
    },

    /// Read access to a service's repository, when its owner is somebody else.
    ///
    /// A private repository belonging to another account is invisible to this
    /// platform until that account grants it, and GitHub reports the refusal as a
    /// 403 about *write* access on a command that asked to read. Only the owner
    /// can grant it, so `access request` emails them a link that does it — and the
    /// service redeploys itself the moment the permission lands.
    Access {
        #[command(subcommand)]
        command: AccessCommand,
    },

    /// Copies of a service's volume, and putting one back.
    #[command(alias = "backup")]
    Backups {
        #[command(subcommand)]
        command: BackupCommand,
    },

    /// Hostnames a service answers on.
    Domains {
        #[command(subcommand)]
        command: DomainCommand,
    },

    /// Wire one service to another.
    Connect {
        project: String,
        /// The service that will read the variables.
        service: String,
        /// The service it should be able to reach.
        provider: String,
    },

    /// Undo a connection: the consumer stops reading the provider's variables.
    Disconnect {
        project: String,
        /// The service that was reading the variables.
        service: String,
        /// The one it was reading them from.
        provider: String,
    },

    /// What a service could be connected to.
    Connectable { project: String, service: String },

    /// Directories that outlive the container.
    Volumes {
        #[command(subcommand)]
        command: VolumeCommand,
    },

    /// The Containerfile a service builds with.
    Recipe {
        #[command(subcommand)]
        command: RecipeCommand,
    },

    /// The routes a load balancer or an API gateway serves.
    Config {
        #[command(subcommand)]
        command: ConfigCommand,
    },

    /// What a service turned out to offer: framework, port, endpoints.
    #[command(alias = "offers")]
    Capabilities { project: String, service: String },

    /// The shared spaces this account belongs to.
    #[command(alias = "workspaces")]
    Workspace {
        #[command(subcommand)]
        command: WorkspaceCommand,
    },

    /// How much of the machine is left.
    Capacity,

    /// Change a service's settings. Only what you pass is touched.
    Settings(SettingsArgs),

    /// Publish a service on the internet, or take it off.
    ///
    /// Every service is always reachable inside its project by name; this is
    /// only about the hostname on top. A database behind an API wants none.
    Expose {
        project: String,
        service: String,

        /// Take it off the internet. Its domains are removed.
        #[arg(long)]
        off: bool,
    },

    /// Deployments across every project you can reach: what is in flight now
    /// and what finished in the last 24 hours, newest first.
    ///
    /// Each row is one deployment: project and service, its status, the six
    /// stages, why it ran, who, the commit and how long it took. `--active`
    /// keeps what is queued, building or deploying; `--failed` what failed or
    /// crashed. `fundaia cancel <project> <service>` stops one in flight.
    Deployments {
        /// Only what is queued, building or deploying.
        #[arg(long, conflicts_with = "failed")]
        active: bool,

        /// Only what failed or crashed in the last 24 hours.
        #[arg(long)]
        failed: bool,

        #[arg(long, default_value_t = 50)]
        limit: usize,
    },

    /// A public status page for a project: each service operational, degraded
    /// or down, and its uptime over 30 days, at an unguessable address anyone
    /// can open without signing in.
    ///
    /// `on` publishes it and `off` withdraws it; nothing prints where it stands
    /// and what a visitor sees. Only the names of the services chosen appear.
    StatusPage(StatusPageArgs),

    /// Preview environments: each pull request opened on a repository the
    /// project builds gets `pr-<number>`, deleted when it closes. `on` or
    /// `off` turns them on or off; nothing prints where they stand.
    Previews {
        project: String,

        #[arg(value_parser = ["on", "off"])]
        switch: Option<String>,
    },

    /// Commands a service runs on a schedule (cron, UTC) in its running
    /// container, and how each run went.
    Tasks {
        #[command(subcommand)]
        command: TasksCommand,
    },

    /// The files in a service's volumes, read from its running container.
    Files {
        #[command(subcommand)]
        command: FilesCommand,
    },

    /// Ask the registry for a newer image behind a service's tag now, and
    /// deploy it if there is one. For a registry image or a catalogue component.
    Pull { project: String, service: String },

    /// Run one command in a service's running container and print what it
    /// printed. `fundaia exec tienda api -- ls -la /app`. Secrets come back
    /// masked; 60 seconds at most.
    Exec {
        project: String,
        service: String,

        /// The command, after `--` so its own flags are not read as ours.
        #[arg(trailing_var_arg = true, allow_hyphen_values = true, required = true)]
        command: Vec<String>,
    },

    /// Show visitors a maintenance page instead of the service, which keeps
    /// running. Nothing restarts; `--off` serves it again.
    Maintenance {
        project: String,
        service: String,

        /// Serve the service again.
        #[arg(long)]
        off: bool,

        /// What visitors read, up to 500 characters.
        #[arg(long)]
        message: Option<String>,
    },

    /// Ask every visitor for a username and password before anything reaches
    /// the service. The service never sees the credential.
    Protect {
        project: String,
        service: String,

        /// The username visitors type.
        #[arg(long)]
        user: String,

        /// 8 to 72 characters. Asked at the keyboard, or read from a pipe,
        /// when not given here.
        #[arg(long, env = "FUNDAIA_SERVICE_PASSWORD", hide_env_values = true)]
        password: Option<String>,
    },

    /// Remove the password: anybody with the address reaches it again.
    Unprotect { project: String, service: String },

    /// The last requests the gateway answered for a public service: when,
    /// method, path (the query's names, never its values), status, time, the
    /// client's address, and whether the gateway itself refused it. The last
    /// 500 are kept in memory; `-f` follows them as they arrive.
    Requests(RequestsArgs),

    /// Let only these IP addresses or networks reach a public service; the
    /// rest get a 403 from the gateway, before anything wakes. The list
    /// becomes exactly these unless `--add`.
    Allow(AllowArgs),

    /// At most this many requests per minute from each client address to a
    /// public service (`600/min`); the rest get a 429 with Retry-After.
    /// `off` removes the limit.
    Ratelimit {
        project: String,
        service: String,

        /// Requests per minute from each address, 1 to 100000, or off.
        rate: String,
    },

    /// Encryption at rest for a storage service's buckets.
    Encrypt {
        project: String,
        service: String,

        /// Turn it off instead. What is already encrypted stays encrypted.
        #[arg(long)]
        off: bool,
    },

    /// Remove a service and everything under it, in every environment.
    ///
    /// The name belongs to the project, so the deletion does too. To be rid of
    /// one environment's copy only, `env rm` that environment.
    Delete {
        project: String,
        service: String,

        /// The service's own name, typed back.
        #[arg(long)]
        confirm: Option<String>,
    },
}

#[derive(Subcommand)]
enum SkillCommand {
    /// Print the skill.
    Show,
    /// Write it where Claude Code finds it.
    Install {
        /// Into `.claude/skills/` of the current directory instead of your home.
        #[arg(long)]
        project: bool,
    },
    /// Where `install` would write it.
    Path {
        #[arg(long)]
        project: bool,
    },
}
#[derive(Subcommand)]
enum WorkspaceCommand {
    /// The spaces you are in.
    List,

    /// Who shares a space, and who has been invited to.
    #[command(alias = "who")]
    Members { workspace: Option<String> },

    /// The prepaid credit the agents of a space run on.
    #[command(alias = "saldo")]
    Credits { workspace: Option<String> },

    /// Invite somebody by email.
    Invite {
        email: String,

        #[arg(long)]
        workspace: Option<String>,

        /// Let them invite others too.
        #[arg(long)]
        admin: bool,
    },

    /// Withdraw an invitation that has not been accepted.
    Revoke {
        /// The id shown by `members`.
        invitation_id: String,

        #[arg(long)]
        workspace: Option<String>,
    },

    /// Remove somebody from the space.
    Remove {
        /// The user id shown by `members`.
        user_id: String,

        #[arg(long)]
        workspace: Option<String>,
    },

    /// Require a second factor of every member (`on`) or stop (`off`).
    ///
    /// Members without a passkey or a TOTP reach none of the space's projects
    /// until they add one; `members` shows who has one. Admins only.
    #[command(name = "2fa")]
    SecondFactor {
        #[arg(value_parser = ["on", "off"])]
        switch: String,

        #[arg(long)]
        workspace: Option<String>,
    },
}

#[derive(Subcommand)]
enum ProjectCommand {
    /// Create one.
    New {
        name: String,

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

        /// Which shared space it belongs to. Yours, if you say nothing.
        #[arg(long)]
        workspace: Option<String>,
    },

    /// Change its name, its description, or both.
    Rename {
        project: String,
        /// The new name. Leave it out to only change the description.
        name: Option<String>,

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

    /// Delete it, with everything under it. There is no archive.
    Delete {
        project: String,

        /// The project's own name, typed back.
        #[arg(long)]
        confirm: Option<String>,
    },

    /// Hand it to another shared space, which is the whole of sharing it.
    Move { project: String, workspace: String },

    /// Star it: it comes first in your lists, and only in yours.
    Star { project: String },

    /// Take the star away.
    Unstar { project: String },
}

#[derive(Subcommand)]
enum HookCommand {
    /// The deploy hooks of a service: name, a hint of the token, last call.
    List { project: String, service: String },

    /// Make one, and print its URL once.
    ///
    /// The URL is the credential: a `POST` to it deploys the service, with
    /// no account and no token. Keep it where you keep your CI secrets.
    Add {
        project: String,
        service: String,
        /// Who will call it, to recognise it later: `GitHub Actions`, `CMS`…
        name: String,
    },

    /// Revoke one: its URL answers 404 from then on.
    Rm {
        project: String,
        service: String,
        /// Its name or id, as `hooks list` shows it.
        hook: String,
    },
}

#[derive(Subcommand)]
enum WebhookCommand {
    /// Post a project's events to a URL.
    ///
    /// Slack and Discord are recognised from the URL; any other address gets
    /// JSON signed with HMAC-SHA256 in `X-Fundaia-Signature`, and the secret is
    /// printed once. Every event unless `--events` narrows it.
    Add {
        project: String,
        url: String,

        /// What to call it. Slack, Discord or the host, unless said.
        #[arg(long)]
        name: Option<String>,

        /// slack, discord or json. Guessed from the URL, unless said.
        #[arg(long)]
        format: Option<String>,

        /// Which events, comma-separated: deployment-succeeded,
        /// deployment-failed, service-crashed, service-recovered,
        /// workflow-failed, task-failed.
        #[arg(long, value_delimiter = ',')]
        events: Vec<String>,
    },

    /// Rename it, change its events, or pause and resume it.
    Set {
        project: String,
        webhook: String,

        #[arg(long)]
        name: Option<String>,

        /// The events it announces from now on, comma-separated.
        #[arg(long, value_delimiter = ',')]
        events: Option<Vec<String>>,

        /// Stop posting without forgetting it.
        #[arg(long, conflicts_with = "resume")]
        pause: bool,

        #[arg(long)]
        resume: bool,
    },

    /// Stop posting to it and forget its URL and secret.
    Rm { project: String, webhook: String },

    /// Send a sample message now and say whether it arrived.
    Test { project: String, webhook: String },
}

#[derive(Subcommand)]
enum ServersCommand {
    /// Every server with its state, free memory, CPUs, environments and
    /// containers, plus the moves still running.
    List,

    /// One server: what it measured last and the environments it holds.
    Show { server: String },

    /// Add a machine to deploy onto. It needs rootless podman with
    /// `systemctl --user enable --now podman.socket`, lingering for that user
    /// and this machine's SSH key authorised. The connection is tried first.
    Add(ServerAddArgs),

    /// Stop placing new environments on a server. What runs there stays.
    Cordon { server: String },

    /// Let a cordoned or drained server take new environments again.
    Uncordon { server: String },

    /// Automatic failover: when the server has not answered for five
    /// minutes, its environments without volumes are redeployed on another.
    Failover {
        server: String,

        #[arg(value_parser = ["on", "off"])]
        switch: String,
    },

    /// Move every environment off a server, one at a time, to whichever other
    /// server has the most free memory, and cordon it.
    Drain {
        server: String,

        /// Only say what would move and where.
        #[arg(long = "dry-run")]
        dry_run: bool,
    },

    /// Forget a server. Refused while it still holds an environment.
    Rm {
        server: String,

        /// The server's name, typed back.
        #[arg(long)]
        confirm: Option<String>,
    },
}

#[derive(Args)]
struct ServerAddArgs {
    /// A short name: lowercase letters, digits and hyphens.
    name: String,

    /// ssh://user@host[:port]/run/user/<uid>/podman/podman.sock
    #[arg(long)]
    connection: String,

    /// The server's private address (LAN, WireGuard, Tailscale) that this
    /// machine reaches it on. Containers publish their ports there.
    #[arg(long)]
    address: String,

    /// Path on the platform's machine to the SSH private key, when not the
    /// default one.
    #[arg(long)]
    identity: Option<String>,

    /// A label for where it is.
    #[arg(long)]
    region: Option<String>,
}

#[derive(Subcommand)]
enum EnvCommand {
    /// Create one, as a copy of another environment or empty.
    ///
    /// A copy carries every service with its settings, its source, its
    /// variables (secrets encrypted again, references pointed at the copies,
    /// databases with new passwords) and volumes at the same paths — never the
    /// data in them, and no hostname: a public service gets a new one with the
    /// environment in it. The copies deploy, providers first.
    New {
        project: String,
        name: String,

        /// The environment to copy. The default one, unless said.
        #[arg(long, conflicts_with = "empty")]
        from: Option<String>,

        /// Create it with nothing in it.
        #[arg(long)]
        empty: bool,

        /// Copy the services without deploying them.
        #[arg(long = "no-deploy")]
        no_deploy: bool,

        /// Delete it on its own after this long: 48h, 7d, 2w (an hour to a
        /// year). It never expires unless said.
        #[arg(long)]
        ttl: Option<String>,
    },

    /// Change its name. Its slug, and every address in it, stays.
    Rename {
        project: String,
        environment: String,
        name: String,
    },

    /// Delete it, with everything in it: services, containers, volumes and
    /// their data, backups and hostnames. The default one cannot be deleted.
    Rm {
        project: String,
        environment: String,

        /// The environment's name or slug, typed back.
        #[arg(long)]
        confirm: Option<String>,
    },

    /// Which server an environment runs on, and how its last move went.
    Server {
        project: String,
        environment: String,
    },

    /// Move an environment to another server: services with data stop and
    /// their volumes are copied, then everything is redeployed there from the
    /// same commit or image, and the old containers drain and stop.
    Move {
        project: String,
        environment: String,

        /// The server to move it to.
        #[arg(long)]
        to: String,

        /// Wait until the move finishes.
        #[arg(long)]
        wait: bool,
    },

    /// Make it delete itself, with everything in it, after a while.
    ///
    /// Counted from now: 48h, 7d, 2w (an hour to a year), or `never` to
    /// take the expiry away. The default environment never expires.
    Expire {
        project: String,
        environment: String,

        /// How long it lives from now, or `never`.
        ttl: String,
    },

    /// Deploy in one environment the images another one runs, building
    /// nothing.
    ///
    /// Every service present in both (or the ones named) starts exactly the
    /// image the origin serves today, providers first. Variables do not
    /// travel: each environment keeps its own. A service with no live
    /// deployment in the origin, or one already running that image, is left
    /// alone and says why. `--dry-run` shows what would change.
    Promote(PromoteArgs),

    /// Replace the data of one environment's volumes with another's.
    ///
    /// Volume by volume, at the same mount path: the target's volumes are
    /// backed up first, its service is stopped while its data is written and
    /// started again after. The origin keeps running. The target's name,
    /// typed back with `--confirm`, is required (its exact name for the
    /// default environment).
    CopyData(CopyDataArgs),

    /// Compare the variables of two environments, service by service.
    ///
    /// Keys only in one, keys whose values differ and how many match. A
    /// secret is compared by a fingerprint and never shown.
    Diff {
        project: String,
        from: String,
        to: String,
    },

    /// Copy one service into an environment that does not have it yet.
    Copy {
        project: String,
        service: String,

        /// Where it is copied from. `--env`, or the default one, unless said.
        #[arg(long)]
        from: Option<String>,

        /// Where it is copied to.
        #[arg(long)]
        to: String,

        /// Copy it without deploying it.
        #[arg(long = "no-deploy")]
        no_deploy: bool,
    },
}

#[derive(Args)]
struct PromoteArgs {
    project: String,

    /// The environment whose images are promoted, such as staging.
    from: String,

    /// The environment that receives them, such as production.
    to: String,

    /// Only these services, by name. Every one in both, unless said.
    services: Vec<String>,

    /// Show what would change, from which commit to which, and change
    /// nothing.
    #[arg(long = "dry-run")]
    dry_run: bool,
}

#[derive(Args)]
struct CopyDataArgs {
    project: String,

    /// The environment whose data is copied.
    from: String,

    /// The environment whose data is replaced.
    to: String,

    /// Only these services, by name. Every one with a volume, unless said.
    services: Vec<String>,

    /// The target environment's name or slug, typed back.
    #[arg(long)]
    confirm: Option<String>,

    /// Show what would be copied, and copy nothing.
    #[arg(long = "dry-run")]
    dry_run: bool,
}

#[derive(Subcommand)]
enum CanvasCommand {
    /// Where every service sits, with its coordinates.
    ///
    /// The coordinates are what `move` takes back, so this is the command to
    /// run before arranging anything by hand.
    Show {
        project: String,

        /// Draw it as well as list it.
        #[arg(long)]
        map: bool,
    },

    /// Put one service somewhere, in canvas units.
    ///
    /// x runs to the right and y downwards, the first column sits at 80, and a
    /// node is 208 wide by 76 tall — so 300 apart horizontally and 130
    /// vertically is what the automatic arrangements leave between two of them.
    /// Positions are snapped to the same 8-unit grid a drag snaps to.
    Move {
        project: String,
        service: String,

        #[arg(long, allow_negative_numbers = true)]
        x: i64,

        #[arg(long, allow_negative_numbers = true)]
        y: i64,
    },

    /// Lay the whole project out again, overwriting every position in it.
    ///
    /// `layered` reads the arrows and puts what a service depends on to its
    /// left, which is how the picture is meant to be read. `grid` ignores them
    /// and lines everything up in creation order, for a canvas that has been
    /// dragged into a heap.
    Arrange {
        project: String,

        #[arg(long, default_value = "layered", value_parser = ["layered", "grid"])]
        layout: String,
    },
}

#[derive(Subcommand)]
enum FixCommand {
    /// A failed deployment: Claude Code reads its log, fixes it and opens a pull request.
    Deployment {
        project: String,
        service: String,
        /// The number `history` shows. The newest by default.
        number: Option<u32>,
    },
}

#[derive(Subcommand)]
enum SecurityCommand {
    /// Audit a service's dependencies. Answers at once unless `--wait`.
    Scan {
        project: String,
        service: String,

        /// Also upgrade to the smallest safe versions and open a pull request.
        #[arg(long)]
        fix: bool,

        /// Stay until the scan ends.
        #[arg(long)]
        wait: bool,
    },

    /// One scan, by the id `scan` or `list` prints.
    Show { scan_id: String },

    /// The recent scans of a service.
    List { project: String, service: String },
}

#[derive(Subcommand)]
enum WorkflowCommand {
    /// The workflow files found in the project's repositories, per branch.
    List {
        project: String,
        /// Look at every branch again first. Slow: one fetch per repository.
        #[arg(long)]
        refresh: bool,
    },

    /// Recent runs, newest first.
    Runs {
        project: String,
        /// Only the runs of one file, e.g. `.fundaia/workflows/ci.yml`.
        #[arg(long)]
        path: Option<String>,
        /// Only the runs of one commit. A short sha works.
        #[arg(long)]
        commit: Option<String>,
        /// How many, 30 by default.
        #[arg(long, default_value_t = 30)]
        limit: u32,
    },

    /// Start a workflow by hand at the current head of its branch, and return at once.
    Run {
        project: String,
        /// The workflow file, as `list` shows it.
        path: String,
        /// Which branch, when the file exists on several the project follows.
        #[arg(long)]
        branch: Option<String>,
        /// A `workflow_dispatch` input, as NAME=value. Repeat for several.
        #[arg(long = "input")]
        inputs: Vec<String>,
    },

    /// One run with its jobs, by the id `runs` shows.
    Show { run_id: String },

    /// What one job printed, by the id `show` shows.
    Logs { job_id: String },

    /// Stop a run that is queued or running.
    Cancel { run_id: String },

    /// The same commit, file and inputs again, as a new run.
    Rerun { run_id: String },

    /// Per workflow: runs, success rate, durations, failing streak and flakiness.
    Stats {
        project: String,
        /// How many recent runs to read.
        #[arg(long, default_value_t = 100)]
        limit: u32,
    },

    /// Wait for a run to end. Non-zero when it did not succeed.
    Wait {
        run_id: String,
        /// Give up after this many seconds.
        #[arg(long, value_name = "SECS", default_value_t = 600)]
        timeout: u64,
    },

    /// Download the artifact archive a job kept, as a .tar.gz.
    Artifact {
        job_id: String,
        /// Where to write it; `<job id>.tar.gz` in this directory by default.
        #[arg(long)]
        into: Option<String>,
    },
}

#[derive(Subcommand)]
enum VolumeCommand {
    List {
        project: String,
        service: String,
    },

    /// Attach one. Nothing is deployed: it is inside the container from the
    /// next deployment on.
    Add {
        project: String,
        service: String,
        /// Where it is mounted, as an absolute path: `/data`.
        mount_path: String,
    },

    /// Change how much disk it may hold, by the id `list` shows.
    ///
    /// Nothing is deployed: the size is what the plan reserves, not a mount
    /// option. It is refused when the plan has no room left and when the volume
    /// already holds more than the new size.
    Resize {
        volume_id: String,
        /// The new size in whole gigabytes.
        #[arg(long)]
        gb: u64,
    },

    /// Take one off, by the id `list` shows.
    Remove {
        volume_id: String,
    },
}

#[derive(Subcommand)]
enum RecipeCommand {
    /// Print it, with what generated it.
    Show {
        project: String,
        service: String,

        /// Only the Containerfile, so it can be redirected into one.
        #[arg(long)]
        plain: bool,
    },

    /// Replace it. From then on it is never regenerated.
    Edit {
        project: String,
        service: String,

        /// The file to send, or `-` for standard input.
        #[arg(long, default_value = "-")]
        file: String,
    },
}

#[derive(Subcommand)]
enum ConfigCommand {
    /// Print it, with where the container reads it.
    Show {
        project: String,
        service: String,

        /// Only the file, so it can be redirected into one.
        #[arg(long)]
        plain: bool,
    },

    /// Replace it. From then on the form never overwrites it again.
    Edit {
        project: String,
        service: String,

        /// The file to send, or `-` for standard input.
        #[arg(long, default_value = "-")]
        file: String,
    },
}

#[derive(Subcommand)]
enum DataCommand {
    /// The tables and views (or collections), with an estimated row count.
    Tables { project: String, service: String },

    /// One read-only statement, first rows back. Two statements are refused.
    Query {
        project: String,
        service: String,
        /// `SELECT …`, or for MongoDB `{"find": "users"}`. Quote it for the
        /// shell; `-` reads it from stdin.
        sql: String,

        /// Rows to print, at most 200.
        #[arg(long, short = 'n')]
        limit: Option<u64>,
    },

    /// One statement that changes data — UPDATE, INSERT, DELETE, ALTER, or a
    /// MongoDB command — committed.
    ///
    /// Run it with `--preview` first: the statement executes and is undone,
    /// and the count printed is exactly what the real run would touch. MongoDB,
    /// ClickHouse and MySQL schema changes cannot be undone, so their preview
    /// runs nothing and says so. The real run needs `--confirm <service>` and is
    /// written in the project's history with the statement. There is no undo.
    Run {
        project: String,
        service: String,
        /// The statement. Quote it for the shell; `-` reads it from stdin.
        sql: String,

        /// Execute and undo, printing what would have happened.
        #[arg(long)]
        preview: bool,

        /// The service's name or slug, repeated. Required unless --preview.
        #[arg(long)]
        confirm: Option<String>,
    },
}

#[derive(Subcommand)]
enum VariableCommand {
    /// List them.
    List {
        project: String,
        service: String,

        /// Decrypt the secrets. Each one is recorded on the server.
        #[arg(long)]
        reveal: bool,
    },

    /// Set one.
    Set {
        project: String,
        service: String,
        key: String,
        value: String,

        /// Store it encrypted, and never show it again.
        #[arg(long)]
        secret: bool,

        /// Seal it on the way in: unreadable and unchangeable from the start.
        #[arg(long)]
        sealed: bool,
    },

    /// Seal one: the container keeps receiving it, nobody can read or change it.
    Seal {
        project: String,
        service: String,
        key: String,

        /// The key again. Sealing cannot be undone.
        #[arg(long)]
        confirm: Option<String>,
    },

    /// Remove one.
    Unset {
        project: String,
        service: String,
        key: String,
    },

    /// Every `${{ … }}` in a project that will not resolve, with the nearest name that exists.
    Audit { project: String },

    /// Read a `.env` and set every variable in it, in one request.
    Import {
        project: String,
        service: String,

        /// The file to read, or `-` for standard input.
        file: String,

        /// Store them all encrypted.
        #[arg(long)]
        secret: bool,
    },
}

#[derive(Args)]
struct SettingsArgs {
    project: String,
    service: String,

    /// The repository this service builds from, as `owner/name`. Only for
    /// a service created from GitHub; the way to follow a repository that
    /// was renamed there. Read by the next deployment.
    #[arg(long)]
    repo: Option<String>,

    /// The branch to watch and build. Only for a service created from
    /// GitHub. Read by the next deployment.
    #[arg(long)]
    branch: Option<String>,

    /// Memory ceiling, in MB.
    #[arg(long)]
    memory: Option<u32>,

    /// How many containers to run behind the one hostname.
    #[arg(long)]
    replicas: Option<u32>,

    /// Which directory of the repository this service is, in a monorepo.
    #[arg(long)]
    root: Option<String>,

    /// What to run instead of the image's own entrypoint.
    #[arg(long = "start-command")]
    start_command: Option<String>,

    /// Deploy on tags instead of branch pushes: a glob such as `v*` deploys
    /// the newest matching tag, by version. An empty value follows the
    /// branch again.
    #[arg(long = "deploy-tags")]
    deploy_tags: Option<String>,

    /// Run once with the new image before it replaces the running one,
    /// e.g. `npx prisma migrate deploy`. A failure keeps the old version
    /// serving. An empty value clears it.
    #[arg(long = "pre-deploy")]
    pre_deploy: Option<String>,

    /// The path a deployment is considered live once it answers. Setting
    /// one is also how a service is moved onto HTTP checks.
    #[arg(long = "health-path")]
    health_path: Option<String>,

    /// What to ask: `auto`, `http`, `tcp`, or `none` for a worker that
    /// serves nothing. `tcp` is what a database brought in as a plain
    /// image needs — asking it for HTTP burns the whole budget.
    #[arg(long = "health-probe")]
    health_probe: Option<String>,

    /// The whole wait, in seconds, before the deployment is called failed.
    #[arg(long = "health-timeout")]
    health_timeout_seconds: Option<u32>,

    /// How often it is asked again, in seconds.
    #[arg(long = "health-interval")]
    health_interval_seconds: Option<u32>,

    /// How long no answer is believed. A server can open its port before
    /// it has a database connection, and pass its check broken.
    #[arg(long = "health-grace")]
    health_grace_seconds: Option<u32>,

    /// Exactly this status. Unset accepts anything under 500, including a
    /// 404 on the health path itself.
    #[arg(long = "health-status")]
    health_expected_status: Option<u32>,

    /// `always`, `on-failure` or `no`.
    #[arg(long = "restart")]
    restart_policy: Option<String>,

    /// How many times the platform tries to bring it back after a crash,
    /// each attempt further apart than the last. Ten by default.
    #[arg(long = "restart-retries")]
    restart_max_retries: Option<u32>,

    /// Sleep when no traffic arrives, and wake on the next request.
    #[arg(long)]
    sleep: Option<bool>,

    /// How many minutes without a request before it sleeps. Eight hours
    /// (480) unless set; the next request pays the wake. Changing it does
    /// not restart the container.
    #[arg(long = "sleep-after")]
    sleep_after_minutes: Option<u32>,

    /// Deploy on its own when the branch moves.
    #[arg(long = "auto-deploy")]
    auto_deploy: Option<bool>,

    /// For a registry image or a catalogue component: deploy on its own
    /// when a newer image appears behind its tag (checked every six hours).
    #[arg(long = "auto-update")]
    image_auto_update: Option<bool>,

    /// Let the gateway hold this service's answers.
    #[arg(long = "cache")]
    cache_enabled: Option<bool>,

    /// How long a cached answer stays fresh, in seconds.
    #[arg(long = "cache-ttl")]
    cache_ttl_seconds: Option<u32>,

    /// When it must be on, in local time: `L-V 08:00-20:00`, `todos
    /// 09:00-18:00`, or several stretches as `"L-V 08:00-14:00 16:00-20:00;
    /// S 10:00-14:00"` (L M X J V S D). Outside them it sleeps once nothing is
    /// in flight, and a request still wakes it. `off` removes the hours.
    #[arg(long)]
    awake: Option<String>,

    /// The time zone of `--awake`, such as `Europe/Madrid`, the default.
    #[arg(long = "awake-tz")]
    awake_tz: Option<String>,

    /// Wake it as its hours begin, so the first visit does not wait. On
    /// unless set.
    #[arg(long = "awake-prewarm")]
    awake_prewarm: Option<bool>,

    /// Go back on its own to the previous healthy deployment when a new one
    /// crashes within ten minutes of going live. Once per deployment; a
    /// rollback never leads to another.
    #[arg(long = "auto-rollback")]
    auto_rollback: Option<bool>,
}

#[derive(Args)]
struct StatusPageArgs {
    project: String,

    #[arg(value_parser = ["on", "off"])]
    switch: Option<String>,

    /// The heading visitors see; the project's name when empty.
    #[arg(long)]
    title: Option<String>,

    /// The services to show, by name and in order, separated by commas:
    /// `--services web,api`.
    #[arg(long)]
    services: Option<String>,

    /// Give it a new address. The old link stops working at once.
    #[arg(long)]
    rotate: bool,
}

#[derive(Args)]
struct NewArgs {
    project: String,
    name: String,

    /// A GitHub repository, as `owner/name`.
    #[arg(long)]
    repo: Option<String>,

    /// A container image.
    #[arg(long)]
    image: Option<String>,

    /// A component from the catalogue: a database, a bucket or Claude Code.
    /// `fundaia templates` lists the ones this account may add.
    #[arg(long)]
    template: Option<String>,

    /// Build from code you upload, with no repository anywhere.
    ///
    /// The service is created empty and waits: `fundaia up` from the
    /// project's directory sends the code and deploys it.
    #[arg(long)]
    upload: bool,

    #[arg(long, default_value = "main")]
    branch: String,

    /// Services it should be able to talk to, by name.
    #[arg(long = "connect-to", value_delimiter = ',')]
    connect_to: Vec<String>,

    /// Create it without starting it.
    ///
    /// Creating a service deploys it — that is what adding one asks for.
    /// This is for the service that cannot start until somebody types a
    /// variable it has no way to guess, where deploying on sight buys a
    /// failed build instead of an empty node.
    #[arg(long = "no-deploy")]
    no_deploy: bool,

    /// For `--template claude-code`: the token `claude setup-token` prints.
    ///
    /// The component spends the subscription behind it, and cannot be
    /// created without one. Left out, it is asked for at the keyboard
    /// (with the echo off; a pipe or --json gets an error naming this
    /// flag) — except by whoever administers the instance, whose
    /// components run on the server's own token and who is never asked.
    /// `fundaia agent` changes it later.
    #[arg(long = "setup-token")]
    setup_token: Option<String>,

    /// For `--template claude-code`: which model. `fundaia templates`
    /// lists them; default claude-sonnet-5.
    #[arg(long)]
    model: Option<String>,

    /// For `--template claude-code`: how hard it thinks — low, medium,
    /// high, xhigh or max. Default high.
    #[arg(long)]
    effort: Option<String>,
}

#[derive(Args)]
struct ImportArgs {
    /// The manifest (`.json`) or the docker-compose (`.yml`, `.yaml`).
    file: String,

    /// Another name, when the original's is taken here.
    #[arg(long)]
    name: Option<String>,

    /// Which shared space it belongs to. Yours, if you say nothing.
    #[arg(long)]
    workspace: Option<String>,

    /// Deploy every service once written.
    #[arg(long)]
    deploy: bool,

    /// For a docker-compose: add its services to this project, in `--env`,
    /// instead of making a new one.
    #[arg(long)]
    project: Option<String>,

    /// For a docker-compose: the GitHub repository (`owner/name`) its
    /// `build:` services are built from, each from its build context.
    /// Without it they are skipped and said.
    #[arg(long)]
    repo: Option<String>,

    /// For a docker-compose: the repository's branch. Default main.
    #[arg(long)]
    branch: Option<String>,
}

#[derive(Subcommand)]
enum StackCommand {
    /// Every stack on offer, with its services and the memory it asks for.
    List,

    /// Put a stack in a project that exists, in `--env`: its services, their
    /// generated passwords, the references between them, volumes and a
    /// hostname for the one it publishes. A name already taken gets a suffix.
    Add {
        project: String,

        /// Its key, from `fundaia stack list`.
        stack: String,

        /// Make it without deploying it.
        #[arg(long = "no-deploy")]
        no_deploy: bool,
    },

    /// A new project made from a stack.
    New {
        /// Its key, from `fundaia stack list`.
        stack: String,

        /// The project's name. The stack's, if you say nothing.
        #[arg(long)]
        name: Option<String>,

        /// Which shared space it belongs to. Yours, if you say nothing.
        #[arg(long)]
        workspace: Option<String>,

        /// Make it without deploying it.
        #[arg(long = "no-deploy")]
        no_deploy: bool,
    },
}

#[derive(Args)]
struct LogsArgs {
    project: String,
    service: String,

    /// Follow the live output.
    #[arg(long, short)]
    follow: bool,

    #[arg(long, short = 'n', default_value_t = 200)]
    tail: usize,

    /// Only one stream: build, deploy, runtime or system.
    #[arg(long)]
    stream: Option<String>,

    /// Only one step of the deployment: queue, checkout, build, start,
    /// health or live — the same six the pipeline draws.
    #[arg(long)]
    step: Option<String>,

    /// Which deployment, by the number `history` shows. The newest by default.
    #[arg(long)]
    deployment: Option<u32>,

    /// Prefix each line with the time the platform recorded it.
    #[arg(long, short = 't')]
    timestamps: bool,

    /// Only one request, by its trace id. The lines print theirs in the
    /// gutter, so this is what you paste after reading one.
    #[arg(long)]
    trace: Option<String>,
}

#[derive(Args)]
struct RequestsArgs {
    project: String,
    service: String,

    /// Only one class of status.
    #[arg(long, value_parser = ["2xx", "3xx", "4xx", "5xx"])]
    status: Option<String>,

    /// Only one HTTP method: GET, POST…
    #[arg(long)]
    method: Option<String>,

    /// Only paths containing this text, case-insensitive.
    #[arg(long)]
    path: Option<String>,

    /// Follow the requests as they arrive.
    #[arg(long, short)]
    follow: bool,

    /// How many of the newest to show, at most 500.
    #[arg(long, short = 'n', default_value_t = 50)]
    limit: usize,
}

#[derive(Args)]
struct AllowArgs {
    project: String,
    service: String,

    /// IPv4 or IPv6 addresses or networks: 203.0.113.7, 198.51.100.0/24,
    /// 2001:db8::/32.
    #[arg(required_unless_present_any = ["clear", "list"], conflicts_with_all = ["clear", "list"])]
    entries: Vec<String>,

    /// Add them to the list instead of replacing it.
    #[arg(long, conflicts_with_all = ["clear", "list"])]
    add: bool,

    /// Remove the list: anybody reaches the service again.
    #[arg(long, conflicts_with = "list")]
    clear: bool,

    /// Show the list, and the rate limit, without changing anything.
    #[arg(long)]
    list: bool,
}

#[derive(Args)]
struct GrepArgs {
    project: String,

    /// What the line contains, 2 to 200 characters. Case-insensitive.
    text: String,

    /// Only one service.
    #[arg(long)]
    service: Option<String>,

    #[arg(long, value_parser = ["debug", "info", "warn", "error"])]
    level: Option<String>,

    #[arg(long, value_parser = ["build", "deploy", "runtime", "system"])]
    stream: Option<String>,

    /// How far back, 24 by default and 168 at most.
    #[arg(long)]
    hours: Option<u32>,

    /// How many lines, 100 by default and 500 at most.
    #[arg(long, short = 'n')]
    limit: Option<u32>,
}

#[derive(Args)]
struct AutofixArgs {
    project: String,
    service: String,

    /// `off`, `diagnose` or `pullRequest`.
    #[arg(long, value_parser = ["off", "diagnose", "pullRequest"])]
    mode: Option<String>,

    /// The Claude Code component that does the work, by id.
    #[arg(long)]
    agent: Option<String>,

    /// Which model it runs on.
    #[arg(long)]
    model: Option<String>,

    /// How many times a failure has to happen before it is worth an agent.
    #[arg(long)]
    min_occurrences: Option<u32>,

    /// Runs per day, per service.
    #[arg(long)]
    daily_limit: Option<u32>,
}

#[derive(Subcommand)]
enum TasksCommand {
    /// Every task of a service: when it runs, when it goes next, how it last went.
    List { project: String, service: String },

    /// Schedule a command: `fundaia tasks add tienda api limpiar "0 3 * * *" -- node cleanup.js`.
    ///
    /// Five-field cron in UTC. It runs with `sh -c` in the running container,
    /// fifteen minutes at most; a sleeping service is woken for it.
    Add {
        project: String,
        service: String,
        name: String,
        schedule: String,

        /// What to run, after `--`.
        #[arg(last = true, required = true)]
        command: Vec<String>,

        /// Create it paused: nothing runs until `tasks edit --resume`.
        #[arg(long)]
        paused: bool,
    },

    /// Change its name, schedule or command, or pause and resume it.
    Edit {
        project: String,
        service: String,
        task: String,

        #[arg(long)]
        name: Option<String>,

        #[arg(long)]
        schedule: Option<String>,

        /// A new command, after `--`.
        #[arg(last = true)]
        command: Vec<String>,

        #[arg(long, conflicts_with = "resume")]
        pause: bool,

        #[arg(long)]
        resume: bool,
    },

    /// Remove it and the record of its runs.
    Rm {
        project: String,
        service: String,
        task: String,
    },

    /// Run it now and follow it to the end, printing its output.
    Run {
        project: String,
        service: String,
        task: String,

        /// Answer as soon as it starts.
        #[arg(long)]
        no_wait: bool,
    },

    /// Its last twenty runs, and the output of the newest.
    Runs {
        project: String,
        service: String,
        task: String,
    },
}

#[derive(Subcommand)]
enum FilesCommand {
    /// List a directory, directories first. The first volume's root by default.
    Ls {
        project: String,
        service: String,
        path: Option<String>,
    },

    /// Print a text file: its first 256 KB, with the service's secrets masked.
    Cat {
        project: String,
        service: String,
        path: String,
    },

    /// Download a file as it is, up to 20 MB.
    Get {
        project: String,
        service: String,
        path: String,

        /// Where to write it. The file's own name, here, unless said.
        #[arg(long, short)]
        output: Option<String>,
    },
}

#[derive(Subcommand)]
enum SharedCommand {
    /// Every environment's, and `--env`'s own.
    List { project: String },

    /// Share one. Every environment gets it unless `--env-only`.
    Set {
        project: String,
        key: String,
        value: String,

        /// Store it encrypted, and never show it again.
        #[arg(long)]
        secret: bool,

        /// Only `--env`'s environment (or the default one) gets it.
        #[arg(long = "env-only")]
        env_only: bool,
    },

    /// Stop sharing one.
    Unset {
        project: String,
        key: String,

        /// Remove the environment's own, not every environment's.
        #[arg(long = "env-only")]
        env_only: bool,
    },
}

#[derive(Subcommand)]
enum AccessCommand {
    /// Whether the repository can be read, and who is being asked.
    Status { project: String, service: String },

    /// Email the owner a link that grants read access.
    Request {
        project: String,
        service: String,

        /// The owner's address. Omit to reuse one this space has already used.
        ///
        /// GitHub publishes an address for almost no account, so this is usually
        /// the one thing that has to be typed: the platform can find out whose
        /// repository it is and never how to reach them.
        #[arg(long)]
        email: Option<String>,
    },
}

#[derive(Subcommand)]
enum BackupCommand {
    /// List them, with the schedule and when the next one lands.
    List { project: String, service: String },

    /// Take one now. Waits for it.
    New { project: String, service: String },

    /// Which schedules run: daily, weekly, monthly. With none, it stops copying.
    Schedule {
        project: String,
        service: String,

        /// Any of `daily`, `weekly`, `monthly`, comma separated.
        #[arg(value_delimiter = ',')]
        schedules: Vec<String>,
    },

    /// Put one back. Overwrites the volume; the server copies it first.
    Restore {
        /// The id `backups list` shows.
        backup_id: String,

        /// The id again. This overwrites data.
        #[arg(long)]
        confirm: Option<String>,
    },

    /// Keep one past its retention.
    Keep { backup_id: String },

    /// Let retention have it again.
    Unkeep { backup_id: String },

    /// Delete one now.
    Remove { backup_id: String },
}

#[derive(Subcommand)]
enum SessionCommand {
    /// Sign one out, by the id `fundaia sessions` printed.
    ///
    /// The id is the session token's digest rather than the token: holding it
    /// opens nothing, which is what makes it safe to print in a table.
    Revoke { session_id: String },
}

#[derive(Subcommand)]
enum DomainCommand {
    List {
        project: String,
        service: String,
    },

    /// Add one. With no host, generates one under the platform's domain.
    Add {
        project: String,
        service: String,
        host: Option<String>,
    },

    /// Check a custom domain now: its DNS record and its certificate.
    Verify {
        domain_id: String,
    },

    Remove {
        domain_id: String,
    },
}

fn main() {
    let cli = Cli::parse();
    let format = output::chosen(cli.json);

    if cli.no_color || format.is_json() {
        owo_colors::set_override(false);
        theme::silence();
    }

    if !matches!(cli.command, Command::Completions { .. }) {
        changelog::history::record(env!("CARGO_PKG_VERSION"));
    }

    let runtime;
    let outcome = if asks_the_registry(&cli.command) {
        runtime = tokio::runtime::Builder::new_multi_thread()
            .enable_all()
            .build()
            .expect("the async runtime starts");

        runtime.block_on(async {
            let update = update::UpdateCheck::start(env!("CARGO_PKG_VERSION"), format.is_json());
            let outcome = run(cli, format).await;
            update.finish().await;
            outcome
        })
    } else {
        run_offline(&cli.command, format)
    };

    if let Err(error) = outcome {
        let status = exit::classify(&error);

        if format.is_json() {
            output::emit_error(&error, exit::hint(status));
            std::process::exit(status.code());
        }

        eprintln!();
        eprintln!("  {} {error}", theme::CROSS.style(theme::danger()));

        for cause in error.chain().skip(1) {
            eprintln!("    {}", cause.style(theme::muted()));
        }

        if let Some(hint) = exit::hint(status) {
            eprintln!("    {}", hint.style(theme::muted()));
        }

        eprintln!();
        std::process::exit(status.code());
    }
}

fn asks_the_registry(command: &Command) -> bool {
    !matches!(
        command,
        Command::Completions { .. } | Command::Schema | Command::Guide | Command::Skill { .. }
    )
}

fn built() -> clap::Command {
    let mut command = Cli::command();
    command.build();
    command
}

fn run_offline(command: &Command, format: Format) -> Result<()> {
    match command {
        Command::Completions { shell } => {
            clap_complete::generate(*shell, &mut built(), "fundaia", &mut std::io::stdout());
            Ok(())
        }
        Command::Schema => commands::schema::run(&built(), format),
        Command::Guide => commands::guide::run(format),
        Command::Skill { command } => match command {
            None | Some(SkillCommand::Show) => commands::skill::show(&built(), format),
            Some(SkillCommand::Install { project }) => {
                commands::skill::install(&built(), *project, format)
            }
            Some(SkillCommand::Path { project }) => commands::skill::print_path(*project, format),
        },
        _ => unreachable!("only the commands that reach nothing are answered offline"),
    }
}

async fn run(cli: Cli, format: Format) -> Result<()> {
    match &cli.command {
        Command::Login {
            url,
            as_profile,
            no_browser,
        } => return commands::login::run(url, as_profile, !no_browser).await,
        Command::Logout { profile } => return commands::login::logout(profile.as_deref()),
        Command::Upgrade { check } => {
            return update::upgrade(env!("CARGO_PKG_VERSION"), *check).await
        }
        Command::Changelog {
            release,
            all,
            since,
            count,
            history,
        } => {
            return if *history {
                commands::changelog::show_history(format)
            } else {
                commands::changelog::show(
                    &commands::changelog::Query {
                        all: *all,
                        version: release.clone(),
                        since: since.clone(),
                        count: *count,
                    },
                    format,
                )
            }
        }
        Command::Completions { .. } | Command::Schema | Command::Guide | Command::Skill { .. } => {
            return run_offline(&cli.command, format)
        }
        _ => {}
    }

    let client = connect(&cli)?.with_environment(cli.environment.as_deref());

    match cli.command {
        Command::Login { .. }
        | Command::Logout { .. }
        | Command::Upgrade { .. }
        | Command::Changelog { .. }
        | Command::Completions { .. }
        | Command::Schema
        | Command::Guide
        | Command::Skill { .. } => {
            unreachable!("handled above")
        }

        Command::Whoami => commands::login::whoami(&client, format).await,

        Command::Status => commands::read::status(&client, format).await,
        Command::Projects => commands::read::projects(&client, format).await,

        Command::Project { command } => match command {
            ProjectCommand::New {
                name,
                description,
                workspace,
            } => {
                commands::write::create_project(
                    &client,
                    &name,
                    description.as_deref(),
                    workspace.as_deref(),
                )
                .await
            }
            ProjectCommand::Rename {
                project,
                name,
                description,
            } => {
                commands::manage::rename_project(
                    &client,
                    &project,
                    name.as_deref(),
                    description.as_deref(),
                )
                .await
            }
            ProjectCommand::Delete { project, confirm } => {
                commands::manage::delete_project(&client, &project, confirm.as_deref()).await
            }
            ProjectCommand::Move { project, workspace } => {
                commands::manage::move_project(&client, &project, &workspace).await
            }
            ProjectCommand::Star { project } => {
                commands::manage::favorite_project(&client, &project, true, format).await
            }
            ProjectCommand::Unstar { project } => {
                commands::manage::favorite_project(&client, &project, false, format).await
            }
        },
        Command::Envs { project } => commands::environments::list(&client, &project, format).await,
        Command::Webhooks { project } => commands::webhooks::list(&client, &project, format).await,
        Command::Webhook { command } => match command {
            WebhookCommand::Add {
                project,
                url,
                name,
                format: webhook_format,
                events,
            } => {
                commands::webhooks::add(
                    &client,
                    commands::webhooks::AddRequest {
                        project: &project,
                        url: &url,
                        name: name.as_deref(),
                        format: webhook_format.as_deref(),
                        events: &events,
                    },
                    format,
                )
                .await
            }
            WebhookCommand::Set {
                project,
                webhook,
                name,
                events,
                pause,
                resume,
            } => {
                commands::webhooks::set(
                    &client,
                    commands::webhooks::SetRequest {
                        project: &project,
                        webhook: &webhook,
                        name: name.as_deref(),
                        events: events.as_deref(),
                        enabled: if pause {
                            Some(false)
                        } else if resume {
                            Some(true)
                        } else {
                            None
                        },
                    },
                    format,
                )
                .await
            }
            WebhookCommand::Rm { project, webhook } => {
                commands::webhooks::remove(&client, &project, &webhook, format).await
            }
            WebhookCommand::Test { project, webhook } => {
                commands::webhooks::test(&client, &project, &webhook, format).await
            }
        },
        Command::Servers { command } => match command {
            ServersCommand::List => commands::servers::list(&client, format).await,
            ServersCommand::Show { server } => {
                commands::servers::show(&client, &server, format).await
            }
            ServersCommand::Add(args) => {
                commands::servers::add(
                    &client,
                    commands::servers::ServerRequest {
                        name: &args.name,
                        connection: &args.connection,
                        address: &args.address,
                        identity: args.identity.as_deref(),
                        region: args.region.as_deref(),
                    },
                    format,
                )
                .await
            }
            ServersCommand::Cordon { server } => {
                commands::servers::cordon(&client, &server, true, format).await
            }
            ServersCommand::Uncordon { server } => {
                commands::servers::cordon(&client, &server, false, format).await
            }
            ServersCommand::Failover { server, switch } => {
                commands::servers::failover(&client, &server, switch == "on", format).await
            }
            ServersCommand::Drain { server, dry_run } => {
                commands::servers::drain(&client, &server, dry_run, format).await
            }
            ServersCommand::Rm { server, confirm } => {
                commands::servers::remove(&client, &server, confirm.as_deref(), format).await
            }
        },
        Command::Env { command } => match command {
            EnvCommand::Server {
                project,
                environment,
            } => {
                commands::servers::environment_server(&client, &project, &environment, format).await
            }
            EnvCommand::Move {
                project,
                environment,
                to,
                wait,
            } => {
                commands::servers::move_environment(
                    &client,
                    &project,
                    &environment,
                    &to,
                    wait,
                    format,
                )
                .await
            }
            EnvCommand::New {
                project,
                name,
                from,
                empty,
                no_deploy,
                ttl,
            } => {
                commands::environments::create(
                    &client,
                    commands::environments::EnvironmentRequest {
                        project: &project,
                        name: &name,
                        from: from.as_deref(),
                        empty,
                        no_deploy,
                        ttl: ttl.as_deref(),
                    },
                    format,
                )
                .await
            }
            EnvCommand::Expire {
                project,
                environment,
                ttl,
            } => {
                commands::environments::expire(&client, &project, &environment, &ttl, format).await
            }
            EnvCommand::Promote(arguments) => {
                commands::environments::promote(
                    &client,
                    commands::environments::PromoteRequest {
                        project: &arguments.project,
                        from: &arguments.from,
                        to: &arguments.to,
                        services: &arguments.services,
                        dry_run: arguments.dry_run,
                    },
                    format,
                )
                .await
            }
            EnvCommand::CopyData(arguments) => {
                commands::environments::copy_data(
                    &client,
                    commands::environments::DataCopyRequest {
                        project: &arguments.project,
                        from: &arguments.from,
                        to: &arguments.to,
                        services: &arguments.services,
                        confirmation: arguments.confirm.as_deref(),
                        dry_run: arguments.dry_run,
                    },
                    format,
                )
                .await
            }
            EnvCommand::Diff { project, from, to } => {
                commands::environments::diff(&client, &project, &from, &to, format).await
            }
            EnvCommand::Rename {
                project,
                environment,
                name,
            } => {
                commands::environments::rename(&client, &project, &environment, &name, format).await
            }
            EnvCommand::Rm {
                project,
                environment,
                confirm,
            } => {
                commands::environments::remove(
                    &client,
                    &project,
                    &environment,
                    confirm.as_deref(),
                    format,
                )
                .await
            }
            EnvCommand::Copy {
                project,
                service,
                from,
                to,
                no_deploy,
            } => {
                commands::environments::copy(
                    &client,
                    commands::environments::CopyRequest {
                        project: &project,
                        service: &service,
                        from: from.as_deref(),
                        to: &to,
                        no_deploy,
                    },
                    format,
                )
                .await
            }
        },
        Command::Services { project } => commands::read::services(&client, &project, format).await,
        Command::Service { project, service } => {
            commands::read::service(&client, &project, &service, format).await
        }
        Command::Canvas { command } => match command {
            CanvasCommand::Show { project, map } => {
                commands::read::canvas(&client, &project, map, format).await
            }
            CanvasCommand::Move {
                project,
                service,
                x,
                y,
            } => commands::write::move_on_canvas(&client, &project, &service, x, y, format).await,
            CanvasCommand::Arrange { project, layout } => {
                commands::write::arrange_canvas(&client, &project, &layout, format).await
            }
        },

        Command::Templates => commands::write::templates(&client, format).await,

        Command::New(NewArgs {
            project,
            name,
            repo,
            image,
            template,
            upload,
            branch,
            connect_to,
            no_deploy,
            setup_token,
            model,
            effort,
        }) => {
            commands::write::create_service(
                &client,
                commands::write::ServiceRequest {
                    project: &project,
                    name: &name,
                    repo: repo.as_deref(),
                    image: image.as_deref(),
                    template: template.as_deref(),
                    upload,
                    branch: &branch,
                    connect_to: &connect_to,
                    no_deploy,
                    setup_token: setup_token.as_deref(),
                    model: model.as_deref(),
                    effort: effort.as_deref(),
                },
                format,
            )
            .await
        }

        Command::Agent {
            project,
            service,
            model,
            effort,
            setup_token,
        } => {
            commands::write::agent(
                &client,
                &project,
                &service,
                api::models::AgentSetupPatch {
                    model,
                    effort,
                    setup_token,
                },
                format,
            )
            .await
        }

        Command::Rename {
            project,
            service,
            name,
        } => commands::manage::rename_service(&client, &project, &service, &name).await,

        Command::Up {
            project,
            service,
            path,
            no_deploy,
            detach,
        } => {
            commands::upload::run(
                &client,
                &project,
                &service,
                std::path::Path::new(&path),
                !no_deploy,
                !detach,
                format,
            )
            .await
        }

        Command::Uploads { project, service } => {
            commands::upload::list(&client, &project, &service, format).await
        }

        Command::Deploy {
            project,
            service,
            restart,
            no_cache,
            detach,
        } => {
            commands::deploy::run(
                &client,
                commands::deploy::DeployRequest {
                    project: &project,
                    service: &service,
                    restart,
                    no_cache,
                    follow: !detach,
                },
                format,
            )
            .await
        }

        Command::Redeploy {
            project,
            service,
            number,
        } => commands::deploy::redeploy(&client, &project, &service, number, format).await,

        Command::Rollback {
            project,
            service,
            number,
        } => commands::deploy::rollback(&client, &project, &service, number, format).await,

        Command::Cancel {
            project,
            service,
            deployment,
        } => commands::deploy::cancel(&client, &project, &service, deployment, format).await,

        Command::Stop { project, service } => {
            commands::write::stop(&client, &project, &service).await
        }

        Command::Bulk {
            action,
            project,
            services,
        } => commands::bulk::run(&client, &action, &project, &services, format).await,

        Command::Hooks { command } => match command {
            HookCommand::List { project, service } => {
                commands::hooks::list(&client, &project, &service, format).await
            }
            HookCommand::Add {
                project,
                service,
                name,
            } => commands::hooks::add(&client, &project, &service, &name, format).await,
            HookCommand::Rm {
                project,
                service,
                hook,
            } => commands::hooks::remove(&client, &project, &service, &hook, format).await,
        },

        Command::History {
            project,
            service,
            limit,
            commit,
        } => {
            commands::read::history(
                &client,
                &project,
                &service,
                limit,
                commit.as_deref(),
                format,
            )
            .await
        }

        Command::Commit {
            project,
            service,
            commit,
            file,
            stat,
        } => commands::read::commit(&client, &project, &service, commit, file, stat, format).await,

        Command::Watch { project, service } => {
            commands::watch::run(&client, project.as_deref(), service.as_deref(), format).await
        }

        Command::Logs(LogsArgs {
            project,
            service,
            follow,
            tail,
            stream,
            step,
            deployment,
            timestamps,
            trace,
        }) => {
            commands::logs::run(
                &client,
                &project,
                &service,
                commands::logs::LogQuery {
                    follow,
                    tail,
                    stream_filter: stream.as_deref(),
                    stage: step.as_deref(),
                    number: deployment,
                    timestamps,
                    trace: trace.as_deref(),
                },
                format,
            )
            .await
        }

        Command::Incidents {
            project,
            service,
            decided,
        } => commands::read::incidents(&client, &project, &service, decided, format).await,

        Command::Workflows { command } => match command {
            WorkflowCommand::List { project, refresh } => {
                commands::workflows::list(&client, &project, refresh, format).await
            }
            WorkflowCommand::Runs {
                project,
                path,
                commit,
                limit,
            } => {
                commands::workflows::runs(
                    &client,
                    &project,
                    path.as_deref(),
                    commit.as_deref(),
                    limit,
                    format,
                )
                .await
            }
            WorkflowCommand::Run {
                project,
                path,
                branch,
                inputs,
            } => {
                commands::workflows::run(
                    &client,
                    &project,
                    &path,
                    branch.as_deref(),
                    &inputs,
                    format,
                )
                .await
            }
            WorkflowCommand::Show { run_id } => {
                commands::workflows::show(&client, &run_id, format).await
            }
            WorkflowCommand::Logs { job_id } => {
                commands::workflows::logs(&client, &job_id, format).await
            }
            WorkflowCommand::Cancel { run_id } => {
                commands::workflows::cancel(&client, &run_id, format).await
            }
            WorkflowCommand::Rerun { run_id } => {
                commands::workflows::rerun(&client, &run_id, format).await
            }
            WorkflowCommand::Stats { project, limit } => {
                commands::workflows::stats(&client, &project, limit, format).await
            }
            WorkflowCommand::Wait { run_id, timeout } => {
                commands::workflows::wait(&client, &run_id, timeout, format).await
            }
            WorkflowCommand::Artifact { job_id, into } => {
                commands::workflows::artifact(&client, &job_id, into.as_deref(), format).await
            }
        },

        Command::Approvals { project, service } => {
            commands::read::approvals(&client, &project, service.as_deref(), format).await
        }

        Command::Approve { id } => commands::write::approve_deployment(&client, &id, format).await,

        Command::Reject { id } => commands::write::reject_deployment(&client, &id, format).await,

        Command::Autofix(AutofixArgs {
            project,
            service,
            mode,
            agent,
            model,
            min_occurrences,
            daily_limit,
        }) => {
            commands::read::autofix(
                &client,
                &project,
                &service,
                api::models::AutofixPatch {
                    mode,
                    agent_service_environment_id: agent,
                    model,
                    minimum_occurrences: min_occurrences,
                    daily_limit,
                },
                format,
            )
            .await
        }

        Command::Fix { id, command } => match (command, id) {
            (
                Some(FixCommand::Deployment {
                    project,
                    service,
                    number,
                }),
                _,
            ) => {
                commands::repair::fix_deployment(&client, &project, &service, number, format).await
            }
            (None, Some(id)) => commands::write::fix_incident(&client, &id, format).await,
            (None, None) => unreachable!("clap requires the id when there is no subcommand"),
        },

        Command::Attention => commands::insights::attention(&client, format).await,
        Command::Health { project } => commands::insights::health(&client, &project, format).await,
        Command::Diagnose { project, service } => {
            commands::insights::diagnose(&client, &project, &service, format).await
        }
        Command::Grep(GrepArgs {
            project,
            text,
            service,
            level,
            stream,
            hours,
            limit,
        }) => {
            commands::insights::grep(
                &client,
                &project,
                commands::insights::GrepQuery {
                    text: &text,
                    service: service.as_deref(),
                    level: level.as_deref(),
                    stream: stream.as_deref(),
                    hours,
                    limit,
                },
                format,
            )
            .await
        }
        Command::Deps { project, service } => {
            commands::insights::dependencies(&client, &project, &service, format).await
        }
        Command::Import(args) => {
            let text = std::fs::read_to_string(&args.file)
                .with_context(|| format!("could not read {}", args.file))?;
            if commands::creation::is_compose(&args.file, &text) {
                commands::creation::import_compose(
                    &client,
                    commands::creation::ComposeRequest {
                        text: &text,
                        name: args.name.as_deref(),
                        workspace: args.workspace.as_deref(),
                        project: args.project.as_deref(),
                        repository: args.repo.as_deref(),
                        branch: args.branch.as_deref(),
                        deploy: args.deploy,
                    },
                    format,
                )
                .await
            } else {
                commands::insights::import(
                    &client,
                    &args.file,
                    args.name.as_deref(),
                    args.workspace.as_deref(),
                    args.deploy,
                    format,
                )
                .await
            }
        }
        Command::Stack { command } => match command {
            StackCommand::List => commands::creation::list_stacks(&client, format).await,
            StackCommand::Add {
                project,
                stack,
                no_deploy,
            } => {
                commands::creation::add_stack(
                    &client,
                    commands::creation::StackRequest {
                        key: &stack,
                        project: Some(&project),
                        name: None,
                        workspace: None,
                        deploy: !no_deploy,
                    },
                    format,
                )
                .await
            }
            StackCommand::New {
                stack,
                name,
                workspace,
                no_deploy,
            } => {
                commands::creation::add_stack(
                    &client,
                    commands::creation::StackRequest {
                        key: &stack,
                        project: None,
                        name: name.as_deref(),
                        workspace: workspace.as_deref(),
                        deploy: !no_deploy,
                    },
                    format,
                )
                .await
            }
        },
        Command::Duplicate {
            project,
            service,
            name,
            no_deploy,
        } => {
            commands::creation::duplicate(&client, &project, &service, &name, !no_deploy, format)
                .await
        }
        Command::Export { project, file } => {
            commands::insights::export(&client, &project, file.as_deref(), format).await
        }
        Command::Compare {
            project,
            service,
            from,
            to,
        } => commands::insights::compare(&client, &project, &service, from, to, format).await,
        Command::Probe {
            project,
            service,
            path,
        } => commands::insights::probe(&client, &project, &service, &path, format).await,
        Command::Wake { project, service } => {
            commands::insights::wake(&client, &project, &service, format).await
        }
        Command::Security { command } => match command {
            SecurityCommand::Scan {
                project,
                service,
                fix,
                wait,
            } => commands::repair::scan(&client, &project, &service, fix, wait, format).await,
            SecurityCommand::Show { scan_id } => {
                commands::repair::show(&client, &scan_id, format).await
            }
            SecurityCommand::List { project, service } => {
                commands::repair::list(&client, &project, &service, format).await
            }
        },
        Command::Issue { kind, id } => commands::repair::issue(&client, &kind, &id, format).await,

        Command::Incident { id, status } => {
            commands::write::decide_incident(&client, &id, &status, format).await
        }

        Command::SignIns { limit } => commands::read::sign_ins(&client, limit, format).await,

        Command::Sessions { command } => match command {
            None => commands::read::auth_sessions(&client, format).await,
            Some(SessionCommand::Revoke { session_id }) => {
                commands::login::revoke_session(&client, &session_id).await
            }
        },

        Command::Activity { project, limit } => {
            commands::read::activity(&client, &project, limit, format).await
        }

        Command::Metrics {
            project,
            service,
            minutes,
        } => commands::read::metrics(&client, &project, &service, minutes, format).await,

        Command::Consumption {
            project,
            service,
            range,
        } => commands::read::consumption(&client, &project, &service, &range, format).await,

        Command::AgentActivity {
            project,
            service,
            range,
            outcome,
        } => {
            commands::read::agent_activity(
                &client,
                &project,
                &service,
                &range,
                outcome.as_deref(),
                format,
            )
            .await
        }

        Command::Data { command } => match command {
            DataCommand::Tables { project, service } => {
                commands::data::tables(&client, &project, &service, format).await
            }
            DataCommand::Query {
                project,
                service,
                sql,
                limit,
            } => commands::data::query(&client, &project, &service, &sql, limit, format).await,
            DataCommand::Run {
                project,
                service,
                sql,
                preview,
                confirm,
            } => {
                commands::data::run(
                    &client,
                    &project,
                    &service,
                    &sql,
                    preview,
                    confirm.as_deref(),
                    format,
                )
                .await
            }
        },

        Command::Shared { command } => match command {
            SharedCommand::List { project } => {
                commands::shared::list(&client, &project, format).await
            }
            SharedCommand::Set {
                project,
                key,
                value,
                secret,
                env_only,
            } => {
                commands::shared::set(
                    &client,
                    commands::shared::SetRequest {
                        project: &project,
                        key: &key,
                        value: &value,
                        secret,
                        environment_only: env_only,
                    },
                    format,
                )
                .await
            }
            SharedCommand::Unset {
                project,
                key,
                env_only,
            } => commands::shared::unset(&client, &project, &key, env_only, format).await,
        },
        Command::Variables { command } => match command {
            VariableCommand::List {
                project,
                service,
                reveal,
            } => commands::read::variables(&client, &project, &service, reveal, format).await,
            VariableCommand::Set {
                project,
                service,
                key,
                value,
                secret,
                sealed,
            } => {
                commands::write::set_variable(
                    &client, &project, &service, &key, &value, secret, sealed,
                )
                .await
            }
            VariableCommand::Seal {
                project,
                service,
                key,
                confirm,
            } => {
                commands::write::seal_variable(
                    &client,
                    &project,
                    &service,
                    &key,
                    confirm.as_deref(),
                )
                .await
            }
            VariableCommand::Unset {
                project,
                service,
                key,
            } => commands::write::unset_variable(&client, &project, &service, &key).await,
            VariableCommand::Audit { project } => {
                commands::insights::audit_variables(&client, &project, format).await
            }
            VariableCommand::Import {
                project,
                service,
                file,
                secret,
            } => {
                commands::write::import_variables(&client, &project, &service, &file, secret).await
            }
        },

        Command::Access { command } => match command {
            AccessCommand::Status { project, service } => {
                commands::read::repository_access(&client, &project, &service, format).await
            }
            AccessCommand::Request {
                project,
                service,
                email,
            } => {
                commands::write::request_repository_access(
                    &client,
                    &project,
                    &service,
                    email.as_deref(),
                    format,
                )
                .await
            }
        },

        Command::Backups { command } => match command {
            BackupCommand::List { project, service } => {
                commands::read::backups(&client, &project, &service, format).await
            }
            BackupCommand::New { project, service } => {
                commands::write::take_backup(&client, &project, &service).await
            }
            BackupCommand::Schedule {
                project,
                service,
                schedules,
            } => commands::write::schedule_backups(&client, &project, &service, &schedules).await,
            BackupCommand::Restore { backup_id, confirm } => {
                commands::write::restore_backup(&client, &backup_id, confirm.as_deref()).await
            }
            BackupCommand::Keep { backup_id } => {
                commands::write::lock_backup(&client, &backup_id, true).await
            }
            BackupCommand::Unkeep { backup_id } => {
                commands::write::lock_backup(&client, &backup_id, false).await
            }
            BackupCommand::Remove { backup_id } => {
                commands::write::delete_backup(&client, &backup_id).await
            }
        },

        Command::Domains { command } => match command {
            DomainCommand::List { project, service } => {
                commands::read::domains(&client, &project, &service, format).await
            }
            DomainCommand::Add {
                project,
                service,
                host,
            } => commands::write::add_domain(&client, &project, &service, host.as_deref()).await,
            DomainCommand::Verify { domain_id } => {
                commands::read::verify_domain(&client, &domain_id, format).await
            }
            DomainCommand::Remove { domain_id } => {
                commands::write::remove_domain(&client, &domain_id).await
            }
        },

        Command::Connect {
            project,
            service,
            provider,
        } => commands::write::connect(&client, &project, &service, &provider).await,

        Command::Disconnect {
            project,
            service,
            provider,
        } => commands::manage::disconnect(&client, &project, &service, &provider).await,

        Command::Connectable { project, service } => {
            commands::write::candidates(&client, &project, &service, format).await
        }

        Command::Volumes { command } => match command {
            VolumeCommand::List { project, service } => {
                commands::read::volumes(&client, &project, &service, format).await
            }
            VolumeCommand::Add {
                project,
                service,
                mount_path,
            } => commands::write::attach_volume(&client, &project, &service, &mount_path).await,
            VolumeCommand::Resize { volume_id, gb } => {
                commands::write::resize_volume(&client, &volume_id, gb).await
            }
            VolumeCommand::Remove { volume_id } => {
                commands::manage::detach_volume(&client, &volume_id).await
            }
        },

        Command::Recipe { command } => match command {
            RecipeCommand::Show {
                project,
                service,
                plain,
            } => commands::read::recipe(&client, &project, &service, plain, format).await,
            RecipeCommand::Edit {
                project,
                service,
                file,
            } => commands::write::edit_recipe(&client, &project, &service, &file).await,
        },

        Command::Config { command } => match command {
            ConfigCommand::Show {
                project,
                service,
                plain,
            } => commands::read::service_config(&client, &project, &service, plain, format).await,
            ConfigCommand::Edit {
                project,
                service,
                file,
            } => commands::write::edit_service_config(&client, &project, &service, &file).await,
        },

        Command::Capabilities { project, service } => {
            commands::read::capabilities(&client, &project, &service, format).await
        }

        Command::Capacity => commands::manage::capacity(&client, format).await,

        Command::Settings(SettingsArgs {
            project,
            service,
            repo,
            branch,
            memory,
            replicas,
            root,
            start_command,
            deploy_tags,
            pre_deploy,
            health_path,
            health_probe,
            health_timeout_seconds,
            health_interval_seconds,
            health_grace_seconds,
            health_expected_status,
            restart_policy,
            restart_max_retries,
            sleep,
            sleep_after_minutes,
            auto_deploy,
            image_auto_update,
            cache_enabled,
            cache_ttl_seconds,
            awake,
            awake_tz,
            awake_prewarm,
            auto_rollback,
        }) => {
            commands::manage::set_settings(
                &client,
                &project,
                &service,
                api::models::SettingsPatch {
                    repo_full_name: repo,
                    branch,
                    memory_mb: memory,
                    replicas,
                    root_directory: root,
                    start_command,
                    pre_deploy_command: pre_deploy,
                    deploy_tag_pattern: deploy_tags,
                    health_path,
                    health_probe,
                    health_timeout_seconds,
                    health_interval_seconds,
                    health_grace_seconds,
                    health_expected_status,
                    restart_policy,
                    restart_max_retries,
                    sleep_enabled: sleep,
                    sleep_after_minutes,
                    auto_deploy,
                    image_auto_update,
                    cache_enabled,
                    cache_ttl_seconds,
                    awake_schedule: awake,
                    awake_timezone: awake_tz,
                    awake_prewarm,
                    auto_rollback,
                },
            )
            .await
        }

        Command::Expose {
            project,
            service,
            off,
        } => commands::manage::expose(&client, &project, &service, !off).await,

        Command::Deployments {
            active,
            failed,
            limit,
        } => commands::visibility::deployments(&client, active, failed, limit, format).await,

        Command::StatusPage(StatusPageArgs {
            project,
            switch,
            title,
            services,
            rotate,
        }) => {
            commands::visibility::status_page(
                &client,
                commands::visibility::StatusPageRequest {
                    project: &project,
                    switch: switch.as_deref().map(|word| word == "on"),
                    title,
                    services: services.as_deref().map(commands::visibility::services_of),
                    rotate,
                },
                format,
            )
            .await
        }

        Command::Previews { project, switch } => {
            commands::previews::run(
                &client,
                &project,
                switch.as_deref().map(|word| word == "on"),
                format,
            )
            .await
        }

        Command::Pull { project, service } => {
            commands::console::pull(&client, &project, &service, format).await
        }

        Command::Tasks { command } => match command {
            TasksCommand::List { project, service } => {
                commands::tasks::list(&client, &project, &service, format).await
            }
            TasksCommand::Add {
                project,
                service,
                name,
                schedule,
                command,
                paused,
            } => {
                commands::tasks::add(
                    &client,
                    commands::tasks::AddRequest {
                        project: &project,
                        service: &service,
                        name: &name,
                        schedule: &schedule,
                        command: &command,
                        paused,
                    },
                    format,
                )
                .await
            }
            TasksCommand::Edit {
                project,
                service,
                task,
                name,
                schedule,
                command,
                pause,
                resume,
            } => {
                commands::tasks::edit(
                    &client,
                    commands::tasks::EditRequest {
                        project: &project,
                        service: &service,
                        task: &task,
                        name: name.as_deref(),
                        schedule: schedule.as_deref(),
                        command: &command,
                        enabled: if pause {
                            Some(false)
                        } else if resume {
                            Some(true)
                        } else {
                            None
                        },
                    },
                    format,
                )
                .await
            }
            TasksCommand::Rm {
                project,
                service,
                task,
            } => commands::tasks::remove(&client, &project, &service, &task, format).await,
            TasksCommand::Run {
                project,
                service,
                task,
                no_wait,
            } => commands::tasks::run(&client, &project, &service, &task, !no_wait, format).await,
            TasksCommand::Runs {
                project,
                service,
                task,
            } => commands::tasks::runs(&client, &project, &service, &task, format).await,
        },

        Command::Files { command } => match command {
            FilesCommand::Ls {
                project,
                service,
                path,
            } => commands::files::list(&client, &project, &service, path.as_deref(), format).await,
            FilesCommand::Cat {
                project,
                service,
                path,
            } => commands::files::cat(&client, &project, &service, &path, format).await,
            FilesCommand::Get {
                project,
                service,
                path,
                output,
            } => {
                commands::files::get(
                    &client,
                    &project,
                    &service,
                    &path,
                    output.as_deref(),
                    format,
                )
                .await
            }
        },

        Command::Exec {
            project,
            service,
            command,
        } => commands::console::exec(&client, &project, &service, &command, format).await,

        Command::Maintenance {
            project,
            service,
            off,
            message,
        } => {
            commands::edge::maintenance(
                &client,
                &project,
                &service,
                !off,
                message.as_deref(),
                format,
            )
            .await
        }

        Command::Protect {
            project,
            service,
            user,
            password,
        } => {
            commands::edge::protect(
                &client,
                &project,
                &service,
                &user,
                password.as_deref(),
                format,
            )
            .await
        }

        Command::Unprotect { project, service } => {
            commands::edge::unprotect(&client, &project, &service, format).await
        }

        Command::Requests(RequestsArgs {
            project,
            service,
            status,
            method,
            path,
            follow,
            limit,
        }) => {
            commands::requests::run(
                &client,
                &project,
                &service,
                commands::requests::RequestQuery {
                    status: status.as_deref(),
                    method: method.as_deref(),
                    path: path.as_deref(),
                    follow,
                    limit,
                },
                format,
            )
            .await
        }

        Command::Allow(AllowArgs {
            project,
            service,
            entries,
            add,
            clear,
            list,
        }) => {
            commands::edge::allow(
                &client,
                &project,
                &service,
                commands::edge::AllowRequest {
                    entries: &entries,
                    add,
                    clear,
                    list,
                },
                format,
            )
            .await
        }

        Command::Ratelimit {
            project,
            service,
            rate,
        } => commands::edge::rate_limit(&client, &project, &service, &rate, format).await,

        Command::Encrypt {
            project,
            service,
            off,
        } => commands::manage::encryption(&client, &project, &service, !off).await,

        Command::Delete {
            project,
            service,
            confirm,
        } => commands::manage::delete(&client, &project, &service, confirm.as_deref()).await,

        Command::Workspace { command } => match command {
            WorkspaceCommand::List => commands::workspace::list(&client, format).await,
            WorkspaceCommand::SecondFactor { switch, workspace } => {
                commands::workspace::require_second_factor(
                    &client,
                    workspace.as_deref(),
                    switch == "on",
                    format,
                )
                .await
            }
            WorkspaceCommand::Members { workspace } => {
                commands::workspace::members(&client, workspace.as_deref(), format).await
            }
            WorkspaceCommand::Credits { workspace } => {
                commands::workspace::credits(&client, workspace.as_deref(), format).await
            }
            WorkspaceCommand::Invite {
                email,
                workspace,
                admin,
            } => commands::workspace::invite(&client, workspace.as_deref(), &email, admin).await,
            WorkspaceCommand::Revoke {
                invitation_id,
                workspace,
            } => commands::workspace::revoke(&client, workspace.as_deref(), &invitation_id).await,
            WorkspaceCommand::Remove { user_id, workspace } => {
                commands::workspace::remove(&client, workspace.as_deref(), &user_id).await
            }
        },
    }
}

fn connect(cli: &Cli) -> Result<ApiClient> {
    if let (Some(url), Some(token)) = (&cli.url, &cli.token) {
        return ApiClient::new(url, Some(token.clone()));
    }

    let config = Config::load().context("could not read the configuration")?;
    let (name, profile) = config.profile(cli.profile.as_deref())?;
    let url = cli.url.as_deref().unwrap_or(&profile.url);

    if cli.token.is_none() && !config::same_host(url, &profile.url) {
        return Err(exit::Refused::invalid(format!(
            "--url points at {} but the profile \"{name}\" was saved for {}: pass --token (or FUNDAIA_TOKEN) as well, or log in to that instance as its own profile",
            config::host_of(url),
            config::host_of(&profile.url)
        ))
        .into());
    }

    ApiClient::new(
        url,
        Some(cli.token.clone().unwrap_or_else(|| profile.token.clone())),
    )
}

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

    #[test]
    fn it_should_ask_the_registry_before_a_command_that_talks_to_an_instance() {
        assert!(asks_the_registry(&Command::Status));
    }

    #[test]
    fn it_should_not_ask_the_registry_to_write_a_completion_script() {
        assert!(!asks_the_registry(&Command::Completions {
            shell: clap_complete::Shell::Bash,
        }));
    }

    #[test]
    fn it_should_not_ask_the_registry_to_describe_itself() {
        assert!(!asks_the_registry(&Command::Schema));
    }

    #[test]
    fn it_should_read_fix_with_one_id_as_an_incident() {
        let cli = Cli::try_parse_from(["fundaia", "fix", "inc_1"]).unwrap();
        assert!(matches!(
            cli.command,
            Command::Fix { id: Some(id), command: None } if id == "inc_1"
        ));
    }

    #[test]
    fn it_should_read_fix_deployment_as_a_deployment() {
        let cli =
            Cli::try_parse_from(["fundaia", "fix", "deployment", "tienda", "api", "42"]).unwrap();
        assert!(matches!(
            cli.command,
            Command::Fix {
                command: Some(FixCommand::Deployment {
                    number: Some(42),
                    ..
                }),
                ..
            }
        ));
    }

    #[test]
    fn it_should_refuse_fix_with_nothing_to_fix() {
        assert!(Cli::try_parse_from(["fundaia", "fix"]).is_err());
    }

    #[test]
    fn it_should_still_read_logs_with_a_project_and_a_service() {
        assert!(Cli::try_parse_from(["fundaia", "logs", "tienda", "api", "-n", "50"]).is_ok());
    }

    #[test]
    fn it_should_read_the_environment_to_work_in_before_any_command() {
        let cli =
            Cli::try_parse_from(["fundaia", "--env", "staging", "services", "tienda"]).unwrap();
        assert_eq!(cli.environment.as_deref(), Some("staging"));
    }

    #[test]
    fn it_should_read_the_environment_to_work_in_after_the_command_too() {
        let cli = Cli::try_parse_from(["fundaia", "deploy", "tienda", "api", "--env", "staging"])
            .unwrap();
        assert_eq!(cli.environment.as_deref(), Some("staging"));
    }

    #[test]
    fn it_should_refuse_an_environment_both_copied_and_empty() {
        assert!(Cli::try_parse_from([
            "fundaia", "env", "new", "tienda", "staging", "--from", "qa", "--empty"
        ])
        .is_err());
    }

    #[test]
    fn it_should_read_how_long_a_new_environment_lives() {
        let cli = Cli::try_parse_from(["fundaia", "env", "new", "tienda", "demo", "--ttl", "7d"])
            .unwrap();
        assert!(matches!(
            cli.command,
            Command::Env { command: EnvCommand::New { ttl: Some(ttl), .. } } if ttl == "7d"
        ));
    }

    #[test]
    fn it_should_read_the_services_a_promotion_is_limited_to() {
        let cli = Cli::try_parse_from([
            "fundaia",
            "env",
            "promote",
            "tienda",
            "staging",
            "production",
            "api",
            "web",
        ])
        .unwrap();
        assert!(matches!(
            cli.command,
            Command::Env { command: EnvCommand::Promote(arguments) } if arguments.services == ["api", "web"]
        ));
    }

    #[test]
    fn it_should_read_a_promotion_that_only_shows_its_plan() {
        let cli = Cli::try_parse_from([
            "fundaia",
            "env",
            "promote",
            "tienda",
            "staging",
            "production",
            "--dry-run",
        ])
        .unwrap();
        assert!(matches!(
            cli.command,
            Command::Env { command: EnvCommand::Promote(arguments) } if arguments.dry_run
        ));
    }

    #[test]
    fn it_should_read_the_confirmation_of_a_data_copy() {
        let cli = Cli::try_parse_from([
            "fundaia",
            "env",
            "copy-data",
            "tienda",
            "production",
            "staging",
            "--confirm",
            "staging",
        ])
        .unwrap();
        assert!(matches!(
            cli.command,
            Command::Env { command: EnvCommand::CopyData(arguments) } if arguments.confirm.as_deref() == Some("staging")
        ));
    }

    #[test]
    fn it_should_read_an_expiry_taken_away() {
        let cli = Cli::try_parse_from(["fundaia", "env", "expire", "tienda", "staging", "never"])
            .unwrap();
        assert!(matches!(
            cli.command,
            Command::Env { command: EnvCommand::Expire { ttl, .. } } if ttl == "never"
        ));
    }

    #[test]
    fn it_should_read_the_two_environments_to_compare() {
        let cli =
            Cli::try_parse_from(["fundaia", "env", "diff", "tienda", "production", "staging"])
                .unwrap();
        assert!(matches!(
            cli.command,
            Command::Env { command: EnvCommand::Diff { from, to, .. } } if from == "production" && to == "staging"
        ));
    }

    #[test]
    fn it_should_read_where_a_service_is_copied_to() {
        let cli =
            Cli::try_parse_from(["fundaia", "env", "copy", "tienda", "api", "--to", "staging"])
                .unwrap();
        assert!(matches!(
            cli.command,
            Command::Env { command: EnvCommand::Copy { to, .. } } if to == "staging"
        ));
    }

    #[test]
    fn it_should_not_ask_the_registry_to_hand_over_the_guide() {
        assert!(!asks_the_registry(&Command::Guide));
    }

    #[test]
    fn it_should_read_the_repository_a_compose_file_builds_from() {
        let cli = Cli::try_parse_from([
            "fundaia",
            "import",
            "docker-compose.yml",
            "--repo",
            "pepito/tienda",
        ])
        .unwrap();
        assert!(matches!(
            cli.command,
            Command::Import(ImportArgs { repo: Some(repo), .. }) if repo == "pepito/tienda"
        ));
    }

    #[test]
    fn it_should_read_a_stack_added_to_a_project() {
        let cli = Cli::try_parse_from(["fundaia", "stack", "add", "tienda", "wordpress"]).unwrap();
        assert!(matches!(
            cli.command,
            Command::Stack { command: StackCommand::Add { stack, .. } } if stack == "wordpress"
        ));
    }

    #[test]
    fn it_should_read_the_name_of_a_duplicate() {
        let cli = Cli::try_parse_from([
            "fundaia",
            "duplicate",
            "tienda",
            "api",
            "api-2",
            "--no-deploy",
        ])
        .unwrap();
        assert!(matches!(
            cli.command,
            Command::Duplicate { name, no_deploy: true, .. } if name == "api-2"
        ));
    }
}