mossaic 0.5.0

Plan and track GitHub contribution art — what today owes to draw your name by December, and whether the year can still be drawn at all
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
//! The `mossaic-art` binary, run as a user runs it.
//!
//! No PTY here: `mossaic-art` prints and exits, so this drives it the way a shell does
//! and asserts on what comes back. Everything is offline — `--merge` reads a
//! saved calendar, so nothing needs `gh`.

use std::path::Path;
use std::process::{Command, Output};

fn art(args: &[&str]) -> Output {
    Command::new(env!("CARGO_BIN_EXE_mossaic-art"))
        .current_dir(env!("CARGO_MANIFEST_DIR"))
        .args(args)
        .output()
        .expect("the art binary runs")
}

/// A scratch path in the temp directory that no other process will touch.
///
/// The names here used to be constants, which made them shared state: a stress
/// loop beside an ordinary `cargo test`, or two people on one machine, raced
/// over the same file and failed in ways that looked like the code rather than
/// like the harness. CONTRIBUTING.md §3 asks for hermetic tests, and a fixed
/// global path is not one.
fn scratch(name: &str) -> std::path::PathBuf {
    std::env::temp_dir().join(format!("mossaic-{}-{name}", std::process::id()))
}

fn stdout(output: &Output) -> String {
    String::from_utf8_lossy(&output.stdout).into_owned()
}

#[test]
fn the_font_can_be_looked_at() {
    let out = art(&["--font", "--no-colour"]);
    assert!(out.status.success());
    let text = stdout(&out);
    // A lower bound, like the unit test's: adding a glyph is the point of the
    // font, and a test that counted them would fail on the one contribution it
    // exists to protect.
    let count: usize = text
        .split_whitespace()
        .next()
        .and_then(|word| word.parse().ok())
        .unwrap_or_else(|| panic!("no glyph count in {text}"));
    assert!(count >= 39, "{count} glyphs: {text}");
    assert!(text.contains("glyphs, 5x5 each"), "{text}");
    assert!(text.contains("add one to FONT in src/art.rs"), "{text}");
    // Every character it claims, drawn.
    for character in ['A', 'Z', '0', '9', '-', '.'] {
        assert!(
            text.contains(character),
            "the font view is missing {character}"
        );
    }
    assert!(
        text.contains("space"),
        "including the one with no glyph: {text}"
    );
}

/// A shape, typed the way anyone without a symbol keyboard has to type it.
#[test]
fn a_shape_can_be_written_between_colons() {
    let out = art(&["I :HEART: RUST", "--year", "2027", "--no-colour"]);
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let text = stdout(&out);
    // The header echoes the character, not the name it was typed as: the plan
    // is stored that way, and the tracker reads it back.
    assert!(text.contains("I \u{2665} RUST"), "{text}");
    // Eight glyphs at six columns apiece, less the gap after the last.
    assert!(text.contains("47 of 53 columns"), "{text}");

    // Upper and lower case name the same shape, because a plan is stored
    // uppercased and has to survive the round trip.
    let lower = art(&["I :heart: RUST", "--year", "2027", "--no-colour"]);
    assert_eq!(stdout(&lower), text, "case should not change the drawing");
}

/// The symbol itself, and the emoji someone is far more likely to paste.
#[test]
fn a_pasted_symbol_draws_the_same_shape_as_its_name() {
    let by_name = art(&[":star::heart:", "--year", "2027", "--no-colour"]);
    let by_symbol = art(&["\u{2605}\u{2665}", "--year", "2027", "--no-colour"]);
    let by_emoji = art(&["\u{2b50}\u{2764}\u{fe0f}", "--year", "2027", "--no-colour"]);

    assert!(
        by_name.status.success(),
        "{}",
        String::from_utf8_lossy(&by_name.stderr)
    );
    assert_eq!(stdout(&by_symbol), stdout(&by_name), "symbol vs name");
    assert_eq!(
        stdout(&by_emoji),
        stdout(&by_name),
        "a pasted emoji, variation selector and all, vs name"
    );
}

/// Both ways of getting the grammar wrong, and what each says.
#[test]
fn a_misspelt_shape_says_which_shapes_there_are() {
    let unknown = art(&[":wombat:", "--year", "2027"]);
    assert!(
        !unknown.status.success(),
        "it should refuse rather than guess"
    );
    let error = String::from_utf8_lossy(&unknown.stderr).into_owned();
    assert!(error.contains("wombat"), "{error}");
    assert!(
        error.contains(":star:") && error.contains(":heart:"),
        "{error}"
    );

    // A colon that opens nothing. The message is about the grammar rather
    // than about a missing glyph for ':', which would be true and useless.
    let unclosed = art(&["12:30", "--year", "2027"]);
    assert!(!unclosed.status.success());
    let error = String::from_utf8_lossy(&unclosed.stderr).into_owned();
    assert!(error.contains("unclosed"), "{error}");
    assert!(error.contains(":name:"), "{error}");
}

/// The font view names its shapes rather than printing them. Several of these
/// symbols are ambiguous-width, so a terminal may draw one in two columns and
/// tear the aligned output apart — the same reason the README lists names.
#[test]
fn the_font_view_names_its_shapes() {
    let out = art(&["--font", "--no-colour"]);
    assert!(out.status.success());
    let text = stdout(&out);
    for named in [
        ":star:", ":heart:", ":smile:", ":sad:", ":moon:", ":flower:",
    ] {
        assert!(text.contains(named), "the font view is missing {named}");
    }
    // The label is the name, so the raw symbol never reaches the column
    // headings it would misalign.
    assert!(
        !text.contains('\u{2605}'),
        "a bare symbol in the headings: {text}"
    );
}

/// A shape has to survive being written to a plan and read back, which is the
/// path every tracked year takes each morning.
#[test]
fn a_shape_round_trips_through_a_saved_plan() {
    let dir = scratch("shape-plan");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();

    let run = |args: &[&str]| {
        Command::new(env!("CARGO_BIN_EXE_mossaic-art"))
            .current_dir(&dir)
            .args(args)
            .output()
            .expect("the art binary runs")
    };

    let saved = run(&[":heart::star:", "--year", "2027", "--save", "--no-colour"]);
    assert!(
        saved.status.success(),
        "{}",
        String::from_utf8_lossy(&saved.stderr)
    );

    // Stored as characters, so nothing downstream has to know the grammar.
    let plan =
        std::fs::read_to_string(dir.join(mossaic::plan::DEFAULT_SPEC)).expect("a plan on disk");
    assert!(
        plan.contains('\u{2665}') && plan.contains('\u{2605}'),
        "{plan}"
    );
    assert!(
        !plan.contains(":heart:"),
        "the name should not survive: {plan}"
    );

    // And read back by the tracker, which is the run that happens every day.
    // Against a saved calendar rather than the network: without `--merge` this
    // asks `gh` whose graph to read, which is not a question a test may ask.
    // The path is absolute because the run happens in the scratch directory.
    let calendar = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("art/vyncint-2027.json")
        .to_string_lossy()
        .into_owned();
    let tracked = run(&[
        "--track",
        "--merge",
        &calendar,
        "--no-colour",
        "--today",
        "2027-06-01",
    ]);
    assert!(
        tracked.status.success(),
        "{}",
        String::from_utf8_lossy(&tracked.stderr)
    );
    assert!(
        stdout(&tracked).contains('\u{2665}'),
        "{}",
        stdout(&tracked)
    );

    let _ = std::fs::remove_dir_all(&dir);
}

/// The README promises a set; the font has to be that set.
///
/// A table of glyphs is exactly the documentation that rots — a shape gets
/// added and the list quietly stops being true, and the list is the only place
/// most people will look. So the list is checked rather than maintained.
#[test]
fn the_readme_lists_every_glyph_the_font_has() {
    let readme = std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("README.md"))
        .expect("a README");
    let section = readme
        .split("## What you can draw")
        .nth(1)
        .expect("a section listing the font")
        .split("\n## ")
        .next()
        .expect("the section ends");

    for (name, _) in mossaic::art::shapes() {
        assert!(
            section.contains(&format!(":{name}:")),
            "the README does not list :{name}:"
        );
    }
    for character in mossaic::art::alphabet() {
        if character.is_whitespace() || mossaic::art::shape_name(character).is_some() {
            continue;
        }
        assert!(
            section.contains(character),
            "the README does not list {character:?}"
        );
    }

    // And nothing it lists is missing from the font: every `:name:` in the
    // section has to draw something.
    for token in section.split_whitespace() {
        let Some(name) = token
            .trim_matches('`')
            .strip_prefix(':')
            .and_then(|rest| rest.strip_suffix(':'))
        else {
            continue;
        };
        assert!(
            mossaic::art::shape(name).is_some(),
            "the README promises :{name}:, which the font does not have"
        );
    }

    // The table's own claim, row by row: every symbol and every emoji on a row
    // draws the shape that row names. This is the half most likely to rot —
    // a fold gets removed and the table still advertises the emoji.
    let mut rows = 0;
    for line in section.lines().filter(|line| line.starts_with('|')) {
        let cells: Vec<&str> = line.split('|').map(str::trim).collect();
        let [_, symbols, names, pastes, ..] = cells.as_slice() else {
            continue;
        };
        let Some(first) = names.split_whitespace().next() else {
            continue;
        };
        let Some(name) = first
            .trim_matches('`')
            .strip_prefix(':')
            .and_then(|rest| rest.strip_suffix(':'))
        else {
            continue;
        };
        let wanted = mossaic::art::bitmap(&format!(":{name}:")).expect("a shape");
        rows += 1;

        // The arrows share a row, so a row may name several shapes and show
        // several symbols; each symbol is checked against its own name.
        let named: Vec<&str> = names
            .split_whitespace()
            .filter_map(|token| {
                token
                    .trim_matches('`')
                    .strip_prefix(':')
                    .and_then(|rest| rest.strip_suffix(':'))
            })
            .collect();
        for symbol in symbols.chars().filter(|c| !c.is_whitespace()) {
            let drawn = mossaic::art::bitmap(&symbol.to_string())
                .unwrap_or_else(|error| panic!("the README shows {symbol:?}: {error}"));
            assert!(
                named
                    .iter()
                    .any(|name| drawn == mossaic::art::bitmap(&format!(":{name}:")).unwrap()),
                "the README shows {symbol:?} beside {named:?}, which it does not draw"
            );
        }

        for pasted in pastes
            .chars()
            // A variation selector says how to draw the character before it,
            // not which character it is, and the README carries whatever an
            // emoji keyboard produced.
            .filter(|c| {
                !c.is_whitespace() && !c.is_ascii() && !matches!(c, '\u{fe0f}' | '\u{fe0e}')
            })
        {
            let drawn = mossaic::art::bitmap(&pasted.to_string())
                .unwrap_or_else(|error| panic!("the README offers {pasted:?}: {error}"));
            assert_eq!(
                drawn, wanted,
                "the README offers {pasted:?} for :{name}:, which is not what it draws"
            );
        }
    }
    assert!(
        rows >= 16,
        "only {rows} rows of the shape table were checked"
    );
}

/// A shape has to survive the last mile as well: into a commit message, and
/// back out of git. The message is the one place the text leaves the program
/// entirely, and a character that draws perfectly can still be mangled there.
#[test]
fn a_shape_reaches_the_commits_it_writes() {
    let dir = scratch("shape-write");
    let _ = std::fs::remove_dir_all(&dir);
    let repo = dir.to_string_lossy().into_owned();

    let out = art(&[
        ":heart:",
        "--year",
        "2027",
        "--commits",
        "1",
        "--repo",
        &repo,
        "--write",
        "--name",
        "Tester",
        "--email",
        "tester@example.invalid",
        "--no-colour",
    ]);
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(
        stdout(&out).contains("nothing has been pushed"),
        "{}",
        stdout(&out)
    );

    let log = Command::new("git")
        .current_dir(&dir)
        .args(["log", "--format=%s"])
        .output()
        .expect("git log runs");
    let subjects = String::from_utf8_lossy(&log.stdout).into_owned();
    assert!(!subjects.trim().is_empty(), "it wrote commits");
    assert!(
        subjects.contains("art: \u{2665}"),
        "the shape did not reach the commit message: {subjects}"
    );
    // The name is not what is stored, so it cannot be what comes back out.
    assert!(!subjects.contains(":heart:"), "{subjects}");

    let _ = std::fs::remove_dir_all(&dir);
}

/// The Action reads `--format json`, so a shape has to come out of it as valid
/// JSON rather than as whatever the character did to the encoder.
#[test]
fn a_shape_survives_the_json_the_action_reads() {
    let out = art(&[
        ":heart:",
        "--year",
        "2027",
        "--track",
        "--merge",
        "art/vyncint-2027.json",
        "--today",
        "2027-06-01",
        "--format",
        "json",
    ]);
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let text = stdout(&out);
    // Parsed rather than matched, which is the only way to say "valid JSON".
    let parsed: serde_json::Value = serde_json::from_str(&text).expect("valid JSON");
    assert_eq!(parsed["text"], "\u{2665}", "{text}");
}

/// The font sheet in the README has to be the font the crate ships.
///
/// An image of the alphabet is documentation that cannot be spot-checked by
/// reading it: a glyph gets added, the picture keeps showing the old set, and
/// nothing says so. So the picture is regenerated here and compared with the
/// committed one, byte for byte — the same input through the same encoder is
/// the same file.
#[test]
fn the_font_sheet_in_the_readme_is_the_font() {
    let committed = Path::new(env!("CARGO_MANIFEST_DIR")).join("art/font.png");
    let fresh = scratch("font-sheet.png");
    let _ = std::fs::remove_file(&fresh);

    let out = art(&["--font", "--png", &fresh.to_string_lossy()]);
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(stdout(&out).contains("76 glyphs"), "{}", stdout(&out));

    let drawn = std::fs::read(&fresh).expect("the sheet it just wrote");
    let shipped = std::fs::read(&committed).expect("art/font.png");
    assert_eq!(
        drawn.len(),
        shipped.len(),
        "art/font.png is {} bytes and the font now draws {} — regenerate it:\n  \
         cargo run --bin mossaic-art -- --font --png art/font.png",
        shipped.len(),
        drawn.len()
    );
    assert!(
        drawn == shipped,
        "art/font.png is not what the font draws — regenerate it:\n  \
         cargo run --bin mossaic-art -- --font --png art/font.png"
    );

    // It is a PNG, and the README points at it.
    assert_eq!(&shipped[..8], b"\x89PNG\r\n\x1a\n");
    let readme = std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("README.md"))
        .expect("a README");
    assert!(
        readme.contains("](art/font.png)"),
        "the README shows the sheet"
    );

    let _ = std::fs::remove_file(&fresh);
}

#[test]
fn an_unknown_character_says_what_there_is() {
    let out = art(&["HI~THERE", "--year", "2027"]);
    assert!(!out.status.success(), "it should refuse rather than guess");
    let error = String::from_utf8_lossy(&out.stderr).into_owned();
    assert!(error.contains('~'), "{error}");
    assert!(error.contains("ABCDEFGHIJKLMNOPQRSTUVWXYZ"), "{error}");
}

#[test]
fn tracking_a_finished_year_says_so() {
    // art/vyncint-2027.json is VYNCINT drawn on an otherwise empty year, at the
    // placement centring gives — so tracking it back is a completed plan.
    //
    // `--today` is pinned because the last assertion is about a year that has
    // not started, which the clock would make true only until it did. Every
    // test that reads a report pins it, for the same reason.
    let out = art(&[
        "VYNCINT",
        "--year",
        "2027",
        "--track",
        "--merge",
        "art/vyncint-2027.json",
        "--today",
        "2026-08-19",
        "--no-colour",
    ]);
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let text = stdout(&out);
    assert!(text.contains("VYNCINT is drawn."), "{text}");
    assert!(text.contains("75 of 75 bright"), "{text}");
    assert!(!text.contains("cannot be drawn"), "{text}");
    // A year still ahead has no advice for this afternoon.
    assert!(text.contains("2027 has not started"), "{text}");
}

#[test]
fn tracking_a_busy_year_says_why_it_cannot_be_drawn() {
    // The same text over a year that already has contributions of its own: the
    // letters can be brightened, but the days inside them that are already lit
    // are permanent.
    let out = art(&[
        "VYNCINT",
        "--year",
        "2026",
        "--track",
        "--merge",
        "art/vyncint-2026.json",
        "--no-colour",
        "--today",
        "2026-08-19",
        "--start-week",
        "1",
    ]);
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let text = stdout(&out);
    assert!(
        text.contains("VYNCINT cannot be drawn cleanly in 2026."),
        "{text}"
    );
    assert!(
        text.contains("inside the letters already have contributions"),
        "and it should say why:\n{text}"
    );
    assert!(
        text.contains("a letter day has to reach"),
        "and what a day costs:\n{text}"
    );
    // The verdict is a fact about the data, not a mood: the same run twice says
    // the same thing.
    assert_eq!(
        text,
        stdout(&art(&[
            "VYNCINT",
            "--year",
            "2026",
            "--track",
            "--merge",
            "art/vyncint-2026.json",
            "--no-colour",
            "--today",
            "2026-08-19",
            "--start-week",
            "1",
        ]))
    );
}

#[test]
fn tracking_without_a_calendar_explains_itself() {
    // No --merge and no `gh` reachable: it has to say what it needed, not fail
    // with whatever the process error happened to be.
    let out = Command::new(env!("CARGO_BIN_EXE_mossaic-art"))
        .current_dir(env!("CARGO_MANIFEST_DIR"))
        .env("PATH", "/nonexistent")
        .args(["VYNCINT", "--year", "2026", "--track"])
        .output()
        .expect("the art binary runs");
    assert!(!out.status.success());
    let error = String::from_utf8_lossy(&out.stderr).into_owned();
    assert!(
        error.contains("--track USER") || error.contains("gh auth login"),
        "{error}"
    );
}

#[test]
fn a_snapshot_round_trips_through_the_chart() {
    let out = scratch("art-cli.json");
    let path = out.to_string_lossy().into_owned();
    let made = art(&["HI", "--year", "2027", "--snapshot", &path, "--no-colour"]);
    assert!(
        made.status.success(),
        "{}",
        String::from_utf8_lossy(&made.stderr)
    );
    assert!(
        stdout(&made).contains("mossaic --file"),
        "it says what to do next"
    );
    assert!(Path::new(&path).exists());

    // And the chart renders it without a terminal.
    let png = scratch("art-cli.png");
    let drawn = Command::new(env!("CARGO_BIN_EXE_mossaic"))
        .args(["--file", &path, "--png", &png.to_string_lossy()])
        .output()
        .expect("the chart runs");
    assert!(
        drawn.status.success(),
        "{}",
        String::from_utf8_lossy(&drawn.stderr)
    );
    assert!(png.exists());
    let _ = std::fs::remove_file(&out);
    let _ = std::fs::remove_file(&png);
}

#[test]
fn the_help_lists_every_flag_the_parser_takes() {
    // Derived from the parser rather than from a list kept alongside it: adding
    // a flag and forgetting the help is exactly the mistake this catches, and a
    // hand-written list would have to be remembered too.
    let source = include_str!("../src/bin/mossaic-art.rs");
    // Every quoted token in a match arm, not just the first: an arm like
    // `"-h" | "--help" =>` documents two flags, and only checking one of them
    // is how `--help` itself went unverified.
    let arms: Vec<&str> = source
        .lines()
        .map(str::trim)
        .filter(|line| line.starts_with('"') && line.contains("=>"))
        .flat_map(|line| line.split('"').skip(1).step_by(2))
        .filter(|token| token.starts_with('-'))
        .collect();
    assert!(
        arms.len() > 15,
        "only found {} flags — did the parser move?",
        arms.len()
    );

    let help = stdout(&art(&["--help"]));
    for flag in arms {
        assert!(help.contains(flag), "--help never mentions {flag}");
    }
    assert!(
        help.contains("examples:"),
        "and it should show how, not just what"
    );
    // The thing that removes the trap: a saved plan.
    assert!(help.contains("--save"), "{help}");
    assert!(help.contains("mossaic-art --track"), "{help}");
}

#[test]
fn the_report_is_machine_readable() {
    let out = art(&[
        "VYNCINT",
        "--year",
        "2026",
        "--track",
        "--merge",
        "art/vyncint-2026.json",
        "--start-week",
        "1",
        "--today",
        "2026-08-19",
        "--format",
        "json",
    ]);
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let json: serde_json::Value =
        serde_json::from_str(&stdout(&out)).expect("--format json emits json");

    // The fields the GitHub Action reads. A rename here breaks every workflow
    // in the wild, so they are pinned by name.
    for field in [
        "text",
        "year",
        "source",
        "start_week",
        "columns",
        "year_total",
        "peak",
        "need_per_day",
        "letters",
        "bright",
        "owing_days",
        "owing_commits",
        "holes",
        "around",
        "verdict",
        "headline",
        "ahead_days",
        "overdue_days",
    ] {
        assert!(!json[field].is_null(), "the report lost `{field}`");
    }
    assert_eq!(json["text"], "VYNCINT");
    assert_eq!(json["year"], 2026);
    assert_eq!(json["verdict"], "holed");
    assert_eq!(json["letters"], 75);
    assert!(json["holes"].as_u64().unwrap() > 0);
    // The headline is carried, not reconstructed downstream.
    let headline = json["headline"].as_str().unwrap();
    assert!(headline.contains("VYNCINT"), "{headline}");
    assert!(headline.contains("hole"), "{headline}");

    // Markdown says the same things, in a shape a message can carry.
    let md = stdout(&art(&[
        "VYNCINT",
        "--year",
        "2026",
        "--track",
        "--merge",
        "art/vyncint-2026.json",
        "--start-week",
        "1",
        "--today",
        "2026-08-19",
        "--format",
        "markdown",
    ]));
    assert!(md.starts_with("### VYNCINT · 2026"), "{md}");
    assert!(md.contains("Cannot be drawn cleanly"), "{md}");
    assert!(md.contains("| letters bright | 75 of 75 |"), "{md}");
    assert!(
        !md.contains('\x1b'),
        "a message body carries no escape codes:\n{md}"
    );
}

#[test]
fn an_unknown_format_is_refused() {
    let out = art(&["VYNCINT", "--year", "2027", "--track", "--format", "yaml"]);
    assert!(!out.status.success());
    let error = String::from_utf8_lossy(&out.stderr).into_owned();
    assert!(error.contains("text, json or markdown"), "{error}");
}

#[test]
fn a_saved_plan_makes_the_flags_optional() {
    let dir = scratch("plan-test");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();

    let run = |args: &[&str]| {
        Command::new(env!("CARGO_BIN_EXE_mossaic-art"))
            .current_dir(&dir)
            .args(args)
            .output()
            .expect("the art binary runs")
    };

    // With no plan and no text, it says what to do rather than what went wrong.
    let lost = run(&["--track"]);
    assert!(!lost.status.success());
    let hint = String::from_utf8_lossy(&lost.stderr).into_owned();
    assert!(hint.contains("--save"), "{hint}");
    assert!(hint.contains("no plan at"), "{hint}");

    // Save one. The placement is stored resolved, not as typed: this run never
    // said --start-week, and centring is what has to survive.
    let saved = run(&["VYNCINT", "--year", "2027", "--save", "--no-colour"]);
    assert!(
        saved.status.success(),
        "{}",
        String::from_utf8_lossy(&saved.stderr)
    );
    assert!(
        stdout(&saved).contains("mossaic-art --track"),
        "it says what is next"
    );
    let spec: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(dir.join("mossaic-plan.json")).unwrap())
            .unwrap();
    assert_eq!(spec["text"], "VYNCINT");
    assert_eq!(spec["year"], 2027);
    assert_eq!(spec["start_week"], 6, "the centred column, resolved");
    assert_eq!(spec["top"], 1);

    // Now the flags are optional, and the plan is the same one.
    let tracked = run(&["--track", "--merge", "../../nonexistent.json"]);
    let error = String::from_utf8_lossy(&tracked.stderr).into_owned();
    assert!(
        error.contains("nonexistent.json"),
        "it should have got as far as reading the calendar: {error}"
    );

    // A typed flag still wins over the saved one.
    let overridden = run(&["--year", "2028", "--no-colour"]);
    assert!(
        stdout(&overridden).contains("2028"),
        "{}",
        stdout(&overridden)
    );
    assert!(
        !stdout(&overridden).contains("· 2027 ·"),
        "{}",
        stdout(&overridden)
    );

    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn every_binary_answers_the_basics() {
    for (name, binary) in [
        ("mossaic", env!("CARGO_BIN_EXE_mossaic")),
        ("mossaic-art", env!("CARGO_BIN_EXE_mossaic-art")),
        ("mossaic-glyphs", env!("CARGO_BIN_EXE_mossaic-glyphs")),
    ] {
        for flag in ["--help", "-h", "--version", "-V"] {
            let out = Command::new(binary).arg(flag).output().expect("runs");
            assert!(out.status.success(), "{name} {flag} failed");
            let text = String::from_utf8_lossy(&out.stdout).into_owned();
            assert!(!text.trim().is_empty(), "{name} {flag} printed nothing");
            if flag.contains("version") || flag == "-V" {
                assert!(
                    text.contains(env!("CARGO_PKG_VERSION")),
                    "{name} {flag} does not print the version: {text}"
                );
                assert!(text.starts_with(name), "{name} {flag} says: {text}");
            }
        }
    }
}

#[test]
fn bad_input_is_refused_the_same_way_by_every_binary() {
    // The two CLIs used to disagree about a year: one range-checked it, the
    // other passed 999999 through to a panic in the calendar.
    for binary in [
        env!("CARGO_BIN_EXE_mossaic"),
        env!("CARGO_BIN_EXE_mossaic-art"),
    ] {
        for bad in ["abc", "999999", "-5", "2101", "0"] {
            let out = Command::new(binary)
                .args(["HI", "--year", bad])
                .output()
                .expect("runs");
            let error = String::from_utf8_lossy(&out.stderr).into_owned();
            assert!(!out.status.success(), "{binary} accepted --year {bad}");
            assert!(
                error.contains("wants a year between 2000 and 2100"),
                "{binary} --year {bad}: {error}"
            );
            assert!(
                !error.contains("panicked"),
                "{binary} --year {bad} panicked"
            );
        }
        // And a missing value is a missing value, not the next flag.
        let out = Command::new(binary)
            .args(["--year"])
            .output()
            .expect("runs");
        assert!(String::from_utf8_lossy(&out.stderr).contains("--year needs a value"));
    }
}

#[test]
fn colour_follows_the_convention() {
    // Piped: no escapes. NO_COLOR: no escapes even when forced by a tty. And
    // --color always: escapes regardless.
    let piped = stdout(&art(&["--font"]));
    assert!(!piped.contains('\x1b'), "a pipe should get no colour");

    let forced = Command::new(env!("CARGO_BIN_EXE_mossaic-art"))
        .current_dir(env!("CARGO_MANIFEST_DIR"))
        .args(["--font", "--color", "always"])
        .output()
        .expect("runs");
    assert!(
        String::from_utf8_lossy(&forced.stdout).contains('\x1b'),
        "--color always should colour a pipe"
    );

    let no_color = Command::new(env!("CARGO_BIN_EXE_mossaic-art"))
        .current_dir(env!("CARGO_MANIFEST_DIR"))
        .env("NO_COLOR", "1")
        .args(["--font", "--color", "auto"])
        .output()
        .expect("runs");
    assert!(!String::from_utf8_lossy(&no_color.stdout).contains('\x1b'));

    let bad = Command::new(env!("CARGO_BIN_EXE_mossaic-art"))
        .args(["--font", "--color", "chartreuse"])
        .output()
        .expect("runs");
    assert!(!bad.status.success());
    assert!(String::from_utf8_lossy(&bad.stderr).contains("auto, always or never"));
}

#[test]
fn a_background_is_drawn_as_a_shade_and_priced_as_one() {
    let out = art(&[
        "VYNCINT",
        "--year",
        "2027",
        "--background",
        "1",
        "--no-colour",
    ]);
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let text = stdout(&out);

    // The two shades, and what a reader will make of them.
    assert!(
        text.contains("background level 1 under letters at level 4"),
        "{text}"
    );
    assert!(text.contains("290 background day(s), 1 each"), "{text}");
    assert!(text.contains("clear"), "level 1 under 4 is clear: {text}");
    assert!(!text.contains("faint"), "{text}");

    // 75 letter days at 4 plus 290 background days at 1.
    assert!(text.contains("590 commits"), "{text}");

    // The preview has to show three states now, not two, or there is no way to
    // check the art before making a single commit.
    assert!(text.contains(''), "the field: {text}");
    assert!(text.contains(''), "the letters: {text}");
}

#[test]
fn neighbouring_shades_are_drawn_but_said_to_be_faint() {
    let out = art(&["VYNCINT", "--year", "2027", "--bg", "3", "--no-colour"]);
    assert!(out.status.success(), "faint is a warning, not a refusal");
    let text = stdout(&out);
    assert!(text.contains("faint"), "{text}");
    assert!(
        text.contains("neighbouring shades"),
        "it should say why: {text}"
    );
    assert!(
        text.contains("--background 2"),
        "and what to do instead: {text}"
    );
}

#[test]
fn a_background_that_would_hide_the_letters_is_refused() {
    // Equal shades draw nothing at all, so this is an error rather than a note.
    let same = art(&["VYNCINT", "--year", "2027", "--background", "4"]);
    assert!(!same.status.success());
    assert_eq!(same.status.code(), Some(2));
    let error = String::from_utf8_lossy(&same.stderr).into_owned();
    assert!(error.contains("darker"), "{error}");

    let wild = art(&["VYNCINT", "--year", "2027", "--background", "7"]);
    assert!(!wild.status.success());
    let error = String::from_utf8_lossy(&wild.stderr).into_owned();
    assert!(error.contains("between 0 and 4"), "{error}");

    // The subtle one: the shades are fine, but --commits is too small for the
    // year to hold both of them, so the letters would come out the same colour
    // as the field.
    let cramped = art(&[
        "VYNCINT",
        "--year",
        "2027",
        "--background",
        "1",
        "--commits",
        "1",
    ]);
    assert!(!cramped.status.success());
    let error = String::from_utf8_lossy(&cramped.stderr).into_owned();
    assert!(error.contains("would not show"), "{error}");
    assert!(
        error.contains("at least 2 commits"),
        "it should quote the fix: {error}"
    );
}

#[test]
fn tracking_reports_the_letters_and_the_field_apart() {
    // The saved calendar is VYNCINT at four commits a day on an otherwise empty
    // year: the letters are finished, the background has not been started.
    let out = art(&[
        "VYNCINT",
        "--year",
        "2027",
        "--track",
        "--merge",
        "art/vyncint-2027.json",
        "--background",
        "1",
        "--today",
        "2027-06-01",
        "--no-colour",
    ]);
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let text = stdout(&out);

    assert!(
        text.contains("75 of 75 bright"),
        "the letters are done: {text}"
    );
    assert!(
        text.contains("0 of 290 at level 1"),
        "and the field is not: {text}"
    );
    assert!(
        text.contains("the shades"),
        "the plan says which two shades it means: {text}"
    );
    assert!(
        text.contains("a background day has to reach 1"),
        "and what one costs: {text}"
    );
    assert!(
        !text.contains("VYNCINT is drawn."),
        "finished letters are not a finished picture: {text}"
    );
    // The bug this guards: the verdict used to count only the letters, and so
    // announced "0 contributions to go" with the whole field still bare.
    assert!(
        text.contains("0 for the letters, 290 for the field"),
        "the verdict has to count both: {text}"
    );
}

#[test]
fn a_saved_plan_remembers_the_background() {
    let dir = scratch("plan-background-test");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();

    let run = |args: &[&str]| {
        Command::new(env!("CARGO_BIN_EXE_mossaic-art"))
            .current_dir(&dir)
            .args(args)
            .output()
            .expect("the art binary runs")
    };

    let saved = run(&[
        "VYNCINT",
        "--year",
        "2027",
        "--background",
        "2",
        "--save",
        "--no-colour",
    ]);
    assert!(
        saved.status.success(),
        "{}",
        String::from_utf8_lossy(&saved.stderr)
    );
    let spec: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(dir.join("mossaic-plan.json")).unwrap())
            .unwrap();
    assert_eq!(spec["background"], 2, "the shade is part of the plan");

    // Later runs need no flags, and get the same picture.
    let again = stdout(&run(&["--no-colour"]));
    assert!(
        again.contains("background level 2 under letters at level 4"),
        "{again}"
    );

    // A plan written before backgrounds existed still loads, as no background.
    std::fs::write(
        dir.join("mossaic-plan.json"),
        r#"{"text":"HI","year":2027,"start_week":10,"top":1,"commits":4,"user":null}"#,
    )
    .unwrap();
    let old = run(&["--no-colour"]);
    assert!(
        old.status.success(),
        "{}",
        String::from_utf8_lossy(&old.stderr)
    );
    assert!(
        !stdout(&old).contains("background level"),
        "an old plan draws no background: {}",
        stdout(&old)
    );

    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn a_background_check_meant_for_drawing_does_not_block_tracking() {
    // `--commits` is what `--write` puts on a lit day. Tracking never writes
    // one — it works out what a letter day needs from the year's real peak —
    // so the "these shades cannot be told apart" guard must not fire there.
    //
    // The regression: over a busy year, `--track --merge --background` was
    // refused with "the letters would not show", telling the user their plan
    // was impossible when the only thing wrong was a flag that run ignores.
    // The GitHub Action never hit it (it passes no --merge), so the two
    // disagreed about the same plan.
    let tracking = art(&[
        "VYNCINT",
        "--year",
        "2026",
        "--start-week",
        "6",
        "--background",
        "1",
        "--commits",
        "4",
        "--track",
        "--merge",
        "art/vyncint-2026.json",
        "--today",
        "2026-08-19",
        "--no-colour",
    ]);
    assert!(
        tracking.status.success(),
        "tracking must not be refused over --commits: {}",
        String::from_utf8_lossy(&tracking.stderr)
    );
    let text = stdout(&tracking);
    assert!(
        text.contains("letters at level 4, background at level 1"),
        "and it reports the shades the plan actually wants: {text}"
    );

    // The same flags without --track *would* draw, and there the guard is
    // right: 4 commits in a year peaking in the hundreds is level 1, the same
    // as the background, so the letters would be invisible.
    let drawing = art(&[
        "VYNCINT",
        "--year",
        "2026",
        "--start-week",
        "6",
        "--background",
        "1",
        "--commits",
        "4",
        "--merge",
        "art/vyncint-2026.json",
        "--no-colour",
    ]);
    assert!(
        !drawing.status.success(),
        "drawing with indistinguishable shades is still refused"
    );
    let error = String::from_utf8_lossy(&drawing.stderr).into_owned();
    assert!(error.contains("would not show"), "{error}");
}

#[test]
fn a_hole_is_called_a_hole_not_a_background_at_level_zero() {
    // With no background there is no field, so describing a spoiled day as
    // "background — 113 contributions, 113 too many for level 0" names a shade
    // the plan never asked for. Inside the letters it is a hole, and that is
    // what it has to say — the markdown report always got this right, so the
    // text report was the one disagreeing.
    //
    // 2026-08-19 is a lit day inside the letters in the calendar this reads, and
    // it is pinned rather than left to the clock. Without `--today` this test
    // asserted that whatever day it happened to run on was one of those, which
    // held on the day it was written and failed the morning after.
    let out = art(&[
        "VYNCINT",
        "--year",
        "2026",
        "--track",
        "--merge",
        "art/vyncint-2026.json",
        "--today",
        "2026-08-19",
        "--no-colour",
    ]);
    assert!(out.status.success());
    let text = stdout(&out);
    let today = text
        .lines()
        .find(|line| line.trim_start().starts_with("today"))
        .expect("a year under way reports on today");
    assert!(
        !today.contains("level 0"),
        "there is no level-0 background to be over: {today}"
    );
    assert!(
        today.contains("permanent hole"),
        "a lit day inside the letters is a hole: {today}"
    );
}

#[test]
fn a_day_that_must_stay_dark_says_so_before_it_arrives() {
    // 2026-08-20 sits inside VYNCINT's block and is not part of a letter, so a
    // contribution on it punches a hole nothing takes back. Every surface used
    // to call it free — "not part of the text — anything you commit today
    // shows" — because a clean day inside the text was dropped from the plan
    // for having nothing to say. It has the most to say of any day in the year.
    let args = |format: &'static str| -> Vec<&'static str> {
        vec![
            "VYNCINT",
            "--year",
            "2026",
            "--track",
            "--merge",
            "art/vyncint-2026.json",
            "--today",
            "2026-08-20",
            "--no-colour",
            "--format",
            format,
        ]
    };

    let text = stdout(&art(&args("text")));
    let today = text
        .lines()
        .find(|line| line.trim_start().starts_with("today"))
        .expect("a year under way reports on today");
    assert!(
        today.contains("keep it dark"),
        "the instruction has to be the instruction: {today}"
    );
    assert!(
        !today.contains("anything committed on it shows"),
        "and never the opposite of it: {today}"
    );
    // The seven-day schedule is where it is read a day early, which is the only
    // time the warning is worth anything.
    assert!(
        text.contains("Thu Aug 20   keep dark"),
        "the schedule names it too:\n{text}"
    );

    // And a machine reading the report gets the same answer, with a ceiling of
    // zero rather than the `null` that said "nothing is asked of this day".
    let json: serde_json::Value = serde_json::from_str(&stdout(&art(&args("json")))).expect("json");
    assert_eq!(json["today"]["kind"], "keep-dark");
    assert_eq!(json["today"]["ceiling"], 0);
    assert_eq!(json["today"]["over"], 0, "clean, so not yet a hole");
    // The count of real holes must not move: a day that must stay dark and has
    // is not damage.
    assert_eq!(json["holes"], 61);

    let md = stdout(&art(&args("markdown")));
    assert!(
        md.contains("| today | inside the letters — keep it dark |"),
        "{md}"
    );
}

#[test]
fn today_is_an_input_so_a_report_is_reproducible() {
    // The whole reason `--today` exists: the answer to "what does today owe"
    // has to be a fact about a calendar and a date, not about when the command
    // ran. Two different dates, two different answers, both stable forever.
    let on = |date: &str| {
        stdout(&art(&[
            "VYNCINT",
            "--year",
            "2026",
            "--track",
            "--merge",
            "art/vyncint-2026.json",
            "--today",
            date,
            "--no-colour",
        ]))
    };

    let lit = on("2026-08-19");
    assert!(
        lit.contains("today       Wed Aug 19"),
        "the date it was told, not the date it is: {lit}"
    );
    let dark = on("2026-08-20");
    assert!(dark.contains("today       Thu Aug 20"), "{dark}");
    assert_ne!(
        lit, dark,
        "two days inside the same block, reported differently"
    );
    // Run twice, byte for byte the same — which is what the clock never was.
    assert_eq!(lit, on("2026-08-19"));

    // A date the plan's year does not hold is not an answer about that plan.
    // Tracking 2026 in 2027 used to report on a day in 2027 and call it
    // `outside`, which is true of the wrong calendar.
    let out = art(&[
        "VYNCINT",
        "--year",
        "2026",
        "--track",
        "--merge",
        "art/vyncint-2026.json",
        "--today",
        "2027-03-01",
        "--format",
        "json",
    ]);
    let json: serde_json::Value = serde_json::from_str(&stdout(&out)).expect("json");
    assert!(json["today"].is_null(), "{}", json["today"]);
    assert!(json["tomorrow"].is_null(), "{}", json["tomorrow"]);
    // And it says so, because `--today` carries no year of its own: the whole
    // "what to do next" half of the report disappears otherwise, which looks
    // like a bug rather than like an answer.
    let note = String::from_utf8_lossy(&out.stderr).into_owned();
    assert!(note.contains("2027-03-01 is after 2026"), "{note}");
    assert!(
        note.contains("no today or tomorrow"),
        "and why that matters: {note}"
    );

    for bad in ["notadate", "2026-13-01", "1999-01-01"] {
        let out = art(&["VYNCINT", "--track", "--today", bad]);
        assert!(!out.status.success(), "--today {bad} was accepted");
        assert_eq!(out.status.code(), Some(2));
    }
}

#[test]
fn numeric_flags_are_bounded_rather_than_cast() {
    // `--year` was range-checked because one binary once passed 999999 through
    // to a panic. Every other number took the unguarded path and `as` is not a
    // check: `--commits -1` came out as 4,294,967,295 — which `--write` would
    // then try to build a fast-import stream for — and `--start-week -1`
    // reached `usize::MAX`, where building a date from it panicked.
    for (flag, value, wanted) in [
        ("--commits", "-1", "between 1 and 1000000"),
        ("--commits", "0", "between 1 and 1000000"),
        ("--top", "-1", "between 0 and 2"),
        ("--top", "9", "between 0 and 2"),
        ("--start-week", "-1", "between 0 and 60"),
        ("--background", "-1", "between 0 and 4"),
    ] {
        let out = art(&["VYNCINT", "--year", "2027", flag, value]);
        let error = String::from_utf8_lossy(&out.stderr).into_owned();
        assert!(!out.status.success(), "{flag} {value} was accepted");
        assert_eq!(out.status.code(), Some(2), "{flag} {value}");
        assert!(error.contains(wanted), "{flag} {value}: {error}");
        assert!(!error.contains("panicked"), "{flag} {value}: {error}");
    }

    // In range for the flag but not for the year: the tight bound needs both
    // the calendar and the text, so `place` is what refuses it — and it names
    // the last column that would have fitted rather than drawing nothing.
    let out = art(&["VYNCINT", "--year", "2027", "--start-week", "20"]);
    assert!(!out.status.success());
    let error = String::from_utf8_lossy(&out.stderr).into_owned();
    assert!(error.contains("past the end of 2027"), "{error}");
    assert!(error.contains("the last one that fits is 12"), "{error}");
}

#[test]
fn a_saved_plan_remembers_who_to_track() {
    // The plan stores whose contributions to compare against, and `--track`
    // threw it away: the user was read out of the file and then overwritten
    // with the nothing a bare `--track` carries. With `gh` off PATH the loss is
    // visible; with `gh` present it was worse than visible, because it tracked
    // the authenticated user while reporting against someone else's plan.
    let dir = scratch("plan-user-test");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(
        dir.join("mossaic-plan.json"),
        r#"{"text":"HI","year":2026,"start_week":10,"top":1,"commits":4,
            "background":0,"user":"octocat"}"#,
    )
    .unwrap();

    let out = Command::new(env!("CARGO_BIN_EXE_mossaic-art"))
        .current_dir(&dir)
        .env("PATH", "/nonexistent")
        .args(["--track"])
        .output()
        .expect("the art binary runs");
    let error = String::from_utf8_lossy(&out.stderr).into_owned();
    assert!(
        error.contains("octocat"),
        "the plan named who to track: {error}"
    );
    assert!(
        !error.contains("could not tell whose"),
        "it knew all along — it just threw the answer away: {error}"
    );

    // A user typed on the command line still wins over the saved one.
    let typed = Command::new(env!("CARGO_BIN_EXE_mossaic-art"))
        .current_dir(&dir)
        .env("PATH", "/nonexistent")
        .args(["--track", "someone-else"])
        .output()
        .expect("the art binary runs");
    let error = String::from_utf8_lossy(&typed.stderr).into_owned();
    assert!(error.contains("someone-else"), "{error}");
    assert!(!error.contains("octocat"), "{error}");

    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn a_calendar_from_another_year_says_so() {
    // Every day of a 2026 calendar falls outside a 2027 grid, so it filters
    // down to nothing and everything downstream is correct about an empty year:
    // 9,527 contributions read as none, and a plan that cannot be drawn reads
    // as reachable at one commit a day. Silence there is the same mistake the
    // plan file was introduced to prevent.
    let out = art(&[
        "VYNCINT",
        "--year",
        "2027",
        "--track",
        "--merge",
        "art/vyncint-2026.json",
        "--today",
        "2027-06-01",
        "--no-colour",
    ]);
    assert!(out.status.success(), "a warning, not a refusal");
    let error = String::from_utf8_lossy(&out.stderr).into_owned();
    assert!(error.contains("holds no contributions in 2027"), "{error}");
    assert!(error.contains("it covers 2026"), "{error}");
    assert_eq!(
        error
            .lines()
            .filter(|line| line.contains("holds no"))
            .count(),
        1,
        "said once, not once per read: {error}"
    );

    // The matching year is quiet.
    let fine = art(&[
        "VYNCINT",
        "--year",
        "2026",
        "--track",
        "--merge",
        "art/vyncint-2026.json",
        "--today",
        "2026-08-19",
        "--no-colour",
    ]);
    assert!(!String::from_utf8_lossy(&fine.stderr).contains("holds no"));
}

#[test]
fn backfill_commits_only_what_is_short() {
    // The command `--track` used to print was a plain `--write`, which puts the
    // same flat count on every lit day — including the ones already bright, and
    // adding to the busiest of them raises the very peak every letter day is
    // measured against. A shortfall cannot do that.
    let dir = scratch("backfill-test");
    let _ = std::fs::remove_dir_all(&dir);
    let repo = dir.to_string_lossy().into_owned();

    // A finished plan is short of nothing at all.
    let done = art(&[
        "VYNCINT",
        "--year",
        "2027",
        "--backfill",
        "--merge",
        "art/vyncint-2027.json",
        "--repo",
        &repo,
        "--today",
        "2027-12-31",
        "--no-colour",
    ]);
    assert!(
        done.status.success(),
        "{}",
        String::from_utf8_lossy(&done.stderr)
    );
    assert!(
        stdout(&done).contains("nothing to backfill"),
        "{}",
        stdout(&done)
    );
    assert!(!dir.exists(), "and it made no repository to do it in");

    // HI over that same calendar: some of its letter days are already lit by
    // VYNCINT's, and those must be left alone.
    let out = art(&[
        "HI",
        "--year",
        "2027",
        "--backfill",
        "--merge",
        "art/vyncint-2027.json",
        "--repo",
        &repo,
        "--write",
        // Past-only, so the run has to be told about a day after the letters it
        // is meant to reach. Without this the whole of 2027 is still to come and
        // there is correctly nothing to back-date.
        "--today",
        "2027-12-31",
        "--no-colour",
    ]);
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let text = stdout(&out);
    assert!(text.contains("backfilling against"), "{text}");
    assert!(text.contains("never a flat count"), "{text}");
    assert!(text.contains("nothing has been pushed"), "{text}");

    // What git actually holds: every commit dated in the plan's year, and every
    // day it touched short of the four that calendar's peak asks for.
    let log = Command::new("git")
        .current_dir(&dir)
        .args(["log", "--format=%ad", "--date=short"])
        .output()
        .expect("git log runs");
    let dates: Vec<String> = String::from_utf8_lossy(&log.stdout)
        .lines()
        .map(str::to_string)
        .collect();
    assert!(!dates.is_empty(), "it wrote commits");
    assert!(
        dates.iter().all(|date| date.starts_with("2027-")),
        "back-dated into the plan's year: {dates:?}"
    );
    let mut per_day: std::collections::BTreeMap<&String, usize> = std::collections::BTreeMap::new();
    for date in &dates {
        *per_day.entry(date).or_default() += 1;
    }
    assert!(
        per_day.values().all(|count| *count == 4),
        "each short day gets exactly what it lacked of 4: {per_day:?}"
    );

    // A dry run is a dry run: nothing new after it.
    let before = dates.len();
    let dry = art(&[
        "HI",
        "--year",
        "2027",
        "--backfill",
        "--merge",
        "art/vyncint-2027.json",
        "--repo",
        &repo,
        "--today",
        "2027-12-31",
        "--no-colour",
    ]);
    assert!(
        stdout(&dry).contains("this was a dry run"),
        "{}",
        stdout(&dry)
    );
    let after = Command::new("git")
        .current_dir(&dir)
        .args(["rev-list", "--count", "HEAD"])
        .output()
        .expect("git rev-list runs");
    assert_eq!(
        String::from_utf8_lossy(&after.stdout).trim(),
        before.to_string(),
        "a dry run wrote something"
    );

    // The two modes are different questions, and running both would mean
    // guessing which was meant.
    let both = art(&["VYNCINT", "--track", "--backfill"]);
    assert!(!both.status.success());
    assert!(String::from_utf8_lossy(&both.stderr).contains("pick one"));

    // And it needs somewhere to write.
    let nowhere = art(&["VYNCINT", "--year", "2027", "--backfill"]);
    assert!(!nowhere.status.success());
    assert!(String::from_utf8_lossy(&nowhere.stderr).contains("--repo"));

    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn a_plan_file_cannot_smuggle_past_the_flag_bounds() {
    // The flags are bounded; a plan file was not, and `--plan PATH` is a path.
    // Each of these got past a different guard: `top` wrapped `place`'s check
    // and drew the letters on scrambled rows, `commits` quoted four billion a
    // day, and the two years panicked or drew a calendar `--year` refuses.
    let dir = scratch("plan-bounds-test");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();

    let run = |plan: &str| {
        std::fs::write(dir.join("mossaic-plan.json"), plan).unwrap();
        Command::new(env!("CARGO_BIN_EXE_mossaic-art"))
            .current_dir(&dir)
            .args(["--no-colour"])
            .output()
            .expect("the art binary runs")
    };
    let plan = |field: &str, value: &str| {
        let mut fields = [
            ("text", "\"HI\""),
            ("year", "2027"),
            ("start_week", "10"),
            ("top", "1"),
            ("commits", "4"),
            ("background", "0"),
            ("user", "null"),
        ];
        for entry in fields.iter_mut() {
            if entry.0 == field {
                entry.1 = value;
            }
        }
        let body: Vec<String> = fields
            .iter()
            .map(|(key, val)| format!("\"{key}\":{val}"))
            .collect();
        format!("{{{}}}", body.join(","))
    };

    for (field, value, wanted) in [
        ("top", "18446744073709551615", "between 0 and 2"),
        ("commits", "4294967295", "between 1 and 1000000"),
        ("commits", "0", "between 1 and 1000000"),
        ("year", "-262143", "between 2000 and 2100"),
        ("year", "180000", "between 2000 and 2100"),
        ("start_week", "18446744073709551615", "between 0 and 60"),
        ("background", "9", "between 0 and 4"),
    ] {
        let out = run(&plan(field, value));
        let error = String::from_utf8_lossy(&out.stderr).into_owned();
        assert!(!out.status.success(), "plan {field}={value} was accepted");
        assert_eq!(out.status.code(), Some(2), "{field}={value}");
        assert!(
            error.contains("is not a plan these tools can use"),
            "{field}={value}: {error}"
        );
        // And it names the way out, because 0.2.0 could write a plan this
        // refuses: it accepted `--commits -1`, which `--save` wrote down as four
        // billion.
        assert!(error.contains("--save"), "{field}={value}: {error}");
        assert!(error.contains(wanted), "{field}={value}: {error}");
        assert!(!error.contains("panicked"), "{field}={value}: {error}");
        // The refusal names the value it refused, not a wrapped version of it.
        assert!(error.contains(value), "{field}={value}: {error}");
    }

    // And a sound plan still loads, or this test would pass by refusing
    // everything.
    let out = run(&plan("text", "\"HI\""));
    assert!(
        out.status.success(),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(stdout(&out).contains("HI  ·  2027"), "{}", stdout(&out));

    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn backfill_reaches_only_the_days_that_have_gone() {
    // `--track` prints this command under "only back-dated commits reach
    // those", and the help calls it the flag for catching up — but it wrote the
    // whole year, future days included, and ignored `--today` entirely. A day
    // still to come wants an ordinary commit when it arrives, and whether
    // GitHub counts a future-dated one is unverified.
    let args = |today: &'static str| -> Vec<&'static str> {
        vec![
            "VYNCINT",
            "--year",
            "2026",
            "--backfill",
            "--merge",
            "art/vyncint-2026.json",
            "--repo",
            "/nonexistent-dry-run",
            "--today",
            today,
            "--no-colour",
        ]
    };

    let mid = stdout(&art(&args("2026-08-19")));
    // The same 34 days and 3,464 commits `--track` calls "already past": both
    // answers come from one plan and one date, so they agree by construction.
    assert!(mid.contains("3,464 commit(s) across 34 day(s)"), "{mid}");
    assert!(
        mid.contains("latest 2026-08-14"),
        "nothing after today: {mid}"
    );
    assert!(
        mid.contains("23 day(s) from 2026-08-19 on are short too, and left alone"),
        "and it says what it is leaving: {mid}"
    );

    // Later in the year, more of it is reachable.
    let end = stdout(&art(&args("2026-12-31")));
    assert!(end.contains("5,994 commit(s) across 57 day(s)"), "{end}");

    // Before the year starts, none of it is — and it says why rather than
    // claiming the plan is finished.
    let early = stdout(&art(&args("2026-01-01")));
    assert!(
        early.contains("every day the plan is short of is still to come"),
        "{early}"
    );

    // A year that cannot be drawn cleanly says so before an irreversible write.
    assert!(
        mid.contains("cannot be drawn cleanly in 2026") && mid.contains("61 day(s) inside the"),
        "a warning belongs where the commits do: {mid}"
    );
}

#[test]
fn tracking_a_year_that_has_not_started_is_not_a_mistake() {
    // The first example in the help, the README and docs/ART.md. The clock is
    // not in 2027, and that is the normal case — the report answers it properly.
    // A note saying "add --year 2026" told people their own year was wrong.
    let out = art(&[
        "VYNCINT",
        "--year",
        "2027",
        "--track",
        "--merge",
        "art/vyncint-2027.json",
        "--today",
        "2026-08-19",
        "--no-colour",
    ]);
    assert!(out.status.success());
    let note = String::from_utf8_lossy(&out.stderr).into_owned();
    assert!(note.is_empty(), "nothing to warn about: {note}");
    assert!(
        stdout(&out).contains("2027 has not started"),
        "{}",
        stdout(&out)
    );
    // Nor when the date comes from the clock, whatever year that turns out to
    // be: the note is about a year that has ended, not about one it is not.
    let bare = art(&[
        "VYNCINT",
        "--year",
        "2100",
        "--track",
        "--merge",
        "art/vyncint-2027.json",
        "--no-colour",
    ]);
    assert!(String::from_utf8_lossy(&bare.stderr)
        .lines()
        .all(|line| !line.contains("no today or tomorrow")));

    // A typed `--today` that misses the year still explains itself, because
    // there the missing today/tomorrow section is a surprise.
    let missed = art(&[
        "VYNCINT",
        "--year",
        "2026",
        "--track",
        "--merge",
        "art/vyncint-2026.json",
        "--today",
        "2027-03-01",
        "--no-colour",
    ]);
    assert!(String::from_utf8_lossy(&missed.stderr).contains("2027-03-01 is after 2026"));
}

#[test]
fn tracking_refuses_a_flag_it_would_have_ignored() {
    // Tracking writes nothing, so a flag asking it to write was doing nothing at
    // all — silently, which is worse than refusing. Distinct from `--commits`,
    // which tracking has no use for but which is a tuning parameter rather than a
    // side effect somebody asked for.
    for extra in [
        vec!["--snapshot", "/tmp/mossaic-should-not-exist.json"],
        vec!["--write"],
        vec!["--repo", "/tmp/mossaic-should-not-exist"],
    ] {
        let mut args = vec![
            "VYNCINT",
            "--year",
            "2026",
            "--track",
            "--merge",
            "art/vyncint-2026.json",
            "--today",
            "2026-08-19",
            "--no-colour",
        ];
        args.extend_from_slice(&extra);
        let out = art(&args);
        let error = String::from_utf8_lossy(&out.stderr).into_owned();
        assert!(!out.status.success(), "{extra:?} was accepted");
        assert_eq!(out.status.code(), Some(2), "{extra:?}");
        assert!(error.contains("writes nothing"), "{extra:?}: {error}");
        assert!(error.contains(extra[0]), "{extra:?}: {error}");
    }
    assert!(
        !Path::new("/tmp/mossaic-should-not-exist.json").exists(),
        "and nothing was written on the way to refusing"
    );

    // `--commits` is still fine, which is the distinction.
    let fine = art(&[
        "VYNCINT",
        "--year",
        "2026",
        "--track",
        "--merge",
        "art/vyncint-2026.json",
        "--today",
        "2026-08-19",
        "--commits",
        "4",
        "--no-colour",
    ]);
    assert!(
        fine.status.success(),
        "{}",
        String::from_utf8_lossy(&fine.stderr)
    );
}

#[test]
fn every_binary_parses_arguments_the_same_way() {
    // `cli::Args` exists "so that the tools agree about the things a user
    // notices: that `--year 2027` and `--year=2027` are the same, that a missing
    // value says so rather than being read as the next flag, and that every error
    // looks like `mossaic-art: …` and exits 2". `mossaic-glyphs` parsed by hand
    // and agreed about none of it.
    for (name, binary) in [
        ("mossaic", env!("CARGO_BIN_EXE_mossaic")),
        ("mossaic-art", env!("CARGO_BIN_EXE_mossaic-art")),
        ("mossaic-glyphs", env!("CARGO_BIN_EXE_mossaic-glyphs")),
    ] {
        let run = |args: &[&str]| {
            Command::new(binary)
                .current_dir(env!("CARGO_MANIFEST_DIR"))
                .args(args)
                .output()
                .expect("runs")
        };

        // An unknown option is an error, and says whose.
        let out = run(&["--definitely-not-a-flag"]);
        let error = String::from_utf8_lossy(&out.stderr).into_owned();
        assert_eq!(out.status.code(), Some(2), "{name}: {error}");
        assert!(error.starts_with(&format!("{name}: ")), "{name}: {error}");
        assert!(error.contains("unknown option"), "{name}: {error}");

        // `--key=value` is the same as `--key value`: forced colour reaches a pipe
        // either way. (`mossaic` needs a source it can render without a network.)
        let colour_args: Vec<Vec<&str>> = match name {
            "mossaic-art" => vec![
                vec!["--font", "--color", "always"],
                vec!["--font", "--color=always"],
            ],
            "mossaic-glyphs" => vec![vec!["--color", "always"], vec!["--color=always"]],
            // The chart's colour comes from the terminal, not a flag; check the
            // `=` form on one it does take.
            _ => vec![
                vec!["--demo", "--png", "/dev/null", "--theme", "light"],
                vec!["--demo", "--png", "/dev/null", "--theme=light"],
            ],
        };
        let mut outcomes = Vec::new();
        for args in &colour_args {
            let out = run(&args.to_vec());
            outcomes.push((
                out.status.success(),
                String::from_utf8_lossy(&out.stdout).contains('\x1b'),
            ));
        }
        assert_eq!(
            outcomes[0], outcomes[1],
            "{name}: the `=` form behaves differently"
        );
        assert!(outcomes[0].0, "{name}: the spaced form should work at all");

        // A missing value says so rather than swallowing the next argument.
        let flag = match name {
            "mossaic-glyphs" => "--color",
            _ => "--year",
        };
        let out = run(&[flag]);
        let error = String::from_utf8_lossy(&out.stderr).into_owned();
        assert_eq!(out.status.code(), Some(2), "{name} {flag}: {error}");
        assert!(
            error.contains("needs a value") || error.contains("wants a"),
            "{name} {flag}: {error}"
        );
    }
}