mossaic 0.8.0

Draw pixel art in your GitHub contribution graph — a terminal chart, an editor, and a planner that says what today owes
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
//! Writing text into a contribution graph by dating commits.
//!
//! Each letter is drawn as pixels on the year's 7×53 calendar, every lit pixel
//! is mapped to a date, and the commits that would light it up are emitted.
//! Nothing here pushes anything: [`write_commits`] makes local commits in a
//! directory you name, and the caller prints the push command.
//!
//! The costing is the interesting part. GitHub's shade for a day is
//! `min(4, ceil(count * 4 / peak))` where `peak` is the busiest day of that
//! year — equal slices of `[0, peak]`, not rank quartiles — so drawing over an
//! active year is priced by its busiest day, and raising the count raises the
//! peak along with it. [`commits_for_level`] solves for the figure rather than
//! estimating it.

use std::collections::BTreeMap;
use std::io::Write;
use std::path::Path;
use std::process::{Command, Stdio};

use chrono::{Datelike, Days, NaiveDate};

use crate::primer::{Appearance, Legibility, Palette, Season};

/// Rows in a glyph. Letters are five tall, placed on Mon-Fri, which leaves
/// Sunday and Saturday clear.
pub const GLYPH_ROWS: usize = 5;
/// Columns in a glyph. Uniform, so letters line up and `6N - 1` describes the
/// width of any text — the placement, the centring and the eight-character
/// limit all rest on it.
pub const GLYPH_COLS: usize = 5;
/// Rows in a calendar week, Sunday first. Public because it is what bounds
/// `--top`: five rows of glyph have to fit inside it.
pub const WEEKDAYS: usize = 7;

/// The font: `#` lights a day, `.` leaves it dark.
///
/// # Adding a glyph
///
/// Add a row to this table and nothing else — [`alphabet`], the previews and
/// the error message for unknown characters all read from it. Three rules,
/// every one of them checked when the crate compiles rather than when someone
/// runs it:
///
/// 1. exactly [`GLYPH_ROWS`] rows of exactly [`GLYPH_COLS`] characters,
/// 2. only `#` and `.`,
/// 3. no character twice.
///
/// Break one and the build stops with the reason. `mossaic-art --font` prints the whole
/// set, which is the quickest way to see what a new glyph actually looks like
/// next to its neighbours.
///
/// The table is uppercase because [`bitmap`] folds its input, but it looks up
/// the character as written first — so lowercase glyphs can be added later
/// without touching anything else.
const FONT: &[(char, [&str; GLYPH_ROWS])] = &[
    ('A', [".###.", "#...#", "#####", "#...#", "#...#"]),
    ('B', ["####.", "#...#", "####.", "#...#", "####."]),
    ('C', [".###.", "#...#", "#....", "#...#", ".###."]),
    ('D', ["####.", "#...#", "#...#", "#...#", "####."]),
    ('E', ["#####", "#....", "####.", "#....", "#####"]),
    ('F', ["#####", "#....", "####.", "#....", "#...."]),
    ('G', [".###.", "#....", "#..##", "#...#", ".###."]),
    ('H', ["#...#", "#...#", "#####", "#...#", "#...#"]),
    ('I', ["#####", "..#..", "..#..", "..#..", "#####"]),
    ('J', ["....#", "....#", "....#", "#...#", ".###."]),
    ('K', ["#...#", "#..#.", "###..", "#..#.", "#...#"]),
    ('L', ["#....", "#....", "#....", "#....", "#####"]),
    ('M', ["#...#", "##.##", "#.#.#", "#...#", "#...#"]),
    ('N', ["#...#", "##..#", "#.#.#", "#..##", "#...#"]),
    ('O', [".###.", "#...#", "#...#", "#...#", ".###."]),
    ('P', ["####.", "#...#", "####.", "#....", "#...."]),
    ('Q', [".###.", "#...#", "#.#.#", "#..#.", ".##.#"]),
    ('R', ["####.", "#...#", "####.", "#..#.", "#...#"]),
    ('S', [".####", "#....", ".###.", "....#", "####."]),
    ('T', ["#####", "..#..", "..#..", "..#..", "..#.."]),
    ('U', ["#...#", "#...#", "#...#", "#...#", ".###."]),
    ('V', ["#...#", "#...#", "#...#", ".#.#.", "..#.."]),
    ('W', ["#...#", "#...#", "#.#.#", "##.##", "#...#"]),
    ('X', ["#...#", ".#.#.", "..#..", ".#.#.", "#...#"]),
    ('Y', ["#...#", ".#.#.", "..#..", "..#..", "..#.."]),
    ('Z', ["#####", "...#.", "..#..", ".#...", "#####"]),
    ('0', [".###.", "#..##", "#.#.#", "##..#", ".###."]),
    ('1', ["..#..", ".##..", "..#..", "..#..", ".###."]),
    ('2', [".###.", "#...#", "..##.", ".#...", "#####"]),
    ('3', ["####.", "....#", "..##.", "....#", "####."]),
    ('4', ["#..#.", "#..#.", "#####", "...#.", "...#."]),
    ('5', ["#####", "#....", "####.", "....#", "####."]),
    ('6', [".###.", "#....", "####.", "#...#", ".###."]),
    ('7', ["#####", "....#", "...#.", "..#..", ".#..."]),
    ('8', [".###.", "#...#", ".###.", "#...#", ".###."]),
    ('9', [".###.", "#...#", ".####", "....#", ".###."]),
    (' ', [".....", ".....", ".....", ".....", "....."]),
    ('-', [".....", ".....", "#####", ".....", "....."]),
    ('.', [".....", ".....", ".....", ".....", "..#.."]),
    ('!', ["..#..", "..#..", "..#..", ".....", "..#.."]),
    ('?', [".###.", "#...#", "..##.", ".....", "..#.."]),
    (',', [".....", ".....", ".....", "..#..", ".#..."]),
    ('\'', ["..#..", "..#..", ".....", ".....", "....."]),
    ('"', [".#.#.", ".#.#.", ".....", ".....", "....."]),
    ('+', [".....", "..#..", "#####", "..#..", "....."]),
    ('=', [".....", "#####", ".....", "#####", "....."]),
    ('<', ["...#.", "..#..", ".#...", "..#..", "...#."]),
    ('>', [".#...", "..#..", "...#.", "..#..", ".#..."]),
    ('(', ["..##.", ".#...", ".#...", ".#...", "..##."]),
    (')', [".##..", "...#.", "...#.", "...#.", ".##.."]),
    ('/', ["....#", "...#.", "..#..", ".#...", "#...."]),
    ('\\', ["#....", ".#...", "..#..", "...#.", "....#"]),
    ('*', [".....", "#.#.#", ".###.", "#.#.#", "....."]),
    ('_', [".....", ".....", ".....", ".....", "#####"]),
    ('@', [".###.", "#...#", "#.##.", "#....", ".###."]),
    ('&', [".##..", "#..#.", ".##..", "#..#.", ".##.#"]),
    ('#', [".#.#.", "#####", ".#.#.", "#####", ".#.#."]),
    ('%', ["#...#", "...#.", "..#..", ".#...", "#...#"]),
    // ------------------------------------------------------------- shapes
    //
    // Keyed by the symbol itself, so `mossaic-art "I \u{2665} RUST"` works if you
    // can type one; `:heart:` is the way in if you cannot. Every one is
    // named in `SHAPES` below, which is what the previews and the error
    // messages print — a name renders in every terminal and every browser,
    // and several of these symbols do not.
    ('\u{2605}', ["..#..", ".###.", "#####", ".#.#.", "#...#"]),
    ('\u{2665}', [".#.#.", "#####", "#####", ".###.", "..#.."]),
    ('\u{263a}', [".###.", "#.#.#", "#####", ".###.", "#...#"]),
    ('\u{2639}', [".###.", "#.#.#", "#####", "#...#", ".###."]),
    ('\u{2713}', [".....", "....#", "...#.", "#.#..", ".#..."]),
    ('\u{25cf}', [".###.", "#####", "#####", "#####", ".###."]),
    ('\u{25a1}', ["#####", "#...#", "#...#", "#...#", "#####"]),
    ('\u{25b2}', ["..#..", "..#..", ".###.", ".###.", "#####"]),
    ('\u{25c6}', ["..#..", ".###.", "#####", ".###.", "..#.."]),
    ('\u{266a}', ["...##", "...#.", "...#.", ".###.", ".##.."]),
    ('\u{2600}', ["#.#.#", ".###.", "#####", ".###.", "#.#.#"]),
    ('\u{263e}', [".###.", "##...", "##...", "##...", ".###."]),
    ('\u{26a1}', ["...##", "..##.", ".###.", "..#..", ".#..."]),
    ('\u{2191}', ["..#..", ".###.", "#.#.#", "..#..", "..#.."]),
    ('\u{2193}', ["..#..", "..#..", "#.#.#", ".###.", "..#.."]),
    ('\u{2190}', ["..#..", ".#...", "#####", ".#...", "..#.."]),
    ('\u{2192}', ["..#..", "...#.", "#####", "...#.", "..#.."]),
    ('\u{2620}', [".###.", "#####", "#.#.#", ".###.", ".#.#."]),
    ('\u{273f}', [".#.#.", "#####", ".###.", "..#..", "..#.."]),
];

/// The shapes, by the name you type between colons.
///
/// # Adding a shape
///
/// Two lines: the glyph goes in [`FONT`] keyed by its symbol, and its name or
/// names go here. Both are checked when the crate compiles — a name for a
/// character the font does not have, a name that is not lowercase ASCII, and
/// the same name twice are all build failures.
///
/// Several names may point at one character; the **first** is the one the
/// previews and the error messages print.
const SHAPES: &[(&str, char)] = &[
    ("star", '\u{2605}'),
    ("heart", '\u{2665}'),
    ("love", '\u{2665}'),
    ("smile", '\u{263a}'),
    ("happy", '\u{263a}'),
    ("sad", '\u{2639}'),
    ("cry", '\u{2639}'),
    ("frown", '\u{2639}'),
    ("check", '\u{2713}'),
    ("tick", '\u{2713}'),
    ("circle", '\u{25cf}'),
    ("dot", '\u{25cf}'),
    ("square", '\u{25a1}'),
    ("triangle", '\u{25b2}'),
    ("diamond", '\u{25c6}'),
    ("note", '\u{266a}'),
    ("music", '\u{266a}'),
    ("sun", '\u{2600}'),
    ("moon", '\u{263e}'),
    ("bolt", '\u{26a1}'),
    ("zap", '\u{26a1}'),
    ("up", '\u{2191}'),
    ("down", '\u{2193}'),
    ("left", '\u{2190}'),
    ("right", '\u{2192}'),
    ("skull", '\u{2620}'),
    ("flower", '\u{273f}'),
];

/// Characters that mean a shape the font already draws.
///
/// Someone who pastes an emoji has said exactly what they meant, and refusing
/// it over a codepoint would be pedantry: \u{2b50} is a star, \u{2764} is a heart, and
/// neither is the codepoint the font is keyed by. Folded rather than added to
/// the font, so there is still one bitmap per shape.
const FOLD: &[(char, char)] = &[
    ('\u{2b50}', '\u{2605}'),
    ('\u{2606}', '\u{2605}'),
    ('\u{2729}', '\u{2605}'),
    ('\u{272d}', '\u{2605}'),
    ('\u{2764}', '\u{2665}'),
    ('\u{2661}', '\u{2665}'),
    ('\u{1f499}', '\u{2665}'),
    ('\u{1f49a}', '\u{2665}'),
    ('\u{1f49c}', '\u{2665}'),
    ('\u{1f9e1}', '\u{2665}'),
    ('\u{263b}', '\u{263a}'),
    ('\u{1f600}', '\u{263a}'),
    ('\u{1f603}', '\u{263a}'),
    ('\u{1f642}', '\u{263a}'),
    ('\u{1f60a}', '\u{263a}'),
    ('\u{1f641}', '\u{2639}'),
    ('\u{1f622}', '\u{2639}'),
    ('\u{1f62d}', '\u{2639}'),
    ('\u{2714}', '\u{2713}'),
    ('\u{2705}', '\u{2713}'),
    ('\u{25cb}', '\u{25cf}'),
    ('\u{2b24}', '\u{25cf}'),
    ('\u{25fb}', '\u{25a1}'),
    ('\u{25a0}', '\u{25a1}'),
    ('\u{25fc}', '\u{25a1}'),
    ('\u{25b3}', '\u{25b2}'),
    ('\u{25c7}', '\u{25c6}'),
    ('\u{266b}', '\u{266a}'),
    ('\u{1f3b5}', '\u{266a}'),
    ('\u{1f31e}', '\u{2600}'),
    ('\u{1f319}', '\u{263e}'),
    ('\u{263d}', '\u{263e}'),
    ('\u{1f5f2}', '\u{26a1}'),
    ('\u{1f480}', '\u{2620}'),
    ('\u{1f338}', '\u{273f}'),
    ('\u{1f337}', '\u{273f}'),
];

/// The font's rules, enforced at compile time. A glyph contributed with a row a
/// character short used to be a panic at the first person to draw it; now it is
/// a build failure with the reason, before it can be merged.
const _: () = {
    let mut index = 0;
    while index < FONT.len() {
        let (character, rows) = FONT[index];

        let mut row = 0;
        while row < GLYPH_ROWS {
            let bytes = rows[row].as_bytes();
            assert!(
                bytes.len() == GLYPH_COLS,
                "every glyph row must be GLYPH_COLS characters wide"
            );
            let mut column = 0;
            while column < bytes.len() {
                assert!(
                    bytes[column] == b'#' || bytes[column] == b'.',
                    "glyph rows are made of '#' and '.' only"
                );
                column += 1;
            }
            row += 1;
        }

        let mut other = 0;
        while other < index {
            assert!(
                FONT[other].0 as u32 != character as u32,
                "the same character is in the font twice"
            );
            other += 1;
        }
        index += 1;
    }

    // A shape name has to name a character the font can actually draw, be
    // typeable between colons, and mean one thing.
    let mut index = 0;
    while index < SHAPES.len() {
        let (name, character) = SHAPES[index];
        assert!(
            in_font(character),
            "a shape names a character the font lacks"
        );

        let bytes = name.as_bytes();
        assert!(!bytes.is_empty(), "a shape name must not be empty");
        let mut byte = 0;
        while byte < bytes.len() {
            assert!(
                (bytes[byte] >= b'a' && bytes[byte] <= b'z') || bytes[byte] == b'-',
                "shape names are lowercase ASCII, so :NAME: folds to one thing"
            );
            byte += 1;
        }

        let mut other = 0;
        while other < index {
            assert!(!same(SHAPES[other].0, name), "the same shape name twice");
            other += 1;
        }
        index += 1;
    }

    // Nothing may fold to a character the font cannot draw, and a character
    // that folds must not also be in the font — one bitmap per shape.
    let mut index = 0;
    while index < FOLD.len() {
        let (from, to) = FOLD[index];
        assert!(in_font(to), "a fold points at a character the font lacks");
        assert!(!in_font(from), "a folded character is also in the font");
        let mut other = 0;
        while other < index {
            assert!(FOLD[other].0 as u32 != from as u32, "the same fold twice");
            other += 1;
        }
        index += 1;
    }
};

/// Whether the font has `character`, at compile time.
const fn in_font(character: char) -> bool {
    let mut index = 0;
    while index < FONT.len() {
        if FONT[index].0 as u32 == character as u32 {
            return true;
        }
        index += 1;
    }
    false
}

/// Whether two names are the same, at compile time.
const fn same(left: &str, right: &str) -> bool {
    let (left, right) = (left.as_bytes(), right.as_bytes());
    if left.len() != right.len() {
        return false;
    }
    let mut index = 0;
    while index < left.len() {
        if left[index] != right[index] {
            return false;
        }
        index += 1;
    }
    true
}

/// The glyph for a character, if the font has one.
///
/// The character as written wins, so a lowercase glyph added to the font table
/// in `src/art.rs` would be used for lowercase text; failing that, its uppercase
/// form is tried, which is what makes `vyncint` and `VYNCINT` draw the same
/// thing today.
pub fn glyph(character: char) -> Option<[&'static str; GLYPH_ROWS]> {
    let exact = |wanted: char| {
        FONT.iter()
            .find(|(candidate, _)| *candidate == wanted)
            .map(|(_, rows)| *rows)
    };
    exact(character)
        .or_else(|| folded(character).and_then(exact))
        .or_else(|| character.to_uppercase().find_map(exact))
}

/// The character `character` stands in for, if it is one the font draws under
/// another codepoint — a pasted \u{2b50} for the font's \u{2605}.
fn folded(character: char) -> Option<char> {
    FOLD.iter()
        .find(|(from, _)| *from == character)
        .map(|(_, to)| *to)
}

/// The character a shape name draws, matched without regard to case so that
/// the uppercasing every plan goes through leaves `:STAR:` meaning a star.
#[must_use]
pub fn shape(name: &str) -> Option<char> {
    SHAPES
        .iter()
        .find(|(candidate, _)| candidate.eq_ignore_ascii_case(name))
        .map(|(_, character)| *character)
}

/// Every shape name, with the character it draws, in the order they are
/// declared — so the first name for a character comes first.
pub fn shapes() -> impl Iterator<Item = (&'static str, char)> {
    SHAPES.iter().copied()
}

/// What to call `character` in a message: `:star:` for a shape, the character
/// itself for anything else.
///
/// Shapes are named rather than printed because a name renders in every
/// terminal and every browser, and several of the symbols do not.
#[must_use]
pub fn label(character: char) -> String {
    match shape_name(character) {
        Some(name) => format!(":{name}:"),
        None if character == ' ' => "space".to_string(),
        None => character.to_string(),
    }
}

/// Reduce text to the characters the font is keyed by: expand `:name:`, drop
/// the variation selectors an emoji keyboard adds, and fold a pasted symbol
/// onto the one the font draws it with.
///
/// This is the whole of the shape grammar: a colon opens a name and the next
/// one closes it. `:` therefore has no glyph of its own — an unclosed one is
/// refused with the list of names rather than drawn, which is the more useful
/// of the two answers by a distance.
///
/// Everything downstream — the uppercasing, the saved plan, the tracker's
/// report — then works on characters, and three spellings of one heart are one
/// heart by the time any of them see it.
pub fn canonical(text: &str) -> Result<String, String> {
    let text: String = text
        .chars()
        // U+FE0F and U+FE0E only say how the character before them should be
        // drawn, and nothing here draws two ways.
        .filter(|character| !matches!(character, '\u{fe0f}' | '\u{fe0e}'))
        .map(|character| folded(character).unwrap_or(character))
        .collect();

    let mut out = String::with_capacity(text.len());
    let mut rest = text.as_str();
    while let Some(open) = rest.find(':') {
        out.push_str(&rest[..open]);
        let after = &rest[open + 1..];
        let Some(close) = after.find(':') else {
            return Err(format!(
                "unclosed ':' — a shape is written :name:, and the font has {}",
                describe_shapes()
            ));
        };
        let name = &after[..close];
        match shape(name) {
            Some(character) => out.push(character),
            None => {
                return Err(format!(
                    "no shape called {name:?} — the font has {}",
                    describe_shapes()
                ))
            }
        }
        rest = &after[close + 1..];
    }
    out.push_str(rest);
    Ok(out)
}

/// Every character the font can draw, in order.
pub fn alphabet() -> impl Iterator<Item = char> {
    FONT.iter().map(|(character, _)| *character)
}

/// The Sunday that starts `day`'s calendar column. Sunday is row 0.
///
/// Panics within six days of the first date a [`NaiveDate`] can hold, where
/// there is no earlier Sunday to name. [`Grid::new`] does this arithmetic
/// checked, because a year reaching it can come from a file.
pub fn sunday_of(day: NaiveDate) -> NaiveDate {
    day - Days::new(u64::from(day.weekday().num_days_from_sunday()))
}

/// The calendar for one year: seven rows by however many Sunday-aligned weeks.
#[derive(Debug, Clone, Copy)]
pub struct Grid {
    /// The calendar year this grid covers.
    pub year: i32,
    /// January 1st.
    pub first: NaiveDate,
    /// December 31st.
    pub last: NaiveDate,
    /// The Sunday that starts column 0, which is usually in the year before.
    pub start: NaiveDate,
    /// Columns, counting the partial weeks at both ends.
    pub weeks: usize,
}

impl Grid {
    /// The calendar for `year`, or `None` for one no calendar can hold.
    ///
    /// Returns rather than panics because this is a library: a year arriving
    /// from a command line, a file or a caller is input, and `--year 999999`
    /// used to end in an `expect`.
    pub fn new(year: i32) -> Option<Self> {
        let first = NaiveDate::from_ymd_opt(year, 1, 1)?;
        let last = NaiveDate::from_ymd_opt(year, 12, 31)?;
        // Checked, not [`sunday_of`]: the first year a calendar can express has
        // no room before it, so stepping back to a Sunday runs off the end and
        // panics. This function promises `None` for a year no calendar can hold,
        // and a year can arrive from a plan file — so it has to keep that
        // promise rather than nearly keep it.
        let start =
            first.checked_sub_days(Days::new(u64::from(first.weekday().num_days_from_sunday())))?;
        Some(Self {
            year,
            first,
            last,
            start,
            weeks: ((last - start).num_days() / 7 + 1) as usize,
        })
    }

    /// The date at a grid position, which may fall outside the year.
    ///
    /// `week` must be less than [`Grid::weeks`] and `row` less than 7 — that is
    /// what "a position on this grid" means, and every caller here walks a
    /// bounded range to satisfy it. Far outside that, adding the offset to a
    /// date runs off the end of the calendar and panics, which is why
    /// [`place`] refuses a start column that would not fit rather than
    /// building dates from it.
    pub fn date_at(&self, week: usize, row: usize) -> NaiveDate {
        self.start + Days::new((week * WEEKDAYS + row) as u64)
    }

    /// Whether `day` is inside the year this grid covers.
    pub fn holds(&self, day: NaiveDate) -> bool {
        self.first <= day && day <= self.last
    }

    /// Columns whose Mon–Fri all fall inside the year. The first and last are
    /// partial weeks, so a letter placed on one loses whatever spills over.
    pub fn usable_weeks(&self) -> usize {
        (0..self.weeks)
            .filter(|week| (1..=5).all(|row| self.holds(self.date_at(*week, row))))
            .count()
    }
}

/// Columns of the rendered text, each `GLYPH_ROWS` tall, with one blank column
/// between letters.
pub fn bitmap(text: &str) -> Result<Vec<[bool; GLYPH_ROWS]>, String> {
    let text = canonical(text)?;
    let unknown: Vec<char> = text.chars().filter(|c| glyph(*c).is_none()).collect();
    if !unknown.is_empty() {
        let names: Vec<String> = unknown.iter().map(|c| format!("{c:?}")).collect();
        return Err(format!(
            "no glyph for: {} — the font has {}",
            names.join(" "),
            describe_alphabet()
        ));
    }

    let mut columns = Vec::new();
    for (index, character) in text.chars().enumerate() {
        let rows = glyph(character).expect("checked above");
        if index > 0 {
            columns.push([false; GLYPH_ROWS]);
        }
        // GLYPH_COLS rather than the first row's length: the width is the same
        // for every glyph, and the compile-time check above is what guarantees it.
        for column in 0..GLYPH_COLS {
            let mut lit = [false; GLYPH_ROWS];
            for (row, line) in rows.iter().enumerate() {
                lit[row] = line.as_bytes()[column] == b'#';
            }
            columns.push(lit);
        }
    }
    Ok(columns)
}

/// The font's contents, for the message someone sees after a typo.
fn describe_alphabet() -> String {
    let printable: String = alphabet()
        .filter(|character| !character.is_whitespace())
        // Shapes are listed by name below; a symbol in the middle of this run
        // would be the one part of the message a terminal might not draw.
        .filter(|character| shape_name(*character).is_none())
        .collect::<Vec<char>>()
        .chunks(36)
        .map(|chunk| chunk.iter().collect::<String>())
        .collect::<Vec<String>>()
        .join(" ");
    format!("{printable} and space, and {}", describe_shapes())
}

/// The shape names, for the same message.
fn describe_shapes() -> String {
    let names: Vec<String> = SHAPES.iter().map(|(name, _)| format!(":{name}:")).collect();
    format!("the shapes {}", names.join(" "))
}

/// The first name declared for `character`, if it is a shape.
#[must_use]
pub fn shape_name(character: char) -> Option<&'static str> {
    SHAPES
        .iter()
        .find(|(_, candidate)| *candidate == character)
        .map(|(name, _)| *name)
}

// ============================================================ the pixel canvas

/// Rows in a full-year canvas: every weekday, Sunday through Saturday.
///
/// A glyph is five tall so that letters sit on Mon–Fri and the weekend stays
/// clear. A canvas has no such courtesy — it is the whole graph, so it is the
/// whole week.
pub const CANVAS_ROWS: usize = WEEKDAYS;

/// The widest a canvas can be. A Sunday-aligned year spans 53 columns at most,
/// which happens when January 1st is a Saturday, or a Friday in a leap year.
pub const CANVAS_COLS: usize = 53;

/// The characters a canvas file may use for each shade, darkest first.
///
/// Two alphabets for the same five levels: digits, which are unambiguous in any
/// editor and any font, and the block glyphs, which let a file be read as a
/// picture rather than as a table of numbers. A file may mix them, because the
/// two say the same thing and refusing a mixture would be pedantry.
pub const SHADE_CHARS: [(char, char); 5] =
    [('0', ' '), ('1', ''), ('2', ''), ('3', ''), ('4', '')];

/// The level a canvas character stands for, or `None` if it is not one.
#[must_use]
pub fn shade_of(character: char) -> Option<u8> {
    SHADE_CHARS
        .iter()
        .position(|(digit, block)| *digit == character || *block == character)
        // A position in a five-element table is a level by construction.
        .map(|level| level as u8)
}

/// What a `.art` file says about itself, from its `# key: value` header.
///
/// Every field is optional. A file with no header at all is still a valid
/// canvas — the header is how a template introduces itself in a listing, not a
/// precondition for drawing it.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Meta {
    /// A display name, from `# name:`.
    pub name: Option<String>,
    /// Who made it, from `# author:`.
    pub author: Option<String>,
    /// One line about it, from `# description:`.
    pub description: Option<String>,
}

/// Pixel art across the whole calendar: one shade per day, seven rows tall.
///
/// This is the general form of what [`bitmap`] produces for text. A glyph
/// column is five booleans — lit or not — because a letter is one shade
/// against another. A canvas column is seven levels, because a picture is
/// however many shades GitHub gives you, and it uses the weekend.
///
/// Stored column-major, like [`bitmap`]'s output, because that is the axis
/// placement walks: a canvas is laid onto the year by choosing which calendar
/// column its first column lands on.
///
/// ```
/// # use mossaic::art::Canvas;
/// let canvas = Canvas::parse("0123\n4321\n0000\n1111\n2222\n3333\n4444\n").unwrap();
/// assert_eq!(canvas.width(), 4);
/// assert_eq!(canvas.at(0, 0), 0); // week 0, Sunday
/// assert_eq!(canvas.at(0, 1), 4); // week 0, Monday
/// assert_eq!(canvas.at(3, 0), 3); // week 3, Sunday
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Canvas {
    /// One entry per calendar column, each seven levels deep, row 0 = Sunday.
    columns: Vec<[u8; CANVAS_ROWS]>,
    /// What the file said about itself.
    meta: Meta,
}

impl Canvas {
    /// An all-dark canvas `width` columns across.
    ///
    /// Returns `None` for a width no calendar column can hold, rather than
    /// clamping: a width comes from a flag or a file, and silently drawing on a
    /// different canvas than the one asked for is worse than refusing.
    #[must_use]
    pub fn blank(width: usize) -> Option<Self> {
        (1..=CANVAS_COLS).contains(&width).then(|| Self {
            columns: vec![[0; CANVAS_ROWS]; width],
            meta: Meta::default(),
        })
    }

    /// Read a canvas from the `.art` format, or say why it could not be read.
    ///
    /// The format is seven rows of shade characters, optionally preceded by
    /// `# key: value` header lines. Three rules about what a line is, and they
    /// exist because the alternative is a file that parses into a picture
    /// nobody drew:
    ///
    /// 1. a line starting with `#` is a comment, and `# name:`, `# author:`
    ///    and `# description:` are read into [`Meta`];
    /// 2. a line of length zero is skipped, so a file may breathe between its
    ///    header and its rows;
    /// 3. anything else is a shade row, and every character in it must be one
    ///    [`SHADE_CHARS`] knows.
    ///
    /// Rule 2 is deliberately about *length zero* rather than about
    /// whitespace. A row of spaces is a row of level-0 days, which is a
    /// perfectly ordinary thing for a picture to contain — trimming it away
    /// would silently turn a seven-row file into a six-row one, and the error
    /// would name the wrong problem.
    ///
    /// A short row is padded with level 0 on the right, because an editor that
    /// strips trailing whitespace will do exactly that to a picture whose last
    /// column is dark, and a format that cannot survive being saved is not a
    /// format contributors can use.
    pub fn parse(text: &str) -> Result<Self, String> {
        let mut meta = Meta::default();
        let mut rows: Vec<Vec<u8>> = Vec::new();

        for (number, line) in text.lines().enumerate() {
            let line = line.strip_suffix('\r').unwrap_or(line);
            if let Some(comment) = line.strip_prefix('#') {
                read_meta(comment, &mut meta);
                continue;
            }
            if line.is_empty() {
                continue;
            }
            if rows.len() == CANVAS_ROWS {
                return Err(format!(
                    "line {}: {} rows already, and a canvas is exactly {}",
                    number + 1,
                    CANVAS_ROWS,
                    CANVAS_ROWS
                ));
            }
            let mut row = Vec::with_capacity(line.chars().count());
            for (column, character) in line.chars().enumerate() {
                let Some(level) = shade_of(character) else {
                    return Err(format!(
                        "line {}, column {}: {character:?} is not a shade — use {}",
                        number + 1,
                        column + 1,
                        describe_shades()
                    ));
                };
                row.push(level);
            }
            rows.push(row);
        }

        if rows.len() != CANVAS_ROWS {
            return Err(format!(
                "a canvas is exactly {CANVAS_ROWS} rows, one per weekday; this has {}",
                rows.len()
            ));
        }
        let width = rows.iter().map(Vec::len).max().unwrap_or(0);
        if !(1..=CANVAS_COLS).contains(&width) {
            return Err(format!(
                "a canvas is 1 to {CANVAS_COLS} columns wide; this is {width}"
            ));
        }

        let mut columns = vec![[0u8; CANVAS_ROWS]; width];
        for (row, levels) in rows.iter().enumerate() {
            for (column, level) in levels.iter().enumerate() {
                columns[column][row] = *level;
            }
        }
        Ok(Self { columns, meta })
    }

    /// Columns across.
    #[must_use]
    pub fn width(&self) -> usize {
        self.columns.len()
    }

    /// What the file said about itself.
    #[must_use]
    pub fn meta(&self) -> &Meta {
        &self.meta
    }

    /// Replace what the file says about itself.
    pub fn set_meta(&mut self, meta: Meta) {
        self.meta = meta;
    }

    /// The level at a position, or 0 for one off the canvas.
    ///
    /// Answering rather than panicking because a cursor walks this: an editor
    /// asking about the cell past the edge wants "nothing there", not a crash.
    #[must_use]
    pub fn at(&self, week: usize, row: usize) -> u8 {
        self.columns
            .get(week)
            .and_then(|column| column.get(row).copied())
            .unwrap_or(0)
    }

    /// Set the level at a position. Off-canvas positions and levels above 4 are
    /// ignored, for the same reason [`Canvas::at`] answers rather than panics.
    pub fn set(&mut self, week: usize, row: usize, level: u8) {
        if level > 4 {
            return;
        }
        if let Some(cell) = self
            .columns
            .get_mut(week)
            .and_then(|column| column.get_mut(row))
        {
            *cell = level;
        }
    }

    /// Every level in the canvas, in column order.
    pub fn levels(&self) -> impl Iterator<Item = u8> + '_ {
        self.columns
            .iter()
            .flat_map(|column| column.iter().copied())
    }

    /// How many *cells* sit at each level, indexed by level.
    ///
    /// This counts the canvas, which is 7 x width — not the year. Use it for
    /// questions about the drawing itself; for anything a user budgets
    /// against, ask [`levels_histogram`] about the days the calendar
    /// actually has.
    #[must_use]
    pub fn histogram(&self) -> [usize; 5] {
        let mut counts = [0usize; 5];
        for level in self.levels() {
            counts[usize::from(level).min(4)] += 1;
        }
        counts
    }

    /// The darkest and brightest levels the picture actually uses.
    ///
    /// `None` for a canvas that is entirely one shade, which has no contrast to
    /// describe and nothing to check.
    #[must_use]
    pub fn range(&self) -> Option<(u8, u8)> {
        let low = self.levels().min()?;
        let high = self.levels().max()?;
        (low != high).then_some((low, high))
    }

    /// Every level the picture uses, darkest first.
    #[must_use]
    pub fn palette(&self) -> Vec<u8> {
        Self::palette_of(&self.histogram())
    }

    /// The same, from a histogram somebody else counted.
    #[must_use]
    pub fn palette_of(histogram: &[usize; 5]) -> Vec<u8> {
        (0..=4u8)
            .filter(|level| histogram[usize::from(*level)] > 0)
            .collect()
    }

    /// The two shades in the picture that look most alike, and how far apart
    /// they are in the worst palette a reader might have.
    ///
    /// **Not [`Canvas::range`].** The darkest and brightest shades in a drawing
    /// are the two furthest apart, so measuring those answers "can anything
    /// here be told from anything else" — which is the flattering question. A
    /// picture drawn in levels 0, 3 and 4 spans ΔE 70 and still has two shades
    /// a reader cannot separate, because 3 and 4 are ΔE 9.1 apart and they are
    /// the ones sitting next to each other.
    ///
    /// This asks the useful question instead: of every pair of shades the
    /// picture actually uses, which two look most alike? That is the pair that
    /// decides whether the drawing reads.
    ///
    /// `None` for a canvas of one shade, which has no pair to compare.
    #[must_use]
    pub fn closest_pair(&self) -> Option<(u8, u8, Legibility, f32)> {
        Self::closest_pair_of(&self.histogram())
    }

    /// The same, over the shades a given histogram holds.
    ///
    /// Taking the histogram rather than the canvas is what lets the preview
    /// ask about the shades that land *inside the year*: a picture whose only
    /// ink falls in the partial weeks at either end drew nothing, and used to
    /// report `shades 0 4 · closest pair 0 and 4 · ΔE 70, clear` — the one
    /// check this project tells you to read twice, passing on a drawing that
    /// does not exist.
    #[must_use]
    pub fn closest_pair_of(histogram: &[usize; 5]) -> Option<(u8, u8, Legibility, f32)> {
        let used = Self::palette_of(histogram);
        let mut worst: Option<(u8, u8, f32)> = None;
        for (index, low) in used.iter().enumerate() {
            for high in used.iter().skip(index + 1) {
                let delta = Shades {
                    ink: *high,
                    field: *low,
                }
                .worst()
                .1;
                if worst.is_none_or(|(_, _, seen)| delta < seen) {
                    worst = Some((*low, *high, delta));
                }
            }
        }
        worst.map(|(low, high, delta)| (low, high, Legibility::of(delta), delta))
    }

    /// The busiest day this canvas needs the year to have before its shades can
    /// be told apart.
    ///
    /// (see [`levels_histogram`] for the calendar-side counterpart)
    ///
    /// GitHub's scale has four steps, so a year whose busiest day is 1 holds
    /// exactly two shades: empty and full. A picture using any level between
    /// needs a peak of at least 4, where the counts 1, 2, 3, 4 land on levels
    /// 1, 2, 3, 4 exactly. The same rule [`Shades::min_peak`] applies to two
    /// shades, stated for however many a picture uses.
    #[must_use]
    pub fn min_peak(&self) -> u32 {
        if self.levels().any(|level| (1..4).contains(&level)) {
            4
        } else {
            1
        }
    }

    /// Turn the canvas back into the `.art` format, header included.
    ///
    /// Digits rather than blocks, and every row padded to the full width: this
    /// is what an editor writes, and a file that round-trips through
    /// [`Canvas::parse`] unchanged is one a contributor can diff.
    #[must_use]
    pub fn to_art(&self) -> String {
        let mut out = String::new();
        for (key, value) in [
            ("name", self.meta.name.as_deref()),
            ("author", self.meta.author.as_deref()),
            ("description", self.meta.description.as_deref()),
        ] {
            if let Some(value) = value {
                out.push_str(&format!("# {key}: {value}\n"));
            }
        }
        if !out.is_empty() {
            out.push('\n');
        }
        for row in 0..CANVAS_ROWS {
            for week in 0..self.width() {
                out.push(SHADE_CHARS[usize::from(self.at(week, row)).min(4)].0);
            }
            out.push('\n');
        }
        out
    }

    /// Lay the canvas on a year and report the shade each day should end at.
    ///
    /// `start` is the calendar column the canvas's first column lands on.
    /// The returned total counts the cells that fell outside the year and
    /// **would have been drawn** — the first and last calendar columns are
    /// partial weeks, so a full-width picture overhangs them.
    ///
    /// Blank cells are not counted, because losing one costs the picture
    /// nothing. Counting them meant a 53-column template warned about six
    /// dropped cells on every year, all six of them empty margin: a `note:`
    /// on the path everybody takes, which teaches people to stop reading
    /// notes. What is worth interrupting for is a *shade* that will not fit.
    ///
    /// Returns the level for **every** day it covers, including the level-0
    /// ones. That is the difference between a canvas and text: a dark day
    /// inside a picture is part of the picture, and the plan has to know it
    /// must stay dark.
    #[must_use]
    pub fn place(&self, grid: &Grid, start: usize) -> (BTreeMap<NaiveDate, u8>, usize) {
        let mut levels = BTreeMap::new();
        let mut skipped = 0;
        for (offset, column) in self.columns.iter().enumerate() {
            let week = match start.checked_add(offset) {
                Some(week) if week < grid.weeks => week,
                // Past the end of the year: nothing in this column lands.
                _ => {
                    skipped += column.iter().filter(|level| **level > 0).count();
                    continue;
                }
            };
            for (row, level) in column.iter().enumerate() {
                let date = grid.date_at(week, row);
                if grid.holds(date) {
                    levels.insert(date, *level);
                } else if *level > 0 {
                    skipped += 1;
                }
            }
        }
        (levels, skipped)
    }

    /// Where the canvas sits when nobody says: centred on the year.
    #[must_use]
    pub fn centred(&self, grid: &Grid) -> usize {
        grid.weeks.saturating_sub(self.width()) / 2
    }
}

/// The most a header field may carry.
///
/// A `# name:` is a title in a listing and the first word of a report line, so
/// a few dozen characters is generous. Unbounded, a 200,000-character name
/// produced a 200,061-byte first output line — and rode through `--save` into
/// the plan and out of the Action's `headline` output.
const MAX_META: usize = 200;

/// How many days sit at each level, over the days the calendar actually has.
///
/// The canvas-side [`Canvas::histogram`] counts cells — 7 x width, which for
/// a full-width picture is 371 against a year of 365 or 366. The preview
/// table and the editor panel used it, so they disagreed with the header
/// above them and with what `--write` makes: a picture with ink in the
/// partial weeks at either end priced out 322 days and 742 commits while the
/// header said 317 and 722, and `--write` made 722. The note directly above
/// the table had just said cells were dropped, and the table counted them
/// anyway.
///
/// The tracking renderer always did it this way, which is why the shipped
/// docs disagree with themselves: `docs/ART.md` prints one figure for the
/// preview and another for the tracking table of the same plan, exactly the
/// out-of-year cells apart.
#[must_use]
pub fn levels_histogram(levels: &std::collections::BTreeMap<chrono::NaiveDate, u8>) -> [usize; 5] {
    let mut counts = [0usize; 5];
    for level in levels.values() {
        counts[usize::from(*level).min(4)] += 1;
    }
    counts
}

/// Read one `# key: value` header line into `meta`.
///
/// Unknown keys are ignored rather than refused. A `.art` file is a document as
/// well as data — a contributor may want a `# note:` line — and a format that
/// rejects a comment it does not recognise is one that breaks when it grows.
///
/// **The value is cleaned here**, which is the rule `crate::printable` states:
/// untrusted text is cleaned where it enters rather than at each of the places
/// that print it. A `.art` file is exactly the thing this project asks
/// strangers to send — issue #57 invites it, and CONTRIBUTING §11 makes the
/// review path "open the file with `mossaic-art`" — so a control character in
/// a header reached the reviewer's terminal, the saved plan, the JSON and
/// markdown reports and the Action's `headline` output, unfiltered, on a
/// binary that had already fixed this same bug on the calendar path.
/// `--no-colour` suppressed none of it, because the point of an escape
/// sequence is that it is not displayed.
///
/// Cleaning here covers every downstream printer at once: the report header,
/// `--list-templates`, both report formats, the saved plan's `art` string and
/// the editor's title.
fn read_meta(comment: &str, meta: &mut Meta) {
    let Some((key, value)) = comment.split_once(':') else {
        return;
    };
    // `printable` first, then trim: an escape sequence around whitespace
    // would otherwise leave the whitespace behind.
    let value: String = crate::printable(value.trim())
        .trim()
        .chars()
        .take(MAX_META)
        .collect();
    if value.is_empty() {
        return;
    }
    match key.trim().to_ascii_lowercase().as_str() {
        "name" => meta.name = Some(value),
        "author" => meta.author = Some(value),
        "description" => meta.description = Some(value),
        _ => {}
    }
}

/// The shade alphabet, for a parse error that has to teach the format.
fn describe_shades() -> String {
    let digits: String = SHADE_CHARS.iter().map(|(digit, _)| *digit).collect();
    let blocks: String = SHADE_CHARS.iter().map(|(_, block)| *block).collect();
    format!("{digits} or {blocks:?} (space is level 0)")
}

/// What a day at `level` must reach, and the most it may hold before it becomes
/// the next shade up.
///
/// The general form of the band [`Shades`] describes for two shades. Level 0
/// must stay dark, so its ceiling is zero; level 4 has no ceiling, because
/// brighter than brightest is still brightest.
#[must_use]
pub fn band(level: u8, peak: u32) -> (u32, Option<u32>) {
    match level.min(4) {
        0 => (0, Some(0)),
        4 => (commits_to_reach(4, peak), None),
        level => (
            commits_to_reach(level, peak),
            commits_to_reach(level + 1, peak).checked_sub(1),
        ),
    }
}

/// The two shades contribution art is drawn in.
///
/// The classic look is `ink: 4, field: 0` — letters against an empty graph. It
/// reads perfectly and it costs you every other day of the year: to keep the
/// background dark you have to *stop contributing* on roughly three hundred
/// days, which is a strange thing for a tool about contributing to ask.
///
/// Raising `field` above zero draws the background as a colour rather than as
/// nothing. The letters are then the difference between two greens instead of
/// the difference between green and empty, and a daily contributor can draw art
/// without going dark for most of the year.
///
/// The catch is that the difference has to be visible, and GitHub's five shades
/// are not evenly spaced. Adjacent levels come as close as ΔE 9.1; levels two
/// or more apart never fall below ΔE 35.4. [`Shades::worst`] measures it across
/// every palette a reader might be looking at.
///
/// ```
/// # use mossaic::art::Shades;
/// # use mossaic::primer::Legibility;
/// // Level 1 under level 4: clear in every palette GitHub ships.
/// assert_eq!(Shades { ink: 4, field: 1 }.worst().0, Legibility::Clear);
/// // One level apart is a gamble that depends on the reader's theme.
/// assert_eq!(Shades { ink: 4, field: 3 }.worst().0, Legibility::Faint);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Shades {
    /// The level a letter day must reach.
    pub ink: u8,
    /// The level every other day should sit at. Zero leaves the background
    /// empty, which is the classic look.
    pub field: u8,
}

impl Default for Shades {
    /// The brightest letters on an empty background.
    fn default() -> Self {
        Self { ink: 4, field: 0 }
    }
}

impl Shades {
    /// Every palette a reader might have the graph open in: three appearances
    /// times three seasons, and GitHub picks the season by date, not by choice.
    const READERS: [(Appearance, Season); 9] = [
        (Appearance::Light, Season::Default),
        (Appearance::Light, Season::Winter),
        (Appearance::Light, Season::Halloween),
        (Appearance::Dark, Season::Default),
        (Appearance::Dark, Season::Winter),
        (Appearance::Dark, Season::Halloween),
        (Appearance::Dimmed, Season::Default),
        (Appearance::Dimmed, Season::Winter),
        (Appearance::Dimmed, Season::Halloween),
    ];

    /// Whether these two shades can draw anything at all.
    ///
    /// This is the one rule that cannot be relaxed: a background at or above
    /// the letters does not make faint art, it makes a blank graph.
    pub fn check(self) -> Result<(), String> {
        if self.ink > 4 || self.field > 4 {
            return Err(format!(
                "shades run 0 to 4; got ink {} and field {}",
                self.ink, self.field
            ));
        }
        if self.ink == 0 {
            return Err("letters cannot be drawn at level 0 — that is an empty day".to_string());
        }
        if self.field >= self.ink {
            return Err(format!(
                "the background (level {}) must be darker than the letters (level {}), \
                 or there is nothing to see",
                self.field, self.ink
            ));
        }
        Ok(())
    }

    /// How far apart the two shades look in one palette, as CIE76 ΔE.
    pub fn separation(self, palette: &Palette) -> f32 {
        palette.separation(self.field, self.ink)
    }

    /// The worst these shades look in any palette a reader might have, and the
    /// separation that earned it.
    ///
    /// Art is drawn once and read by everyone: someone on the light theme,
    /// someone on dark, and — for a few weeks each year — everyone at once on
    /// GitHub's seasonal palette. The honest number is the worst of them.
    pub fn worst(self) -> (Legibility, f32) {
        let worst = Self::READERS
            .iter()
            .map(|(appearance, season)| self.separation(&Palette::new(*appearance, *season, true)))
            .fold(f32::INFINITY, f32::min);
        (Legibility::of(worst), worst)
    }

    /// The smallest busiest-day these shades can be told apart in.
    ///
    /// GitHub's scale has four steps, so a year whose busiest day is 1 holds
    /// exactly two shades: empty and full. Asking for a level-1 background in
    /// one is asking for a colour the scale cannot express — both shades round
    /// to the same commit count and the letters vanish. At a peak of 4 the
    /// counts 1, 2, 3, 4 land on levels 1, 2, 3, 4 exactly, which is as small
    /// as a five-shade year gets.
    pub fn min_peak(self) -> u32 {
        if self.field > 0 {
            4
        } else {
            1
        }
    }

    /// The commits a day of each kind needs, in a year whose busiest day ends
    /// at `peak`.
    pub fn commits(self, peak: u32) -> Ink {
        Ink {
            lit: commits_to_reach(self.ink, peak),
            field: match self.field {
                0 => 0,
                level => commits_to_reach(level, peak),
            },
        }
    }

    /// The most a background day may hold before it stops being background.
    ///
    /// Zero-field art has a ceiling of zero: the day must stay dark. Otherwise
    /// it is one below the count that would reach the next shade up, and that is
    /// always a number — [`commits_to_reach`] never returns less than 1, so the
    /// `Option` here is a shape the caller wanted rather than a case that
    /// happens. [`crate::plan::Day::ceiling`] is the one that is genuinely
    /// `None`, for a day that cannot be too bright at all.
    pub fn ceiling(self, peak: u32) -> Option<u32> {
        if self.field == 0 {
            return Some(0);
        }
        // Saturating, because `Shades` is public and need not have been checked:
        // a field of 255 would otherwise overflow the level rather than clamp.
        commits_to_reach(self.field.saturating_add(1), peak).checked_sub(1)
    }
}

/// How many commits each kind of day gets.
///
/// Separate from [`Shades`] because a shade is what a reader sees and a commit
/// count is what you have to do — the map between them depends on the year's
/// busiest day, which changes as the art is drawn.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Ink {
    /// Commits on a day that is part of a letter.
    pub lit: u32,
    /// Commits on every other day. Zero leaves the background empty.
    pub field: u32,
}

/// Where the text landed, and what it cost.
#[derive(Debug, Clone, Default)]
pub struct Placed {
    /// Commits per lit day, in date order.
    pub lit: BTreeMap<NaiveDate, u32>,
    /// Commits per background day, in date order. Empty unless a field shade
    /// was asked for.
    pub field: BTreeMap<NaiveDate, u32>,
    /// Pixels that fell outside the year — the first and last calendar columns
    /// are partial weeks, so text that fills the year loses its edges.
    pub skipped: usize,
    /// The column the text starts at, centred unless one was given.
    pub start_week: usize,
}

impl Placed {
    /// Every day the art writes to, letters and background together.
    pub fn all(&self) -> BTreeMap<NaiveDate, u32> {
        let mut all = self.field.clone();
        all.extend(self.lit.iter().map(|(date, count)| (*date, *count)));
        all
    }

    /// Every commit the art would make.
    pub fn total(&self) -> u32 {
        self.all()
            .values()
            .fold(0u32, |sum, count| sum.saturating_add(*count))
    }
}

/// Map lit pixels onto dates. `top` is the first calendar row used, 0 = Sunday.
///
/// When `ink.field` is non-zero every other day of the year is filled too, so
/// the art is a contrast between two shades rather than between something and
/// nothing. Those days land in [`Placed::field`], kept apart from the letters
/// because they are priced, tracked and reported differently.
pub fn place(
    columns: &[[bool; GLYPH_ROWS]],
    grid: &Grid,
    top: usize,
    start: Option<usize>,
    ink: Ink,
) -> Result<Placed, String> {
    // Subtraction, so the guard cannot be wrapped past: `usize::MAX + GLYPH_ROWS`
    // comes out as 4, which is comfortably "inside" a seven-row week, and the
    // rows were then drawn wherever the wrapping took them.
    if top > WEEKDAYS - GLYPH_ROWS {
        return Err(format!("--top {top} would push the text past row 6"));
    }
    if columns.len() > grid.weeks {
        return Err(format!(
            "{} columns needed but {} has only {}; use shorter text",
            columns.len(),
            grid.year,
            grid.weeks
        ));
    }
    // Centred by default, which is also what keeps a short text off the ragged
    // first and last columns.
    let start_week = start.unwrap_or((grid.weeks - columns.len()) / 2);
    // Refused rather than drawn. Past the last column that fits, every pixel
    // falls outside the year: the old answer was a note about dropped pixels
    // and a plan of nought days, and far enough out — `--start-week -1`, cast
    // to a usize — building the date panicked.
    // Subtraction rather than `start_week + columns.len() > grid.weeks`: the
    // check above has already ruled out the underflow, and the addition would
    // itself overflow for the very value that made this check necessary.
    if start_week > grid.weeks - columns.len() {
        return Err(format!(
            "--start-week {start_week} puts {} columns past the end of {}, \
             which has {}; the last one that fits is {}",
            columns.len(),
            grid.year,
            grid.weeks,
            grid.weeks - columns.len()
        ));
    }

    let mut lit = BTreeMap::new();
    let mut skipped = 0;
    for (offset, column) in columns.iter().enumerate() {
        for (row, on) in column.iter().enumerate() {
            if !on {
                continue;
            }
            let day = grid.date_at(start_week + offset, top + row);
            if grid.holds(day) {
                lit.insert(day, ink.lit);
            } else {
                skipped += 1;
            }
        }
    }

    // The background is every day of the year the letters did not claim. Built
    // after the letters so a lit day is never also a field day, whatever order
    // the glyphs were walked in.
    let mut field = BTreeMap::new();
    if ink.field > 0 {
        let mut date = grid.first;
        loop {
            if !lit.contains_key(&date) {
                field.insert(date, ink.field);
            }
            match date.succ_opt() {
                Some(next) if next <= grid.last => date = next,
                _ => break,
            }
        }
    }

    Ok(Placed {
        lit,
        field,
        skipped,
        start_week,
    })
}

/// GitHub's shade for a day, 0-4. Verified against a real calendar, 365 of 365
/// days matching.
pub fn level(count: u32, peak: u32) -> u8 {
    if count == 0 || peak == 0 {
        return 0;
    }
    // Widened, not saturated: a count comes from a calendar, and a calendar can
    // come from a file, so `count * 4` must not wrap — but saturating it would
    // be worse than wrong, because a day equal to the peak would then divide to
    // level 1 instead of 4.
    (u64::from(count) * 4).div_ceil(u64::from(peak)).min(4) as u8
}

/// The contributions a day needs to reach `level`, in a year whose busiest day
/// is `peak`.
///
/// GitHub's shade is `min(4, ceil(count * 4 / peak))`, so a day reaches `level`
/// exactly when `count * 4 > (level - 1) * peak`. That inverts to one line — no
/// searching, and it is the same arithmetic everywhere a price is quoted here.
///
/// ```
/// # use mossaic::art::commits_to_reach;
/// // A year whose busiest day is 112 sells its brightest shade for 85 a day.
/// assert_eq!(commits_to_reach(4, 112), 85);
/// assert_eq!(commits_to_reach(1, 112), 1);   // any contribution shows
/// ```
pub fn commits_to_reach(level: u8, peak: u32) -> u32 {
    let wanted = u64::from(level.saturating_sub(1)) * u64::from(peak) / 4 + 1;
    wanted.clamp(1, u64::from(u32::MAX)) as u32
}

/// The smallest uniform number of *extra* commits per lit day that puts the art
/// at `target`, given what those days already hold.
///
/// A day's shade comes from its total, and so does the year's peak — adding to
/// an already-busy day raises the bar for every other day, which is why this is
/// a fixed point rather than a formula. It converges in a handful of rounds:
/// each pass can only raise the peak by the spread between the busiest and
/// quietest lit day, and that spread does not grow.
pub fn commits_for_level(
    days: &[NaiveDate],
    existing: &BTreeMap<NaiveDate, u32>,
    target: u8,
) -> Option<u32> {
    if days.is_empty() {
        return None;
    }
    let held = |day: &NaiveDate| existing.get(day).copied().unwrap_or(0);
    let elsewhere = existing
        .iter()
        .filter(|(day, _)| !days.contains(day))
        .map(|(_, count)| *count)
        .max()
        .unwrap_or(0);
    let quietest = days.iter().map(held).min().unwrap_or(0);

    let mut added = 0;
    for _ in 0..64 {
        let peak = days
            .iter()
            // Saturating, like every other sum here: the counts come from a
            // calendar and a calendar can come from a file.
            .map(|day| held(day).saturating_add(added))
            .chain([elsewhere])
            .max()
            .unwrap_or(added)
            .max(1);
        // The quietest lit day is the binding one: every other ends up brighter.
        let wanted = commits_to_reach(target, peak).saturating_sub(quietest);
        if wanted <= added {
            return Some(added.max(1));
        }
        added = wanted;
    }
    None
}

/// A GraphQL-shaped response, so `mossaic --file` can render this for real.
pub fn snapshot(counts: &BTreeMap<NaiveDate, u32>, grid: &Grid, login: &str) -> String {
    const NAMES: [&str; 5] = [
        "NONE",
        "FIRST_QUARTILE",
        "SECOND_QUARTILE",
        "THIRD_QUARTILE",
        "FOURTH_QUARTILE",
    ];
    let peak = counts.values().copied().max().unwrap_or(1);
    let mut weeks = Vec::with_capacity(grid.weeks);
    for week in 0..grid.weeks {
        let days: Vec<serde_json::Value> = (0..WEEKDAYS)
            .map(|row| grid.date_at(week, row))
            .filter(|day| grid.holds(*day))
            .map(|day| {
                let count = counts.get(&day).copied().unwrap_or(0);
                serde_json::json!({
                    "date": day.to_string(),
                    "contributionCount": count,
                    "contributionLevel": NAMES[level(count, peak) as usize],
                })
            })
            .collect();
        if !days.is_empty() {
            weeks.push(serde_json::json!({ "contributionDays": days }));
        }
    }

    let total = counts
        .values()
        .fold(0u32, |sum, count| sum.saturating_add(*count));
    let payload = serde_json::json!({
        "data": { "user": {
            "login": login,
            "contributionsCollection": {
                "contributionYears": [grid.year],
                "contributionCalendar": { "totalContributions": total, "weeks": weeks },
            },
        }},
        "errors": serde_json::Value::Null,
    });
    serde_json::to_string_pretty(&payload).expect("a tree of numbers and strings")
}

/// The shade each day of the art would end at, which is what a reader sees.
///
/// Lit days take the ink shade, everything the background covers takes the
/// field shade, and any day neither claims stays at 0.
pub fn shading(placed: &Placed, shades: Shades) -> BTreeMap<NaiveDate, u8> {
    let mut out: BTreeMap<NaiveDate, u8> = placed
        .field
        .keys()
        .map(|date| (*date, shades.field))
        .collect();
    out.extend(placed.lit.keys().map(|date| (*date, shades.ink)));
    out
}

/// The whole year as the chart would draw it, so the text can be checked before
/// a single commit is made.
///
/// Takes shades rather than commit counts because that is what is being
/// checked: whether the letters stand out from the background they sit on.
pub fn preview(levels: &BTreeMap<NaiveDate, u8>, grid: &Grid, palette: Option<&Palette>) -> String {
    const NAMES: [&str; WEEKDAYS] = ["", "Mon", "", "Wed", "", "Fri", ""];
    // Without colour the five shades still have to be told apart, so the ramp
    // carries the level rather than just "on" or "off" — which is the whole
    // point once the background is a shade instead of nothing.
    const RAMP: [&str; 5] = ["  ", "░░", "▒▒", "▓▓", "██"];
    let paint = |level: u8| {
        let level = usize::from(level).min(4);
        match palette {
            Some(palette) => {
                let colour = palette.levels[level];
                format!("\x1b[38;2;{};{};{}m██\x1b[0m", colour.0, colour.1, colour.2)
            }
            None => RAMP[level].to_string(),
        }
    };

    let mut label = " ".repeat(4);
    let mut seen = Vec::new();
    for week in 0..grid.weeks {
        let Some(first) = (0..WEEKDAYS)
            .map(|row| grid.date_at(week, row))
            .find(|day| grid.holds(*day))
        else {
            continue;
        };
        if seen.contains(&first.month()) {
            continue;
        }
        seen.push(first.month());
        let column = 4 + week * 2;
        if column >= label.chars().count() {
            label.push_str(&" ".repeat(column - label.chars().count()));
            label.push_str(&first.format("%b").to_string());
        }
    }

    let mut out = vec![label];
    for (row, name) in NAMES.iter().enumerate() {
        let mut line = format!("{name:<4}");
        for week in 0..grid.weeks {
            let day = grid.date_at(week, row);
            if !grid.holds(day) {
                line.push_str("  ");
            } else {
                line.push_str(&paint(levels.get(&day).copied().unwrap_or(0)));
            }
        }
        out.push(line);
    }
    out.join("\n")
}

/// Whoever git is configured as. The email must be one GitHub knows, or the
/// commits will exist but never reach the contribution graph.
pub fn identity() -> (String, String) {
    let config = |key: &str| {
        Command::new("git")
            .args(["config", "--get", key])
            .output()
            .ok()
            .filter(|out| out.status.success())
            .map(|out| String::from_utf8_lossy(&out.stdout).trim().to_string())
            .filter(|value| !value.is_empty())
    };
    (
        config("user.name").unwrap_or_else(|| "art".to_string()),
        config("user.email").unwrap_or_else(|| "art@example.invalid".to_string()),
    )
}

/// Create the commits locally with `git fast-import`. Never pushes.
///
/// fast-import because the counts get large: shading is relative to the year's
/// peak, so standing out in an active year can need thousands of commits, and a
/// `git commit` process each would take minutes.
pub fn write_commits(
    lit: &BTreeMap<NaiveDate, u32>,
    repo: &Path,
    label: &str,
    name: &str,
    email: &str,
) -> Result<usize, String> {
    // An identity is written into the fast-import stream as a line of its own,
    // so a newline in it would be a command. git refuses the malformed result
    // today; refusing it here makes that a clear error rather than a crash
    // report, and does not depend on git continuing to notice.
    for (what, value) in [("name", name), ("email", email)] {
        if value.chars().any(|c| c.is_control()) || value.contains(['<', '>']) {
            return Err(format!(
                "the commit {what} may not contain control characters, '<' or '>': {value:?}"
            ));
        }
    }

    if !repo.join(".git").is_dir() {
        std::fs::create_dir_all(repo).map_err(|e| format!("could not create {repo:?}: {e}"))?;
        run(repo, &["init", "-q", "-b", "main"])?;
    }

    let mut child = Command::new("git")
        .args(["fast-import", "--quiet"])
        .current_dir(repo)
        .stdin(Stdio::piped())
        .spawn()
        .map_err(|e| format!("could not run git fast-import: {e}"))?;

    // Streamed into git rather than built up first. The whole point of
    // fast-import here is that the counts get large, and a stream held in a
    // `String` costs about 275 bytes a commit — a scale where the buffer is the
    // limit rather than the work. Buffered through a `BufWriter` so this is
    // still one write syscall per few thousand commits, not one per line.
    //
    // No deadlock to worry about: `--quiet` says almost nothing, and its stdout
    // and stderr are inherited rather than piped, so nothing of ours has to be
    // drained while we write.
    let mut stdin = std::io::BufWriter::new(child.stdin.take().expect("piped"));
    let feed = |error: std::io::Error| format!("could not feed git fast-import: {error}");
    let mut index = 0usize;
    for (day, count) in lit {
        let stamp = day
            .and_hms_opt(12, 0, 0)
            .expect("noon exists")
            .and_utc()
            .timestamp();
        for _ in 0..*count {
            index += 1;
            let message = format!("{label} {day} #{index}\n");
            let body = format!("{index}\n");
            write!(
                stdin,
                "commit refs/heads/main\nmark :{index}\n\
                 author {name} <{email}> {stamp} +0000\n\
                 committer {name} <{email}> {stamp} +0000\n\
                 data {}\n{message}",
                message.len()
            )
            .map_err(feed)?;
            if index > 1 {
                writeln!(stdin, "from :{}", index - 1).map_err(feed)?;
            }
            write!(
                stdin,
                "M 100644 inline count.txt\ndata {}\n{body}\n",
                body.len()
            )
            .map_err(feed)?;
        }
    }
    // Flushed and closed before waiting, or fast-import never sees end of input.
    stdin.flush().map_err(feed)?;
    drop(stdin);

    let status = child
        .wait()
        .map_err(|e| format!("git fast-import failed: {e}"))?;
    if !status.success() {
        return Err(format!("git fast-import exited with {status}"));
    }
    run(repo, &["reset", "--hard", "main"])?;
    Ok(index)
}

fn run(repo: &Path, args: &[&str]) -> Result<(), String> {
    let out = Command::new("git")
        .args(args)
        .current_dir(repo)
        .output()
        .map_err(|e| format!("could not run git {}: {e}", args[0]))?;
    if out.status.success() {
        return Ok(());
    }
    Err(format!(
        "git {} failed: {}",
        args[0],
        String::from_utf8_lossy(&out.stderr).trim()
    ))
}