fundaia 0.26.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
//! The read-only half of the tool: everything that answers a question.
//!
//! Every one of these prints a table and nothing else. That is a rule rather
//! than a habit — the output of this tool is read by people and by scripts, and
//! a command that also prints a friendly sentence is a command whose second
//! line breaks `awk`.
//!
//! With `--json` each one prints the server's own DTOs back out instead, so a
//! program never has to parse a table that was laid out for eyes.

use anyhow::Result;
use owo_colors::OwoColorize;

use crate::api::client::ApiClient;
use crate::api::models::{Backup, CanvasNode, Domain, Volume};
use crate::output::{self, Format};
use crate::render::diff;
use crate::render::table::{truncate, Cell, Table};
use crate::render::theme;
use crate::render::time;
use crate::render::time::{epoch_millis, format_millis};

pub async fn status(client: &ApiClient, format: Format) -> Result<()> {
    // Concurrent because they are independent, and `status` is the command an
    // agent runs before every decision — the round trips should overlap.
    let (projects, version) = tokio::join!(client.projects(), client.version());
    let projects = projects?;
    // Best effort, and never fatal. An instance too old to answer `/api/version`
    // is exactly the case this line exists to surface, so failing to read it
    // must not take the rest of the screen down with it.
    let version = version.ok();

    if format.is_json() {
        output::emit(&serde_json::json!({
            "url": client.base(),
            "cli": env!("CARGO_PKG_VERSION"),
            "server": version,
            "projects": projects,
        }));
        return Ok(());
    }

    let services: u32 = projects.iter().map(|project| project.service_count).sum();
    let online: u32 = projects.iter().map(|project| project.online_count).sum();

    println!();
    println!("  {}", client.base().style(theme::strong()));

    if let Some(version) = version {
        let mine = env!("CARGO_PKG_VERSION");
        let note = if version.platform == mine {
            String::new()
        } else {
            format!(" · este binario es {mine}")
        };

        println!(
            "  {}{}",
            format!("servidor {}", version.platform).style(theme::muted()),
            note.style(theme::muted()),
        );
    }

    println!(
        "  {} proyectos · {} servicios · {} en marcha",
        projects.len().style(theme::strong()),
        services.style(theme::strong()),
        if online == services && services > 0 {
            format!("{}", online.style(theme::success()))
        } else if online == 0 && services > 0 {
            format!("{}", online.style(theme::danger()))
        } else {
            format!("{}", online.style(theme::warning()))
        },
    );
    println!();

    let mut table = Table::new(&["proyecto", "entorno", "servicios", "estado"]);

    for project in &projects {
        // The dots are the service states in creation order, which is the same
        // order the canvas lays them out — one glance says which one is red.
        let dots: String = project
            .services
            .iter()
            .map(|service| theme::state_dot(&service.state))
            .collect::<Vec<_>>()
            .join(" ");

        table.push(vec![
            Cell::styled(project.name.clone(), theme::strong()),
            Cell::styled(project.environment_name.clone(), theme::muted()),
            Cell::plain(format!(
                "{}/{}",
                project.online_count, project.service_count
            )),
            Cell::plain(dots),
        ]);
    }

    if table.is_empty() {
        println!(
            "  {}",
            "Todavía no hay ningún proyecto.".style(theme::muted())
        );
    } else {
        table.print();
    }
    println!();

    Ok(())
}

pub async fn projects(client: &ApiClient, format: Format) -> Result<()> {
    let projects = client.projects().await?;

    if format.is_json() {
        output::emit(&projects);
        return Ok(());
    }

    let mut table = Table::new(&["id", "nombre", "slug", "servicios"]);

    for project in &projects {
        table.push(vec![
            Cell::styled(project.id.clone(), theme::muted()),
            Cell::styled(project.name.clone(), theme::strong()),
            Cell::plain(project.slug.clone()),
            Cell::plain(format!(
                "{}/{}",
                project.online_count, project.service_count
            )),
        ]);
    }

    if table.is_empty() {
        println!("Todavía no hay ningún proyecto.");
        return Ok(());
    }

    table.print();
    Ok(())
}

pub async fn services(client: &ApiClient, project_reference: &str, format: Format) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let page = client.services(&project.id).await?;

    if format.is_json() {
        output::emit(&page);
        return Ok(());
    }

    let mut table = Table::new(&["servicio", "estado", "origen", "host", "depende de"]);

    for service in &page.services {
        // Named rather than by id: the arrow is for a person, and an id in a
        // dependency column is unreadable next to a name in the first one.
        let dependencies: Vec<String> = page
            .edges
            .iter()
            .filter(|edge| edge.from == service.id)
            .filter_map(|edge| page.services.iter().find(|target| target.id == edge.to))
            .map(|target| target.name.clone())
            .collect();

        table.push(vec![
            Cell::styled(service.name.clone(), theme::strong()),
            Cell::styled(
                format!(
                    "{} {}",
                    theme::state_dot(&service.state),
                    theme::state_word(&service.state)
                ),
                theme::state_style(&service.state),
            ),
            Cell::styled(
                service
                    .repo_full_name
                    .clone()
                    .or_else(|| service.brand.clone())
                    .unwrap_or_else(|| "—".to_owned()),
                theme::muted(),
            ),
            Cell::styled(
                service.host.clone().unwrap_or_else(|| "—".to_owned()),
                theme::muted(),
            ),
            Cell::plain(if dependencies.is_empty() {
                "—".to_owned()
            } else {
                dependencies.join(", ")
            }),
        ]);
    }

    if table.is_empty() {
        println!("`{}` todavía no tiene servicios.", project.name);
        return Ok(());
    }

    table.print();
    Ok(())
}

pub async fn service(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    format: Format,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let found = client.find_service(&project.id, service_reference).await?;
    let detail = client.service_detail(&found.id).await?;

    if format.is_json() {
        output::emit(&detail);
        return Ok(());
    }

    println!();
    println!(
        "  {} {} {}",
        theme::state_dot(&detail.environment.state),
        detail.service.name.style(theme::strong()),
        theme::state_word(&detail.environment.state)
            .style(theme::state_style(&detail.environment.state)),
    );
    println!(
        "  {} {}",
        "id".style(theme::muted()),
        detail.environment.id.style(theme::muted())
    );
    println!(
        "  {} {} MB · {} CPU · {}",
        "recursos".style(theme::muted()),
        detail.environment.memory_mb,
        detail.environment.cpus,
        if detail.environment.sleep_enabled {
            sleep_phrase(detail.environment.sleep_after_minutes)
        } else {
            "siempre despierto".to_owned()
        },
    );

    /*
     * What the platform read out of the repository, in one line.
     *
     * Everything here was read without running anything, so the endpoints carry
     * the file they came from in `evidence` — `fundaia capabilities` prints
     * those; this line is the glance.
     */
    if let Some(capabilities) = &detail.capabilities {
        let mut parts: Vec<String> = Vec::new();
        if let Some(framework) = &capabilities.framework {
            parts.push(match &capabilities.framework_version {
                Some(version) => format!("{framework} {version}"),
                None => framework.clone(),
            });
        }
        if let Some(port) = capabilities.declared_port {
            parts.push(format!(":{port}"));
        }
        for endpoint in capabilities.endpoints.iter().take(3) {
            parts.push(endpoint.path.clone());
        }
        if !parts.is_empty() {
            println!("  {} {}", "ofrece".style(theme::muted()), parts.join(" · "));
        }
    }

    // What is asked before a deployment replaces the container that is serving.
    println!(
        "  {} {}{}",
        "salud".style(theme::muted()),
        match &detail.environment.health_path {
            Some(path) => path.clone(),
            // The resolved probe, not the word on the column: `auto` is the
            // service's origin and its declared path deciding between the two,
            // and only the server can answer that.
            None => match detail.environment.health_probe_resolved.as_deref() {
                Some("tcp") => "el puerto acepta conexiones".to_owned(),
                Some("none") => "solo que siga en pie".to_owned(),
                _ => "/".to_owned(),
            },
        },
        // Only where there is a path to have been detected: the label describes
        // one, and beside "el puerto acepta conexiones" it describes nothing.
        match (
            detail.environment.health_path.as_deref(),
            detail.environment.health_path_origin.as_deref(),
        ) {
            (Some(_), Some("detected")) => " (detectada)".style(theme::muted()).to_string(),
            _ => String::new(),
        },
    );

    // Serving ones only. A summary is read as "where is this", and a hostname
    // that is switched off is not an answer to that.
    for domain in detail.domains.iter().filter(|domain| domain.enabled) {
        println!(
            "  {} {}",
            "host".style(theme::muted()),
            domain.url.style(theme::accent())
        );
    }

    // The resident one first: a service that is asleep still has a version
    // deployed, and saying nothing about it is how the summary used to answer
    // "what is on this service" with silence for most of them.
    if let Some(deployment) = detail
        .live_deployment
        .as_ref()
        .or(detail.active_deployment.as_ref())
    {
        println!(
            "  {} #{} {}",
            "desplegado".style(theme::muted()),
            deployment.number,
            deployment
                .commit_subject
                .clone()
                .unwrap_or_else(|| deployment.trigger.clone())
                .style(theme::muted()),
        );
    }

    println!();
    Ok(())
}

pub async fn history(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    limit: usize,
    format: Format,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let found = client.find_service(&project.id, service_reference).await?;
    let deployments = client.deployments(&found.id).await?;

    if format.is_json() {
        let limited: Vec<_> = deployments.iter().take(limit).collect();
        output::emit(&limited);
        return Ok(());
    }

    let mut table = Table::new(&["#", "estado", "motivo", "commit", "duración", "asunto"]);

    for deployment in deployments.iter().take(limit) {
        let duration = match (
            &deployment.finished_at,
            epoch_millis(&deployment.created_at),
        ) {
            (Some(finished), Some(created)) => epoch_millis(finished)
                .map(|end| format_millis(end - created))
                .unwrap_or_else(|| "—".to_owned()),
            _ => "—".to_owned(),
        };

        table.push(vec![
            Cell::plain(format!("{}", deployment.number)),
            Cell::styled(
                deployment.status.clone(),
                theme::deployment_status_style(&deployment.status),
            ),
            Cell::styled(deployment.trigger.clone(), theme::muted()),
            Cell::styled(
                deployment
                    .commit_sha
                    .as_ref()
                    .map(|sha| sha.chars().take(7).collect::<String>())
                    .unwrap_or_else(|| "—".to_owned()),
                theme::muted(),
            ),
            Cell::plain(duration),
            Cell::plain(truncate(
                deployment
                    .failure_message
                    .as_ref()
                    .or(deployment.commit_subject.as_ref())
                    .map(String::as_str)
                    .unwrap_or("—"),
                52,
            )),
        ]);
    }

    if table.is_empty() {
        println!("`{}` no se ha desplegado nunca.", found.name);
        return Ok(());
    }

    table.print();
    Ok(())
}

/// The code one commit changed, the way `git show` would put it.
///
/// Without a hash it takes the one the newest deployment shipped — not simply
/// the newest deployment, which after a restart carries no commit of its own
/// and would answer that there is nothing to look at.
pub async fn commit(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    sha: Option<String>,
    file: Option<String>,
    stat: bool,
    format: Format,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let found = client.find_service(&project.id, service_reference).await?;

    let sha = match sha {
        Some(given) => given,
        None => {
            let deployments = client.deployments(&found.id).await?;
            let Some(shipped) = deployments.iter().find_map(|one| one.commit_sha.clone()) else {
                println!("`{}` no ha desplegado nunca un commit.", found.name);
                return Ok(());
            };
            shipped
        }
    };

    let answer = client.commit_change(&found.id, &sha).await?;

    if format.is_json() {
        output::emit(&answer);
        return Ok(());
    }

    if let Some(unavailable) = &answer.unavailable {
        println!("{}", unavailable.message);
        return Ok(());
    }

    let Some(change) = &answer.commit else {
        println!("GitHub no ha dicho nada de ese commit.");
        return Ok(());
    };

    print_commit_heading(change);

    // One file, when that is what was asked for: a commit that touches sixty
    // files is unreadable in a terminal, and the path is how somebody narrows
    // it after reading the list this printed the first time.
    if let Some(path) = &file {
        let Some(only) = change.files.iter().find(|one| &one.path == path) else {
            println!("`{path}` no está entre los ficheros de este commit.");
            return Ok(());
        };
        diff::print_file(only);
        return Ok(());
    }

    let mut table = Table::new(&["estado", "", "+", "−", "fichero"]);
    for one in &change.files {
        table.push(vec![
            Cell::plain(diff::status_word(&one.status).to_owned()),
            Cell::plain(diff::proportion(one.additions, one.deletions)),
            Cell::styled(format!("{}", one.additions), theme::success()),
            Cell::styled(format!("{}", one.deletions), theme::danger()),
            Cell::plain(truncate(&one.path, 64)),
        ]);
    }
    table.print();

    if change.truncated {
        println!(
            "{}",
            "GitHub solo lista los 300 primeros ficheros de un commit; hay más."
                .style(theme::warning())
        );
    }

    if !stat {
        for one in &change.files {
            diff::print_file(one);
        }
    }

    Ok(())
}

fn print_commit_heading(change: &crate::api::models::CommitChange) {
    let author = change
        .author
        .as_ref()
        .map(|account| account.login.clone())
        .or_else(|| change.author_name.clone())
        .unwrap_or_else(|| "—".to_owned());

    println!(
        "{} {}",
        change
            .sha
            .chars()
            .take(7)
            .collect::<String>()
            .style(theme::accent()),
        change.subject.clone().style(theme::strong())
    );
    println!(
        "{}",
        format!(
            "{author} · {} · {} ficheros · +{} −{}",
            change.repo_full_name,
            change.files.len(),
            change.additions,
            change.deletions
        )
        .style(theme::muted())
    );
    if let Some(url) = &change.html_url {
        println!("{}", url.clone().style(theme::muted()));
    }
    println!();
}

pub async fn metrics(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    minutes: u32,
    format: Format,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let found = client.find_service(&project.id, service_reference).await?;
    let samples = client.usage(&found.id, minutes).await?;

    if format.is_json() {
        output::emit(&samples);
        return Ok(());
    }

    let Some(latest) = samples.last() else {
        println!("Todavía no hay medidas de `{}`.", found.name);
        return Ok(());
    };

    // `checked_div` rather than a guard: a limit of zero means the runtime never
    // reported one, and "no percentage" is honestly zero rather than a division
    // somebody has to remember to protect.
    let share = (latest.memory_bytes * 100)
        .checked_div(latest.memory_limit_bytes)
        .unwrap_or(0) as u32;

    println!();
    println!(
        "  {} {} mCPU",
        "cpu    ".style(theme::muted()),
        latest.cpu_millicores.style(theme::strong())
    );
    println!(
        "  {} {} MB de {} MB",
        "memoria".style(theme::muted()),
        (latest.memory_bytes / 1_000_000).style(theme::strong()),
        latest.memory_limit_bytes / 1_000_000,
    );
    println!("  {} {}", "límite ".style(theme::muted()), bar(share));
    println!();

    // The sparkline is the point of asking for a window rather than a reading:
    // one number says how it is, forty say where it is going.
    let cpu: Vec<u64> = samples
        .iter()
        .map(|sample| u64::from(sample.cpu_millicores))
        .collect();
    let memory: Vec<u64> = samples
        .iter()
        .map(|sample| sample.memory_bytes / 1_000_000)
        .collect();

    println!("  {} {}", "cpu    ".style(theme::muted()), sparkline(&cpu));
    println!(
        "  {} {}",
        "memoria".style(theme::muted()),
        sparkline(&memory)
    );
    println!(
        "  {}",
        format!("{} medidas de los últimos {minutes} minutos", samples.len()).style(theme::muted()),
    );
    println!();

    Ok(())
}

/// Money, at the precision the figure deserves.
///
/// A prompt costs about three thousandths of a dollar, so two decimals print an
/// afternoon's work as `$0.00` — which reads as "free" rather than as "not
/// much". Under a cent it shows four; above it, the two everybody expects.
pub fn format_money(micros: u64) -> String {
    if micros == 0 {
        return "$0".to_string();
    }

    let dollars = micros as f64 / 1e6;
    if dollars < 0.01 {
        format!("${dollars:.4}")
    } else {
        format!("${dollars:.2}")
    }
}

pub fn format_tokens(value: u64) -> String {
    if value >= 1_000_000 {
        format!("{:.1} M", value as f64 / 1e6)
    } else if value >= 1000 {
        format!("{} k", value / 1000)
    } else {
        value.to_string()
    }
}

/// What an agent component has spent, in tokens and in dollars.
///
/// The same figures the consumption tab draws, from the same route: a bill read
/// from a terminal and a bill read from a browser must not be able to disagree.
pub async fn consumption(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    range: &str,
    format: Format,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let found = client.find_service(&project.id, service_reference).await?;
    let page = client.consumption(&found.id, range).await?;

    if format.is_json() {
        output::emit(&page);
        return Ok(());
    }

    if !page.available {
        println!("`{}` no lleva cuenta de lo que gasta.", found.name);
        return Ok(());
    }

    println!();
    println!(
        "  {} {}",
        format!("gasto ({range})").style(theme::muted()),
        format_money(page.totals.cost_micros).style(theme::strong()),
    );
    println!(
        "  {} {}",
        "gasto total ".style(theme::muted()),
        format_money(page.lifetime.cost_micros).style(theme::strong()),
    );
    println!(
        "  {} {} ({} de media)",
        "peticiones  ".style(theme::muted()),
        page.totals.prompts.style(theme::strong()),
        format_money(page.totals.average_cost_micros),
    );
    println!(
        "  {} {}",
        "tokens      ".style(theme::muted()),
        format_tokens(page.totals.tokens.total()).style(theme::strong()),
    );
    println!();

    let mut table = Table::new(&["cuándo", "modelo", "tokens", "tardó", "coste"]);

    for prompt in &page.recent {
        table.push(vec![
            Cell::plain(time::relative_time(&prompt.at).unwrap_or_else(|| "—".to_string())),
            Cell::styled(truncate(&prompt.model, 24), theme::muted()),
            Cell::plain(format_tokens(prompt.tokens.total())),
            Cell::styled(format_millis(prompt.duration_ms as i64), theme::muted()),
            Cell::styled(format_money(prompt.cost_micros), theme::strong()),
        ]);
    }

    if table.is_empty() {
        println!(
            "  {}",
            format!("`{}` todavía no ha contestado nada.", found.name).style(theme::muted())
        );
    } else {
        table.print();
    }
    println!();

    Ok(())
}

/// What an agent has been asked to do, and what it is doing right now.
///
/// The sibling of `consumption` above: that one answers what the answered
/// prompts cost, and this one answers what was asked and how much of it worked
/// — the question a component that looks stuck or overloaded actually needs.
pub async fn agent_activity(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    range: &str,
    outcome: Option<&str>,
    format: Format,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let found = client.find_service(&project.id, service_reference).await?;
    let page = client.agent_activity(&found.id, range, outcome).await?;

    if format.is_json() {
        output::emit(&page);
        return Ok(());
    }

    if !page.available {
        println!("`{}` no lleva cuenta de lo que le piden.", found.name);
        return Ok(());
    }

    println!();
    println!(
        "  {} {} ({} contestadas, {} fallidas, {} rechazadas)",
        format!("peticiones ({range})").style(theme::muted()),
        page.requests.style(theme::strong()),
        page.counts.answered,
        page.counts.failed,
        page.counts.rejected,
    );
    println!(
        "  {} {}",
        "contestadas       ".style(theme::muted()),
        format!("{}%", page.answered_percent).style(theme::strong()),
    );

    /*
     * A container that could not be asked says so, rather than being drawn as
     * an idle one. They look identical in every table below and mean opposite
     * things: one agent is free and the other cannot be reached at all.
     */
    match &page.live {
        Some(live) => {
            println!(
                "  {} {} en curso, {} en cola (de {} a la vez, {} en espera)",
                "ahora mismo       ".style(theme::muted()),
                live.running.style(theme::strong()),
                live.queued,
                live.max_concurrent,
                live.max_queued,
            );

            for request in &live.requests {
                let state = if request.started_at.is_some() {
                    "en curso"
                } else {
                    "en cola"
                };
                println!(
                    "    {} {}",
                    format!("· {state}").style(theme::muted()),
                    truncate(&first_line(&request.prompt_excerpt), 64),
                );
            }
        }
        None => println!(
            "  {} {}",
            "ahora mismo       ".style(theme::muted()),
            "el contenedor no está respondiendo".style(theme::muted()),
        ),
    }
    println!();

    /*
     * No trace gutter and no reserved column for the excerpt: a terminal is
     * narrower than the panel and the prompt is what somebody is scanning for,
     * so it takes whatever width is left.
     */
    let mut table = Table::new(&["cuándo", "resultado", "vía", "prompt", "tardó", "coste"]);

    for request in &page.entries {
        table.push(vec![
            Cell::plain(time::relative_time(&request.at).unwrap_or_else(|| "—".to_string())),
            Cell::styled(outcome_label(request), outcome_style(&request.outcome)),
            Cell::styled(truncate(&request.route, 8), theme::muted()),
            Cell::plain(truncate(&first_line(&request.prompt_excerpt), 48)),
            Cell::styled(format_millis(request.duration_ms as i64), theme::muted()),
            Cell::styled(format_money(request.cost_micros), theme::strong()),
        ]);
    }

    if table.is_empty() {
        println!(
            "  {}",
            format!("A `{}` no le han pedido nada todavía.", found.name).style(theme::muted())
        );
    } else {
        table.print();
    }
    println!();

    Ok(())
}

/// The outcome, carrying why when there is a why.
///
/// `rechazada · busy` rather than two columns: the reason only exists for two of
/// the three outcomes, and a column that is empty two thirds of the time is
/// width taken from the prompt beside it.
fn outcome_label(request: &crate::api::models::AgentRequest) -> String {
    let word = match request.outcome.as_str() {
        "answered" => "contestada",
        "failed" => "falló",
        "rejected" => "rechazada",
        other => other,
    };

    match &request.detail {
        Some(detail) if !detail.is_empty() => format!("{word} · {detail}"),
        _ => word.to_string(),
    }
}

fn outcome_style(outcome: &str) -> owo_colors::Style {
    match outcome {
        "failed" => theme::danger(),
        "rejected" => theme::warning(),
        _ => theme::muted(),
    }
}

/// The first line of a prompt, because a table row is one line.
///
/// A prompt pasted from an editor carries its newlines, and printing them into
/// a cell tears the table apart — every row after it is one column out.
fn first_line(excerpt: &str) -> String {
    match excerpt.lines().next() {
        Some(line) if !line.trim().is_empty() => line.trim().to_string(),
        _ => "—".to_string(),
    }
}

/// A meter, in twenty characters.
fn bar(percent: u32) -> String {
    let filled = (percent.min(100) as usize) / 5;
    let style = if percent > 90 {
        theme::danger()
    } else if percent > 70 {
        theme::warning()
    } else {
        theme::success()
    };

    format!(
        "{}{} {percent}%",
        "█".repeat(filled).style(style),
        "░".repeat(20 - filled).style(theme::muted()),
    )
}

/// Braille-free sparkline: eight block heights, scaled to the largest reading.
///
/// Scaled to the window rather than to the limit, because the question a
/// sparkline answers is "is this changing", and a series pinned to the bottom
/// of a 512 MB axis answers nothing.
pub fn sparkline(values: &[u64]) -> String {
    const BLOCKS: [char; 8] = ['▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];

    let Some(highest) = values.iter().copied().max() else {
        return String::new();
    };
    if highest == 0 {
        return BLOCKS[0].to_string().repeat(values.len());
    }

    values
        .iter()
        .map(|value| {
            let index = ((value * 7) / highest) as usize;
            BLOCKS[index.min(7)]
        })
        .collect()
}

pub async fn variables(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    reveal: bool,
    format: Format,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let found = client.find_service(&project.id, service_reference).await?;
    let variables = client.variables(&found.id).await?;

    if format.is_json() {
        // The DTO plus, under `--reveal`, a `value` the server never sends on
        // the list — each reveal is its own audited request, same as the table.
        let mut entries = Vec::with_capacity(variables.len());
        for variable in &variables {
            let mut entry = serde_json::to_value(variable)?;
            if reveal && variable.kind == "secret" && !variable.write_only && !variable.is_sealed()
            {
                if let Ok(value) = client.reveal_variable(&variable.id).await {
                    entry["value"] = value.into();
                }
            }
            entries.push(entry);
        }
        output::emit(&entries);
        return Ok(());
    }

    let mut table = Table::new(&["clave", "tipo", "valor"]);

    for variable in &variables {
        // Revealing is per variable and audited server-side, so it is one call
        // each rather than a bulk endpoint that would log one access for many.
        // A sealed one is skipped rather than attempted: the server would refuse
        // it, and a row of failed requests is a worse way to say "no".
        let value =
            if reveal && variable.kind == "secret" && !variable.write_only && !variable.is_sealed()
            {
                client
                    .reveal_variable(&variable.id)
                    .await
                    .unwrap_or_else(|_| "—".to_owned())
            } else if variable.is_sealed() {
                "sellada · solo se puede borrar".to_owned()
            } else {
                variable
                    .preview
                    .clone()
                    .unwrap_or_else(|| "••••••••".to_owned())
            };

        let kind = if variable.is_sealed() {
            "sellada".to_owned()
        } else {
            variable.kind.clone()
        };

        table.push(vec![
            Cell::styled(variable.key.clone(), theme::strong()),
            Cell::styled(
                kind,
                match (variable.is_sealed(), variable.kind.as_str()) {
                    (true, _) => theme::warning(),
                    (false, "reference") => theme::accent(),
                    (false, "secret") => theme::warning(),
                    _ => theme::muted(),
                },
            ),
            Cell::plain(truncate(&value, 60)),
        ]);
    }

    if table.is_empty() {
        println!("`{}` no define ninguna variable.", found.name);
        return Ok(());
    }

    table.print();
    Ok(())
}

pub async fn domains(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    format: Format,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let found = client.find_service(&project.id, service_reference).await?;
    let domains = client.domains(&found.id).await?;

    if format.is_json() {
        output::emit(&domains);
        return Ok(());
    }

    let mut table = Table::new(&["host", "tipo", "estado", "id"]);

    for domain in &domains {
        // A disabled hostname is not `failed` and not `pending`: nothing went
        // wrong with it, the service was taken off the internet. Painting its
        // DNS state would say the opposite in red.
        let (state, style) = if domain.enabled {
            (
                domain.state.clone(),
                match domain.state.as_str() {
                    "active" => theme::success(),
                    "failed" => theme::danger(),
                    _ => theme::warning(),
                },
            )
        } else {
            ("desactivado".to_string(), theme::muted())
        };

        table.push(vec![
            Cell::styled(
                domain.host.clone(),
                if domain.enabled {
                    theme::strong()
                } else {
                    theme::muted()
                },
            ),
            Cell::styled(domain.kind.clone(), theme::muted()),
            Cell::styled(state, style),
            Cell::styled(domain.id.clone(), theme::muted()),
        ]);
    }

    if table.is_empty() {
        println!("`{}` no responde en ningún host.", found.name);
        return Ok(());
    }

    table.print();

    // Under the table rather than in it, because a domain still being set up
    // needs several lines and the other rows need none: folding them into
    // columns would widen every row for the sake of one.
    for domain in &domains {
        if domain.enabled && domain.state != "active" {
            print_domain_progress(domain);
        }
    }

    if domains.iter().all(|domain| !domain.enabled) {
        println!();
        println!(
            "  {}",
            "El servicio es privado. Sus dominios vuelven con `fundaia expose`."
                .style(theme::muted()),
        );
    }

    Ok(())
}

/// Asks about one custom domain now, and prints where it got to.
///
/// It exists because the platform's backoff is right about the average case and
/// wrong about the only one anybody types this in: somebody who has just saved
/// a record knows something the schedule does not, and five minutes is a long
/// time to wonder whether you typed it correctly.
pub async fn verify_domain(client: &ApiClient, domain_id: &str, format: Format) -> Result<()> {
    let domain = client.verify_domain(domain_id).await?;

    if format.is_json() {
        output::emit(&domain);
        return Ok(());
    }

    if domain.steps.is_none() {
        println!(
            "{} no es un dominio personalizado: no hay nada que comprobar.",
            domain.host.style(theme::strong()),
        );
        return Ok(());
    }

    print_domain_progress(&domain);

    if domain.state == "active" {
        println!();
        println!(
            "  {} {}",
            "✓".style(theme::success()),
            domain.url.clone().style(theme::accent())
        );
    }

    Ok(())
}

/// A custom domain's three steps, and the record still to be created.
///
/// It reads top to bottom rather than as a bar, because a terminal that is
/// re-run rather than watched has no animation to carry the difference — and
/// what somebody needs from this is the one line saying what to do next, not a
/// picture of how far along it is.
fn print_domain_progress(domain: &Domain) {
    let Some(steps) = domain.steps.as_ref() else {
        return;
    };

    println!();
    println!("  {}", domain.host.style(theme::strong()));

    for step in steps {
        let (mark, style) = match step.state.as_str() {
            "done" => ("✓", theme::success()),
            "working" => ("·", theme::accent()),
            "blocked" => ("✗", theme::danger()),
            _ => ("·", theme::muted()),
        };

        println!(
            "    {} {}",
            mark.style(style),
            step.detail.clone().style(if step.state == "done" {
                theme::muted()
            } else {
                theme::strong()
            }),
        );
    }

    // Only while it is the thing being waited for: a record printed under a
    // domain that already resolves is an invitation to change something that
    // works.
    let waiting_on_dns = steps.first().is_some_and(|step| step.state != "done");
    if let (true, Some(target)) = (waiting_on_dns, domain.cname_target.as_ref()) {
        println!();
        println!(
            "    {}  CNAME   {}   {}",
            "→".style(theme::muted()),
            domain.dns_label.clone().unwrap_or_else(|| "@".to_string()),
            target.clone().style(theme::accent()),
        );
    }
}

/// The persistent directories a service has, and whether the running container
/// actually has them.
///
/// `mounted` is the column worth reading: attaching a volume does not restart
/// anything, so a directory added five minutes ago is not in the container
/// until the next deployment — and a table that only listed names would hide
/// exactly that.
pub async fn volumes(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    format: Format,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let found = client.find_service(&project.id, service_reference).await?;
    let volumes = client.volumes(&found.id).await?;

    if format.is_json() {
        output::emit(&volumes);
        return Ok(());
    }

    let mut table = Table::new(&["ruta", "ocupación", "montado", "id"]);

    for volume in &volumes {
        table.push(vec![
            Cell::styled(volume.mount_path.clone(), theme::strong()),
            occupancy_cell(volume),
            Cell::styled(
                if volume.mounted {
                    "sí"
                } else {
                    "en el próximo despliegue"
                }
                .to_owned(),
                if volume.mounted {
                    theme::success()
                } else {
                    theme::warning()
                },
            ),
            Cell::styled(volume.id.clone(), theme::muted()),
        ]);
    }

    if table.is_empty() {
        println!("`{}` no tiene ningún volumen.", found.name);
        return Ok(());
    }

    table.print();
    Ok(())
}

/// How full a volume is, coloured by how close it is to what the plan reserves.
///
/// The generated name is what this column replaced, and losing it costs nothing:
/// `api-var-lib-postgresql-data` is derived from the two columns beside it and
/// was never the reason anybody ran this command. What it makes room for is the
/// figure that decides whether somebody has to do something today.
///
/// A volume the platform has never measured says so rather than showing 0 %:
/// `used_bytes` has been a column since the first migration and defaulted to
/// zero for a year, so a percentage with no measurement behind it would be a
/// confident claim that a full database is empty.
fn occupancy_cell(volume: &Volume) -> Cell {
    let Some(percent) = volume.occupancy_percent else {
        return Cell::styled("sin medir".to_owned(), theme::muted());
    };

    let style = match percent {
        0..=79 => theme::muted(),
        80..=99 => theme::warning(),
        _ => theme::danger(),
    };

    Cell::styled(
        format!("{percent} % de {}", format_megabytes(volume.size_limit_mb)),
        style,
    )
}

/// Megabytes as somebody reads them, mirroring `formatMb` on the server.
fn format_megabytes(megabytes: u64) -> String {
    if megabytes >= 1024 && megabytes % 1024 == 0 {
        format!("{} GB", megabytes / 1024)
    } else {
        format!("{megabytes} MB")
    }
}

/// The Containerfile a service builds with.
///
/// Printed on stdout with nothing around it when `--plain` is given, because
/// the useful thing to do with it is `> Containerfile`, edit, and hand it back
/// to `recipe edit`.
pub async fn recipe(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    plain: bool,
    format: Format,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let found = client.find_service(&project.id, service_reference).await?;
    let recipe = client.recipe(&found.id).await?;

    // `--plain` beats `--json`: it exists to be redirected into a file, and a
    // Containerfile wrapped in a JSON string is not one.
    if format.is_json() && !plain {
        output::emit(&recipe);
        return Ok(());
    }

    if plain {
        print!("{}", recipe.containerfile);
        return Ok(());
    }

    println!();
    println!(
        "  {}  {}",
        recipe.builder.style(theme::strong()),
        match recipe.source.as_str() {
            "edited" => "editado a mano — no se vuelve a generar".to_owned(),
            _ => "generado".to_owned(),
        }
        .style(theme::muted()),
    );

    if let Some(port) = recipe.exposed_port {
        println!("  {}", format!("puerto {port}").style(theme::muted()));
    }

    for warning in &recipe.warnings {
        println!("  {} {}", "!".style(theme::warning()), warning);
    }

    println!();
    for line in recipe.containerfile.lines() {
        println!("  {line}");
    }
    println!();

    for note in &recipe.notes {
        println!("  {}", note.style(theme::muted()));
    }

    Ok(())
}

/// A service's copies, newest first.
///
/// The size and the age are the two columns somebody scans for, and `guardada`
/// is the third: a locked copy is the one that will still be there next month,
/// and that is exactly what you want to know before deleting anything.
pub async fn backups(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    format: Format,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let found = client.find_service(&project.id, service_reference).await?;
    let page = client.backups(&found.id).await?;

    if format.is_json() {
        output::emit(&page);
        return Ok(());
    }

    if !page.supported {
        println!(
            "`{}` no tiene volumen, así que no hay nada que copiar.",
            found.name
        );
        return Ok(());
    }

    println!();
    println!(
        "  {} {}",
        "programación".style(theme::muted()),
        if page.schedules.is_empty() {
            "ninguna — este servicio no se copia solo".to_owned()
        } else {
            page.schedules.join(", ")
        }
        .style(theme::strong()),
    );
    if let Some(next) = &page.next_at {
        println!(
            "  {} {}",
            "siguiente".style(theme::muted()),
            next.style(theme::muted())
        );
    }
    // The one line to read before trusting the table: a copy on the same disk
    // as the volume dies with it.
    println!(
        "  {} {}",
        "remoto".style(theme::muted()),
        match &page.remote {
            Some(remote) => remote.clone(),
            None => "ninguno — las copias están solo en esta máquina".to_owned(),
        }
        .style(theme::strong()),
    );
    println!();

    // The column only exists when there is somewhere for a copy to go; without
    // a remote every row would say `no`, which is the line above said once.
    let headers: Vec<&str> = if page.remote.is_some() {
        vec!["id", "origen", "tamaño", "estado", "remoto", "hecha"]
    } else {
        vec!["id", "origen", "tamaño", "estado", "hecha"]
    };
    let mut table = Table::new(&headers);

    for backup in &page.backups {
        let mut row = vec![
            Cell::styled(backup.id.clone(), theme::muted()),
            Cell::plain(match &backup.schedule {
                Some(schedule) => schedule.clone(),
                None => "a mano".to_owned(),
            }),
            Cell::plain(human_size(backup.size_bytes)),
            Cell::styled(
                if backup.locked {
                    format!("{} · guardada", backup.status)
                } else {
                    backup.status.clone()
                },
                match backup.status.as_str() {
                    "ready" => theme::success(),
                    "failed" => theme::danger(),
                    _ => theme::warning(),
                },
            ),
        ];
        if page.remote.is_some() {
            row.push(replication_cell(backup));
        }
        row.push(Cell::styled(backup.created_at.clone(), theme::muted()));
        table.push(row);
    }

    if table.is_empty() {
        println!("Todavía no hay ninguna copia de `{}`.", found.name);
        return Ok(());
    }

    table.print();
    Ok(())
}

/// Whether a copy also left the machine: `sí`, `falló` with the reason on the
/// row's error, or `no` for one the hourly sweep has not reached yet.
fn replication_cell(backup: &Backup) -> Cell {
    match (&backup.replicated_at, &backup.replication_error) {
        (Some(_), _) => Cell::styled("sí", theme::success()),
        (None, Some(_)) => Cell::styled("falló", theme::danger()),
        (None, None) => Cell::styled("no", theme::muted()),
    }
}

/// Bytes as a person reads them. Two significant figures is all a size column needs.
fn human_size(bytes: u64) -> String {
    const UNITS: [&str; 4] = ["B", "KB", "MB", "GB"];
    let mut size = bytes as f64;
    let mut unit = 0;

    while size >= 1024.0 && unit < UNITS.len() - 1 {
        size /= 1024.0;
        unit += 1;
    }

    if unit == 0 {
        format!("{bytes} B")
    } else {
        format!("{size:.1} {}", UNITS[unit])
    }
}

/// What has been done to a project, newest first.
///
/// The terminal half of the panel on the canvas, from the same endpoint and the
/// same sentences — `describeActivity` runs on the server precisely so a history
/// read here and one read in a browser cannot disagree about what happened.
///
/// It covers both surfaces because the recording does: every write goes through
/// a service that both the web and this tool call, so a variable changed from a
/// terminal appears in the panel and a deployment started from the panel appears
/// here, with nobody having had to instrument either one twice.
pub async fn activity(
    client: &ApiClient,
    project_reference: &str,
    limit: usize,
    format: Format,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let entries = client.activity(&project.id, limit).await?;

    if format.is_json() {
        output::emit(&entries);
        return Ok(());
    }

    if entries.is_empty() {
        println!("Todavía no se ha hecho nada en `{}`.", project.name);
        return Ok(());
    }

    println!();
    let mut table = Table::new(&["cuándo", "quién", "qué"]);

    for entry in &entries {
        table.push(vec![
            Cell::styled(
                time::relative_time(&entry.at).unwrap_or_else(|| "—".to_string()),
                theme::muted(),
            ),
            Cell::styled(
                entry
                    .actor
                    .display_name
                    .clone()
                    .unwrap_or_else(|| entry.actor.id.clone()),
                theme::strong(),
            ),
            Cell::plain(entry.summary.clone()),
        ]);
    }

    table.print();
    println!();
    Ok(())
}

/// The file a load balancer or an API gateway is configured with.
pub async fn service_config(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    plain: bool,
    format: Format,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let found = client.find_service(&project.id, service_reference).await?;
    let page = client.service_config(&found.id).await?;

    // `--plain` beats `--json`, for the reason `recipe` gives: it exists to be
    // redirected into a file, and a YAML document inside a JSON string is not one.
    if format.is_json() && !plain {
        output::emit(&page);
        return Ok(());
    }

    if plain {
        print!("{}", page.config.content);
        return Ok(());
    }

    println!();
    println!(
        "  {}  {}",
        page.config.container_path.style(theme::strong()),
        match page.config.source.as_str() {
            "edited" => "editado a mano — el formulario ya no lo sobrescribe".to_owned(),
            _ => "generado desde el formulario".to_owned(),
        }
        .style(theme::muted()),
    );

    // The file is left exactly as it was: rewriting it because a service was
    // deleted is the silent regeneration this contract exists to prevent.
    if !page.stale_targets.is_empty() {
        println!(
            "  {} {} apuntan a un servicio que ya no existe",
            "!".style(theme::warning()),
            page.stale_targets.len(),
        );
    }

    for warning in &page.config.warnings {
        println!("  {} {}", "!".style(theme::warning()), warning);
    }

    println!();
    for line in page.config.content.lines() {
        println!("  {line}");
    }
    println!();
    Ok(())
}

/// What a service turned out to offer, with the file each answer came from.
pub async fn capabilities(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    format: Format,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let found = client.find_service(&project.id, service_reference).await?;
    let detail = client.service_detail(&found.id).await?;

    let Some(capabilities) = detail.capabilities else {
        if format.is_json() {
            output::emit(&serde_json::Value::Null);
            return Ok(());
        }
        println!("\n  Todavía no se ha leído este repositorio.\n");
        return Ok(());
    };

    if format.is_json() {
        output::emit(&capabilities);
        return Ok(());
    }

    println!();
    if let Some(framework) = &capabilities.framework {
        println!(
            "  {} {}{}",
            "framework".style(theme::muted()),
            framework,
            match &capabilities.framework_version {
                Some(version) => format!(" {version}"),
                None => String::new(),
            },
        );
    }
    if let Some(port) = capabilities.declared_port {
        println!("  {} {port}", "puerto".style(theme::muted()));
    }

    /*
     * Every endpoint carries the file it was read out of.
     *
     * All of this is a reading of source rather than an answer from an API, and
     * a guess with no provenance is a guess nobody can check.
     */
    for endpoint in &capabilities.endpoints {
        println!(
            "  {}  {}  {}",
            endpoint.path.style(theme::accent()),
            endpoint.kind.style(theme::muted()),
            endpoint.evidence.style(theme::muted()),
        );
    }

    if capabilities.shallow {
        println!(
            "\n  {}",
            "leído sin descargar el repositorio; el próximo despliegue mirará dentro del código"
                .style(theme::muted())
        );
    }
    println!();
    Ok(())
}

/// Who has been getting into this account, and from where.
///
/// The failed attempts are in the list and that is the point of it: a
/// successful sign-in nobody recognises is normally preceded by attempts nobody
/// recognises, and a history that showed only what worked would hide the half
/// worth reading. The address is printed in full for the same reason — "was
/// that me?" is answered by recognising a place, and a masked one answers
/// nothing.
pub async fn sign_ins(client: &ApiClient, limit: usize, format: Format) -> Result<()> {
    let entries = client.sign_ins(limit).await?;

    if format.is_json() {
        output::emit(&entries);
        return Ok(());
    }

    if entries.is_empty() {
        println!("Todavía no hay ningún acceso registrado.");
        return Ok(());
    }

    println!();
    let mut table = Table::new(&["cuándo", "cómo", "resultado", "desde", "dispositivo"]);

    for entry in &entries {
        table.push(vec![
            Cell::styled(
                time::relative_time(&entry.at).unwrap_or_else(|| "—".to_string()),
                theme::muted(),
            ),
            Cell::plain(sign_in_method(&entry.method)),
            Cell::styled(
                sign_in_outcome(&entry.outcome),
                match entry.outcome.as_str() {
                    "succeeded" => theme::success(),
                    "pending" => theme::muted(),
                    "refused" => theme::warning(),
                    _ => theme::danger(),
                },
            ),
            Cell::plain(entry.client_address.clone()),
            Cell::styled(
                entry.device.clone().unwrap_or_else(|| "—".to_string()),
                theme::muted(),
            ),
        ]);
    }

    table.print();
    println!();
    Ok(())
}

/// The sessions open right now, which is a different question from the history.
pub async fn auth_sessions(client: &ApiClient, format: Format) -> Result<()> {
    let sessions = client.auth_sessions().await?;

    if format.is_json() {
        output::emit(&sessions);
        return Ok(());
    }

    if sessions.is_empty() {
        println!("No hay ninguna sesión abierta.");
        return Ok(());
    }

    println!();
    let mut table = Table::new(&["id", "dispositivo", "desde", "activa", ""]);

    for session in &sessions {
        table.push(vec![
            Cell::styled(
                session.id.chars().take(12).collect::<String>(),
                theme::muted(),
            ),
            Cell::plain(session.device.clone().unwrap_or_else(|| "—".to_string())),
            Cell::plain(
                session
                    .client_address
                    .clone()
                    .unwrap_or_else(|| "—".to_string()),
            ),
            Cell::styled(
                time::relative_time(&session.last_seen_at).unwrap_or_else(|| "—".to_string()),
                theme::muted(),
            ),
            Cell::styled(
                if session.current {
                    "esta".to_string()
                } else if session.pending {
                    "sin verificar".to_string()
                } else {
                    String::new()
                },
                theme::accent(),
            ),
        ]);
    }

    table.print();
    println!();
    Ok(())
}

/// The wire's word for a method, in the one this tool prints.
pub fn sign_in_method(method: &str) -> String {
    match method {
        "github" => "GitHub",
        "passkey" => "passkey",
        "totp" => "código",
        "recovery-code" => "recuperación",
        "api-token" => "token",
        "cli-approval" => "terminal",
        other => other,
    }
    .to_string()
}

/// Unrecognised values fall through as themselves rather than as "desconocido":
/// this crate ships on its own schedule, so the server will one day record an
/// outcome this binary predates, and the raw word is more use than a shrug.
pub fn sign_in_outcome(outcome: &str) -> String {
    match outcome {
        "succeeded" => "entró",
        "pending" => "a medias",
        "refused" => "rechazado",
        "failed" => "falló",
        other => other,
    }
    .to_string()
}

/// What the platform can read of a service's repository, and who is being asked.
///
/// A service whose deployments die at the checkout with a 403 about write access
/// is this and not a broken build: the repository belongs to another account and
/// nobody has granted it. The states are the platform's own words — `pending` is
/// *we have nobody to write to*, which is the one that asks something of whoever
/// runs this.
pub async fn repository_access(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    format: Format,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let service = client.find_service(&project.id, service_reference).await?;
    let page = client.repository_access(&service.id).await?;

    if format.is_json() {
        output::emit(&page);
        return Ok(());
    }

    let Some(request) = page.request else {
        println!(
            "  {}",
            "el repositorio se lee sin problema".style(theme::muted())
        );
        return Ok(());
    };

    let owner = match &request.owner_name {
        Some(name) => format!("{name} (@{})", request.owner_login),
        None => format!("@{}", request.owner_login),
    };

    println!("  {}", request.repo_full_name.style(theme::strong()));
    println!("  propietario  {owner}");
    println!(
        "  estado       {}",
        request.state.style(match request.state.as_str() {
            "pending" => theme::warning(),
            "sent" => theme::accent(),
            "granted" => theme::success(),
            _ => theme::muted(),
        })
    );

    match (&request.email, request.state.as_str()) {
        (Some(email), "sent") => {
            println!("  enlace       enviado a {email}");
            println!(
                "  {}",
                match request.opened_at {
                    // Opened and not yet granted is the state worth naming: the
                    // link works, and the favour is halfway done.
                    Some(_) => "ya ha abierto el enlace; falta que lo autorice en GitHub",
                    None => "todavía no lo ha abierto",
                }
                .style(theme::muted())
            );
        }
        _ => println!(
            "  {}",
            format!(
                "GitHub no publica su correo: fundaia access request {project_reference} {service_reference} --email <correo>"
            )
            .style(theme::muted())
        ),
    }

    println!();
    println!(
        "  {}",
        "en cuanto lo conceda, el servicio se despliega solo".style(theme::muted())
    );
    Ok(())
}

/// Commits held at the door, and what became of them.
///
/// Named per project rather than per service because a held commit is somebody
/// else's push: whoever runs this does not yet know which service it landed on.
/// Naming a service narrows it and shows that service's whole history, answered
/// requests included.
pub async fn approvals(
    client: &ApiClient,
    project_reference: &str,
    service_reference: Option<&str>,
    format: Format,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;

    let approvals = match service_reference {
        None => client.project_approvals(&project.id).await?,
        Some(reference) => {
            let found = client.find_service(&project.id, reference).await?;
            client.service_approvals(&found.id).await?
        }
    };

    if format.is_json() {
        output::emit(&approvals);
        return Ok(());
    }

    if approvals.is_empty() {
        println!("  {}", "nada esperando aprobación".style(theme::muted()));
        return Ok(());
    }

    let mut table = Table::new(&["commit", "autor", "por qué", "estado", "cuándo", "id"]);

    for approval in &approvals {
        table.push(vec![
            Cell::plain(short_sha(&approval.commit_sha)),
            Cell::plain(
                approval
                    .author_login
                    .clone()
                    .map(|login| format!("@{login}"))
                    // The blank is the fact: GitHub matched no account at all.
                    .unwrap_or_else(|| "—".to_string()),
            ),
            Cell::plain(reason_label(&approval.reason).to_string()),
            Cell::styled(
                approval.state.clone(),
                match approval.state.as_str() {
                    "pending" => theme::warning(),
                    "approved" => theme::success(),
                    "rejected" => theme::danger(),
                    _ => theme::muted(),
                },
            ),
            Cell::plain(format_millis(
                epoch_millis(&approval.requested_at).unwrap_or(-1),
            )),
            Cell::styled(approval.id.clone(), theme::muted()),
        ]);
    }

    table.print();
    println!();
    println!(
        "  {}",
        "fundaia approve <id> despliega · fundaia reject <id> lo descarta para siempre"
            .style(theme::muted())
    );
    Ok(())
}

/// Seven characters identify a commit to git and to nobody standing at a screen,
/// which is why the subject is on the row beside it wherever there is room.
fn short_sha(sha: &str) -> String {
    sha.chars().take(7).collect()
}

/// The platform's word, in the words somebody deciding would use.
fn reason_label(reason: &str) -> &str {
    match reason {
        "outside-workspace" => "no está en el espacio",
        "unlinked-commit" => "sin cuenta de GitHub",
        "unverifiable" => "no se pudo comprobar",
        other => other,
    }
}

/// What a service keeps getting wrong.
///
/// Folded by shape and counted, so this is short where the log is thousands of
/// lines: one row per distinct failure, worst first. `--json` carries the whole
/// sample message and the trace, which is what `logs --trace` wants next.
pub async fn incidents(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    decided: bool,
    format: Format,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let found = client.find_service(&project.id, service_reference).await?;
    let incidents = client.incidents(&found.id, decided).await?;

    if format.is_json() {
        output::emit(&incidents);
        return Ok(());
    }

    let mut table = Table::new(&["veces", "nivel", "qué falla", "última vez", "estado", "id"]);

    for incident in &incidents {
        let level = match incident.level.as_str() {
            "error" => theme::danger(),
            _ => theme::warning(),
        };

        table.push(vec![
            Cell::plain(incident.occurrences.to_string()),
            Cell::styled(incident.level.clone(), level),
            // Truncated hard: a shape is a whole log line and this is a column.
            Cell::plain(truncate(&incident.shape, 60)),
            Cell::plain(format_millis(
                epoch_millis(&incident.last_seen_at).unwrap_or(-1),
            )),
            Cell::styled(
                incident.status.clone(),
                match incident.status.as_str() {
                    "open" => theme::danger(),
                    "investigating" | "fixProposed" => theme::accent(),
                    _ => theme::muted(),
                },
            ),
            Cell::styled(incident.id.clone(), theme::muted()),
        ]);
    }

    table.print();
    Ok(())
}

/// What the platform has tried to fix on its own.
pub async fn autofix(
    client: &ApiClient,
    project_reference: &str,
    service_reference: &str,
    changes: serde_json::Value,
    format: Format,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let found = client.find_service(&project.id, service_reference).await?;

    // Named a setting: write first, then print the history under the new rules.
    // One command for both because "what is it doing" and "do this instead" are
    // the same question asked a second apart.
    if let Some(object) = changes.as_object() {
        if !object.is_empty() {
            let settings = client.set_autofix(&found.id, &changes).await?;
            if format.is_json() {
                output::emit(&settings);
                return Ok(());
            }
            println!(
                "  {} ajustes guardados",
                theme::CHECK.style(theme::success())
            );
        }
    }

    let runs = client.autofix_runs(&found.id).await?;

    if format.is_json() {
        output::emit(&runs);
        return Ok(());
    }

    let mut table = Table::new(&["estado", "paso", "coste", "pull request", "cuándo"]);

    for run in &runs {
        table.push(vec![
            Cell::styled(
                run.status.clone(),
                match run.status.as_str() {
                    "succeeded" => theme::success(),
                    "running" => theme::accent(),
                    // Not a failure: the agent could not reproduce the bug and
                    // stopped rather than guessing.
                    "notReproducible" => theme::warning(),
                    _ => theme::danger(),
                },
            ),
            Cell::plain(run.step.clone()),
            Cell::plain(format!("{:.2} €", run.cost_micros as f64 / 1_000_000.0)),
            Cell::plain(
                run.pull_request_url
                    .clone()
                    .unwrap_or_else(|| "—".to_owned()),
            ),
            Cell::plain(format_millis(epoch_millis(&run.started_at).unwrap_or(-1))),
        ]);
    }

    table.print();
    Ok(())
}

/// Where every service of a project sits, and what points at what.
///
/// The table is the answer — a script reads the coordinates out of it and
/// `canvas move` takes them back — and `--map` is the picture, which is the
/// half a person came for. Two prints rather than one shape that tries to be
/// both: an ASCII drawing cannot be parsed and a table cannot be read at a
/// glance.
pub async fn canvas(
    client: &ApiClient,
    project_reference: &str,
    map: bool,
    format: Format,
) -> Result<()> {
    let project = client.find_project(project_reference).await?;
    let view = client.canvas(&project.id).await?;

    if format.is_json() {
        output::emit(&view);
        return Ok(());
    }

    if view.nodes.is_empty() {
        println!("`{}` todavía no tiene servicios.", project.name);
        return Ok(());
    }

    if map {
        for line in sketch(&view.nodes) {
            println!("{}", line.style(theme::muted()));
        }
        println!();
    }

    let mut table = Table::new(&["servicio", "x", "y", "depende de"]);

    for node in &view.nodes {
        // Named rather than by id, for the reason `services` gives: the column
        // sits beside a name and an id in it is unreadable.
        let dependencies: Vec<String> = view
            .edges
            .iter()
            .filter(|arrow| arrow.from_service_id == node.service_id)
            .map(|arrow| arrow.to.clone())
            .collect();

        table.push(vec![
            Cell::styled(node.name.clone(), theme::strong()),
            Cell::plain(node.x.to_string()),
            Cell::plain(node.y.to_string()),
            Cell::styled(
                if dependencies.is_empty() {
                    "—".to_owned()
                } else {
                    dependencies.join(", ")
                },
                theme::muted(),
            ),
        ]);
    }

    table.print();
    Ok(())
}

/// How wide and how tall the drawing is, in characters.
const SKETCH_WIDTH: usize = 72;
const SKETCH_HEIGHT: usize = 14;

/// The canvas as characters, with every node where it actually is.
///
/// The coordinates are scaled into the grid rather than divided by a fixed
/// factor: a project laid out by hand can span ten thousand units or two
/// hundred, and a fixed scale draws one of those as a single column.
fn sketch(nodes: &[CanvasNode]) -> Vec<String> {
    let left = nodes.iter().map(|node| node.x).min().unwrap_or(0);
    let right = nodes.iter().map(|node| node.x).max().unwrap_or(0);
    let top = nodes.iter().map(|node| node.y).min().unwrap_or(0);
    let bottom = nodes.iter().map(|node| node.y).max().unwrap_or(0);

    let label_width = 12;
    let mut grid = vec![vec![' '; SKETCH_WIDTH]; SKETCH_HEIGHT];

    for node in nodes {
        let label = truncate(&node.slug, label_width);
        let column = scaled(
            node.x - left,
            right - left,
            SKETCH_WIDTH - label.chars().count(),
        );
        let row = scaled(node.y - top, bottom - top, SKETCH_HEIGHT - 1);
        place(&mut grid, row, column, &label);
    }

    grid.into_iter()
        .map(|row| row.into_iter().collect::<String>().trim_end().to_owned())
        .filter(|row| !row.is_empty())
        .collect()
}

/// One coordinate into one cell, with a span of zero meaning the first one.
fn scaled(offset: i64, span: i64, cells: usize) -> usize {
    if span <= 0 || cells == 0 {
        return 0;
    }

    let ratio = offset as f64 / span as f64;
    (ratio * cells as f64).round() as usize
}

/// Writes a label into the grid, moving it aside rather than over a neighbour.
///
/// Two services genuinely close together land on the same cell once a whole
/// canvas is squeezed into seventy-two characters, and a drawing that overwrote
/// one with the other would be a picture of a project with a service missing.
fn place(grid: &mut [Vec<char>], row: usize, column: usize, label: &str) {
    let width = label.chars().count();

    for line in grid.iter_mut().skip(row) {
        for candidate in column..=line.len().saturating_sub(width) {
            let free = line[candidate..candidate + width]
                .iter()
                .all(|cell| *cell == ' ');
            // One space of margin, so two labels never read as one word.
            let margin_free = candidate == 0 || line[candidate - 1] == ' ';

            if free && margin_free {
                for (offset, letter) in label.chars().enumerate() {
                    line[candidate + offset] = letter;
                }
                return;
            }
        }
    }
}

/// `duerme tras 8 h sin tráfico`, or `tras 90 min` when the window is not
/// whole hours. A window of zero is a server too old to send one, and then
/// the sentence says only what it knows.
fn sleep_phrase(sleep_after_minutes: u32) -> String {
    match sleep_after_minutes {
        0 => "duerme sin tráfico".to_owned(),
        minutes if minutes % 60 == 0 => format!("duerme tras {} h sin tráfico", minutes / 60),
        minutes => format!("duerme tras {minutes} min sin tráfico"),
    }
}

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

    #[test]
    fn it_should_say_the_idle_window_in_hours_when_it_is_whole_hours() {
        assert_eq!(sleep_phrase(480), "duerme tras 8 h sin tráfico");
    }

    #[test]
    fn it_should_say_the_idle_window_in_minutes_otherwise() {
        assert_eq!(sleep_phrase(90), "duerme tras 90 min sin tráfico");
    }

    #[test]
    fn it_should_not_invent_a_window_a_server_did_not_send() {
        assert_eq!(sleep_phrase(0), "duerme sin tráfico");
    }

    fn node(slug: &str, x: i64, y: i64) -> CanvasNode {
        CanvasNode {
            service_id: format!("svc_{slug}"),
            service_environment_id: format!("sve_{slug}"),
            name: slug.to_owned(),
            slug: slug.to_owned(),
            kind: "application".to_owned(),
            state: "active".to_owned(),
            x,
            y,
        }
    }

    #[test]
    fn it_should_draw_the_leftmost_service_against_the_left_margin() {
        let drawn = sketch(&[node("db", 80, 80), node("api", 380, 80)]);
        assert!(drawn[0].starts_with("db"));
    }

    #[test]
    fn it_should_draw_a_service_further_right_further_right() {
        let drawn = sketch(&[node("db", 80, 80), node("api", 380, 80)]);
        assert!(drawn[0].find("api") > drawn[0].find("db"));
    }

    #[test]
    fn it_should_draw_a_service_further_down_on_a_later_line() {
        let drawn = sketch(&[node("db", 80, 80), node("api", 80, 500)]);
        assert!(drawn.len() > 1);
    }

    /// Squeezing a canvas into 72 characters puts neighbours on one cell, and a
    /// drawing that overwrote one with the other is a project missing a service.
    #[test]
    fn it_should_draw_both_of_two_services_at_the_same_point() {
        let drawn = sketch(&[node("db", 80, 80), node("api", 80, 80)]);
        assert!(drawn.concat().contains("db") && drawn.concat().contains("api"));
    }

    #[test]
    fn it_should_put_a_lone_service_in_the_first_cell() {
        assert_eq!(scaled(0, 0, 40), 0);
    }

    #[test]
    fn it_should_draw_one_block_per_reading() {
        assert_eq!(sparkline(&[1, 2, 3]).chars().count(), 3);
    }

    #[test]
    fn it_should_draw_the_largest_reading_at_full_height() {
        assert!(sparkline(&[1, 10]).ends_with('█'));
    }

    #[test]
    fn it_should_draw_a_flat_series_of_zeroes_at_the_floor() {
        assert_eq!(sparkline(&[0, 0, 0]), "▁▁▁");
    }

    #[test]
    fn it_should_draw_nothing_for_no_readings() {
        assert_eq!(sparkline(&[]), "");
    }

    #[test]
    fn it_should_fill_a_full_meter_completely() {
        assert!(bar(100).contains(&"█".repeat(20)));
    }

    #[test]
    fn it_should_leave_an_empty_meter_unfilled() {
        assert!(bar(0).contains(&"░".repeat(20)));
    }

    /// Two decimals would print an afternoon of prompts as `$0.00`.
    #[test]
    fn it_should_show_four_decimals_under_a_cent() {
        assert_eq!(format_money(3_400), "$0.0034");
    }

    #[test]
    fn it_should_show_two_decimals_above_a_cent() {
        assert_eq!(format_money(1_250_000), "$1.25");
    }

    #[test]
    fn it_should_print_nothing_spent_without_decimals() {
        assert_eq!(format_money(0), "$0");
    }

    #[test]
    fn it_should_abbreviate_thousands_of_tokens() {
        assert_eq!(format_tokens(23_578), "23 k");
    }

    #[test]
    fn it_should_abbreviate_millions_of_tokens() {
        assert_eq!(format_tokens(2_400_000), "2.4 M");
    }

    #[test]
    fn it_should_print_a_small_count_whole() {
        assert_eq!(format_tokens(511), "511");
    }

    #[test]
    fn it_should_count_cached_tokens_towards_the_total() {
        let counts = crate::api::models::TokenCounts {
            input_tokens: 1,
            output_tokens: 2,
            cache_read_tokens: 4,
            cache_creation_tokens: 8,
        };
        assert_eq!(counts.total(), 15);
    }
}