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

import (
	"database/sql"
	"encoding/json"
	"flag"
	"fmt"
	"io"
	"log"
	"math/rand"
	"net/http"
	"os"
	"path/filepath"
	"sort"
	"strconv"
	"strings"
	"time"

	_ "modernc.org/sqlite"
)

// ============================================================================
// Schema + migrations
// ============================================================================

// Each migration is applied exactly once, in order, tracked by schema_version.
// Never modify an existing migration — add a new one instead.

const migration001 = `
CREATE TABLE schema_version (
  version     INTEGER PRIMARY KEY,
  applied_at  INTEGER NOT NULL
);

-- One row per answered note. Source of truth for the picker.
-- Difficulty is aggregated per *written note* (clef + spelling), i.e. the thing
-- as it appears on paper, not per piano key.
--   midi:        pitch of the shown note (used only to grade the key press)
--   clef:        "treble" | "bass" (part of the written-note identity)
--   spelling:    shown VexFlow spelling, e.g. "F#/4" (part of the identity)
--   answer_midi: pitch the user pressed (NULL if skipped)
--   correct:     1 if answer_midi pitch == midi
--   reply_ms:    time from render to first press
CREATE TABLE attempts (
  id           INTEGER PRIMARY KEY AUTOINCREMENT,
  created_at   INTEGER NOT NULL,
  clef         TEXT    NOT NULL,
  midi         INTEGER NOT NULL,
  spelling     TEXT    NOT NULL,
  answer_midi  INTEGER,
  correct      INTEGER NOT NULL,
  reply_ms     INTEGER NOT NULL
);
CREATE INDEX idx_attempts_midi ON attempts(midi);
`

// migration002 indexes attempts by the written-note identity (clef + spelling),
// which is how difficulty is now aggregated: per "thing on the paper" rather
// than per piano key. Enharmonic spellings (C#/4 vs Db/4) and the same glyph in
// different clefs are tracked as distinct items.
const migration002 = `
CREATE INDEX idx_attempts_clef_spelling ON attempts(clef, spelling);
`

func runMigrations(db *sql.DB) error {
	migrations := []struct {
		version int
		sql     string
	}{
		{1, migration001},
		{2, migration002},
	}

	// Ensure schema_version exists before we query it (first run).
	// We detect "already applied" by querying; if the table is missing the
	// query errors only for version 1, which we tolerate.
	for _, m := range migrations {
		var count int
		err := db.QueryRow(
			"SELECT COUNT(*) FROM schema_version WHERE version = ?", m.version,
		).Scan(&count)
		if err != nil && m.version != 1 {
			return fmt.Errorf("check migration %d: %w", m.version, err)
		}
		if err == nil && count > 0 {
			continue
		}

		tx, err := db.Begin()
		if err != nil {
			return fmt.Errorf("begin migration %d: %w", m.version, err)
		}
		if _, err := tx.Exec(m.sql); err != nil {
			tx.Rollback()
			return fmt.Errorf("exec migration %d: %w", m.version, err)
		}
		if _, err := tx.Exec(
			"INSERT INTO schema_version (version, applied_at) VALUES (?, ?)",
			m.version, time.Now().Unix(),
		); err != nil {
			tx.Rollback()
			return fmt.Errorf("record migration %d: %w", m.version, err)
		}
		if err := tx.Commit(); err != nil {
			return fmt.Errorf("commit migration %d: %w", m.version, err)
		}
		log.Printf("applied migration %d", m.version)
	}
	return nil
}

func initDB(path string) (*sql.DB, error) {
	if dir := filepath.Dir(path); dir != "" {
		if err := os.MkdirAll(dir, 0o755); err != nil {
			return nil, fmt.Errorf("create db dir: %w", err)
		}
	}
	// Pragmas travel in the DSN so they apply to every pooled connection:
	// busy_timeout (a writer waits for the lock instead of failing with
	// SQLITE_BUSY), and WAL so readers do not block the writer. A post-open
	// db.Exec("PRAGMA …") would only configure whichever single pooled
	// connection ran it, leaving the others at SQLite's defaults.
	db, err := sql.Open("sqlite",
		"file:"+path+"?_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)")
	if err != nil {
		return nil, fmt.Errorf("open db: %w", err)
	}
	if err := runMigrations(db); err != nil {
		db.Close()
		return nil, err
	}
	return db, nil
}

// ============================================================================
// Note model
// ============================================================================
//
// We identify each playable note by MIDI number. Middle C (C4) = MIDI 60.
// Pools:
//   bass clef:   C2 (36) .. C4 (60)
//   treble clef: G3 (55) .. C6 (84)
// The pool includes accidentals (every semitone). Each generated note carries
// the clef it should be drawn in plus a VexFlow spelling.

const (
	midiC2 = 36
	midiC4 = 60
	midiG3 = 55
	midiC6 = 84
)

// note is a single prompt to render.
type note struct {
	Clef       string `json:"clef"`       // "treble" | "bass"
	MIDI       int    `json:"midi"`       // tracked pitch
	Key        string `json:"key"`        // VexFlow key, e.g. "c/4" or "c##/4"
	Accidental string `json:"accidental"` // "", "#", "b", "##", "bb"
	Spelling   string `json:"spelling"`   // e.g. "C#/4" (display/analysis)
}

func upperFirst(s string) string {
	if s == "" {
		return s
	}
	return string(s[0]-32) + s[1:]
}

// letterSemitone is the semitone offset of each natural letter above C.
var letterSemitone = map[byte]int{
	'c': 0, 'd': 2, 'e': 4, 'f': 5, 'g': 7, 'a': 9, 'b': 11,
}

// accidentalSemitone is the semitone shift for each accidental.
var accidentalSemitone = map[string]int{
	"":   0,
	"#":  1,
	"b":  -1,
	"##": 2,
	"bb": -2,
}

// floorDiv divides a by b rounding toward negative infinity (unlike Go's /
// which truncates toward zero), so octave math is correct for negative inputs.
func floorDiv(a, b int) int {
	q := a / b
	if (a%b != 0) && ((a < 0) != (b < 0)) {
		q--
	}
	return q
}

// spell builds a written note for the given pitch (MIDI) using the chosen
// natural letter and accidental, computing the octave so that the written note
// sounds at exactly that MIDI. Returns ok=false if letter+accidental cannot
// spell the pitch (shouldn't happen for the curated tables below).
func spell(midi int, clef, letter, accidental string) (note, bool) {
	base, okL := letterSemitone[letter[0]]
	shift, okA := accidentalSemitone[accidental]
	if !okL || !okA {
		return note{}, false
	}
	// The pitch class produced by this letter+accidental.
	pc := ((base+shift)%12 + 12) % 12
	if pc != ((midi%12)+12)%12 {
		return note{}, false
	}
	// Choose the octave for the letter so the sounding pitch matches midi.
	// sounding MIDI of "<letter><accidental>/<oct>" = (oct+1)*12 + base + shift,
	// so oct = (midi - base - shift)/12 - 1, using floor division so negative
	// numerators (low cross-spellings) round correctly.
	num := midi - base - shift
	oct := floorDiv(num, 12) - 1
	if (oct+1)*12+base+shift != midi {
		return note{}, false
	}
	key := fmt.Sprintf("%s%s/%d", letter, accidental, oct)
	spelling := fmt.Sprintf("%s%s/%d", upperFirst(letter), accidental, oct)
	return note{
		Clef:       clef,
		MIDI:       midi,
		Key:        key,
		Accidental: accidental,
		Spelling:   spelling,
	}, true
}

// spellingDef is one way to write a pitch class: a natural letter + accidental.
type spellingDef struct {
	letter     string
	accidental string
	advanced   bool // true = only shown in advanced mode
}

// pitchSpellings lists, per MIDI pitch class (0=C .. 11=B), every spelling we
// support. The non-advanced entries are the "basic" set (7 naturals + the
// sharp/flat of each black key). Advanced entries add the white-key cross
// spellings (B#, Cb, E#, Fb) and the double accidentals (##, bb).
var pitchSpellings = [12][]spellingDef{
	0: { // C
		{"c", "", false},
		{"b", "#", true},  // B#
		{"d", "bb", true}, // Dbb
	},
	1: { // C# / Db
		{"c", "#", false},
		{"d", "b", false},
		{"b", "##", true}, // B##
	},
	2: { // D
		{"d", "", false},
		{"c", "##", true}, // C##
		{"e", "bb", true}, // Ebb
	},
	3: { // D# / Eb
		{"d", "#", false},
		{"e", "b", false},
		{"f", "bb", true}, // Fbb
	},
	4: { // E
		{"e", "", false},
		{"f", "b", true},  // Fb
		{"d", "##", true}, // D##
	},
	5: { // F
		{"f", "", false},
		{"e", "#", true},  // E#
		{"g", "bb", true}, // Gbb
	},
	6: { // F# / Gb
		{"f", "#", false},
		{"g", "b", false},
		{"e", "##", true}, // E##
	},
	7: { // G
		{"g", "", false},
		{"f", "##", true}, // F##
		{"a", "bb", true}, // Abb
	},
	8: { // G# / Ab
		{"g", "#", false},
		{"a", "b", false},
	},
	9: { // A
		{"a", "", false},
		{"g", "##", true}, // G##
		{"b", "bb", true}, // Bbb
	},
	10: { // A# / Bb
		{"a", "#", false},
		{"b", "b", false},
		{"c", "bb", true}, // Cbb
	},
	11: { // B
		{"b", "", false},
		{"c", "b", true},  // Cb
		{"a", "##", true}, // A##
	},
}

// writtenNote pairs a renderable note with whether it is an advanced-only
// spelling (enharmonic cross-spelling or double accidental).
type writtenNote struct {
	note     note
	advanced bool
}

// writtenNotesFor returns every distinct written note (thing on the paper) for
// a pitch in a clef, each tagged with whether it is advanced-only.
func writtenNotesFor(midi int, clef string) []writtenNote {
	pc := ((midi % 12) + 12) % 12
	var notes []writtenNote
	for _, sd := range pitchSpellings[pc] {
		n, ok := spell(midi, clef, sd.letter, sd.accidental)
		if !ok {
			continue
		}
		notes = append(notes, writtenNote{note: n, advanced: sd.advanced})
	}
	return notes
}

// poolEntry is a candidate prompt: a single written note (its full visual
// identity plus the pitch needed to grade the key press).
type poolEntry struct {
	note     note
	key      string // noteKey(clef, spelling): the stats aggregation key
	advanced bool   // true = only available in advanced (enharmonic) mode
}

func newPoolEntry(wn writtenNote) poolEntry {
	return poolEntry{
		note:     wn.note,
		key:      noteKey(wn.note.Clef, wn.note.Spelling),
		advanced: wn.advanced,
	}
}

// buildPool enumerates every written note we may show, including advanced
// enharmonic spellings (each tagged so the picker can include/exclude them by
// mode). Each spelling is tracked and weighted independently.
func buildPool() []poolEntry {
	var pool []poolEntry
	for m := midiC2; m <= midiC4; m++ {
		for _, wn := range writtenNotesFor(m, "bass") {
			pool = append(pool, newPoolEntry(wn))
		}
	}
	for m := midiG3; m <= midiC6; m++ {
		for _, wn := range writtenNotesFor(m, "treble") {
			pool = append(pool, newPoolEntry(wn))
		}
	}
	return pool
}

// keyboardRange is the union span shown on the on-screen piano (C2..C6).
const (
	keyboardLowMIDI  = midiC2
	keyboardHighMIDI = midiC6
)

// ============================================================================
// Picker: difficulty-weighted random selection
// ============================================================================
//
// weight(midi) combines:
//   - unseen bonus: notes never attempted get a high weight so they show up
//   - error penalty: lower recent success rate -> higher weight
//   - slowness penalty: higher average reply time -> higher weight
// We compute stats per MIDI pitch (correctness is pitch-based).

// A reply slower than distractionThresholdMS is assumed to be a distraction
// (looked away, got interrupted) rather than a genuinely hard note. Instead of
// letting it inflate the note's average reply time, we record it as a neutral,
// unremarkable value (neutralReplyMS) so it neither rewards nor penalizes.
const (
	distractionThresholdMS = 10000 // 10s
	neutralReplyMS         = 2000  // ~average reply, no difficulty influence
)

// sessionGapMS defines a practice session: a run of consecutive answers with no
// pause longer than this between them. A gap larger than this starts a new
// session. Used only for the live "Session" counter on the practice page.
const sessionGapMS = 5 * 60 * 1000 // 5 minutes

type keyStat struct {
	attempts int
	correct  int
	avgReply float64 // ms
}

// noteKey is the identity of a written note ("thing on the paper") used to
// aggregate difficulty statistics: clef + visual spelling (letter, accidental,
// octave). Enharmonic spellings (C#/4 vs Db/4) and the same glyph in different
// clefs (treble C/4 vs bass C/4) are therefore distinct items.
func noteKey(clef, spelling string) string {
	return clef + "|" + spelling
}

// loadStats returns aggregate stats per written note (keyed by noteKey),
// computed over all recorded attempts.
func loadStats(db *sql.DB) (map[string]keyStat, error) {
	rows, err := db.Query(`
		SELECT clef, spelling,
		       COUNT(*)            AS attempts,
		       SUM(correct)        AS correct,
		       AVG(reply_ms)       AS avg_reply
		FROM attempts
		WHERE answer_midi IS NOT NULL
		GROUP BY clef, spelling
	`)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	stats := map[string]keyStat{}
	for rows.Next() {
		var clef, spelling string
		var attempts, correct int
		var avg sql.NullFloat64
		if err := rows.Scan(&clef, &spelling, &attempts, &correct, &avg); err != nil {
			return nil, err
		}
		stats[noteKey(clef, spelling)] = keyStat{
			attempts: attempts, correct: correct, avgReply: avg.Float64,
		}
	}
	return stats, rows.Err()
}

// sessionStat is the live counter for the current practice session: a run of
// answers with no pause longer than sessionGapMS between them.
type sessionStat struct {
	Total   int `json:"total"`
	Correct int `json:"correct"`
}

// loadSessionStat computes the current session's correct/total from attempt
// timestamps. The session is the most recent contiguous run of attempts whose
// consecutive gaps are all <= sessionGapMS, ending at the latest attempt. If the
// most recent attempt is itself older than sessionGapMS, the session is just
// that run (it ends whenever the gap rule breaks). Returns {0,0} if no attempts.
func loadSessionStat(db *sql.DB) (sessionStat, error) {
	// Scan attempts newest-first; stop as soon as a gap exceeds the threshold.
	rows, err := db.Query(`
		SELECT created_at, correct
		FROM attempts
		WHERE answer_midi IS NOT NULL
		ORDER BY created_at DESC
	`)
	if err != nil {
		return sessionStat{}, err
	}
	defer rows.Close()

	var st sessionStat
	var prev int64
	first := true
	for rows.Next() {
		var createdAt int64
		var correct int
		if err := rows.Scan(&createdAt, &correct); err != nil {
			return sessionStat{}, err
		}
		if !first && prev-createdAt > sessionGapMS {
			break // gap too large: previous rows belong to an earlier session
		}
		st.Total++
		st.Correct += correct
		prev = createdAt
		first = false
	}
	return st, rows.Err()
}

// weightFor turns a stat into a positive selection weight.
func weightFor(s keyStat, ok bool) float64 {
	if !ok || s.attempts == 0 {
		return 10.0 // unseen: strongly favored
	}
	successRate := float64(s.correct) / float64(s.attempts)
	errPenalty := (1.0 - successRate) * 8.0 // up to +8 for always-wrong
	// reply time penalty: normalize around 2s, cap contribution.
	slow := s.avgReply / 2000.0
	if slow > 3 {
		slow = 3
	}
	slowPenalty := slow * 2.0 // up to +6 for very slow
	return 1.0 + errPenalty + slowPenalty
}

// pickNote chooses the next written note using weighted-random selection.
// Each candidate is a distinct written note (including its sharp/flat spelling),
// weighted by its own per-note difficulty. If clef is "treble" or "bass", only
// that clef's entries are considered; any other value (e.g. "") uses all.
// When advanced is false, advanced-only enharmonic spellings are excluded.
// exclude is the noteKey of the previously shown note; it is skipped so the
// same note is never shown twice in a row (unless it's the only candidate).
func pickNote(pool []poolEntry, stats map[string]keyStat, rng *rand.Rand, clef, exclude string, advanced bool) note {
	matchesMode := func(e poolEntry) bool {
		if (clef == "treble" || clef == "bass") && e.note.Clef != clef {
			return false
		}
		if e.advanced && !advanced {
			return false
		}
		return true
	}

	// Filter the pool by clef/mode and the excluded previous note.
	candidates := pool[:0:0]
	for _, e := range pool {
		if !matchesMode(e) || e.key == exclude {
			continue
		}
		candidates = append(candidates, e)
	}
	// If filtering left nothing (e.g. the excluded note was the only candidate),
	// fall back to the mode-matching pool ignoring the exclusion.
	if len(candidates) == 0 {
		for _, e := range pool {
			if matchesMode(e) {
				candidates = append(candidates, e)
			}
		}
	}
	if len(candidates) == 0 {
		candidates = pool
	}

	weights := make([]float64, len(candidates))
	var total float64
	for i, e := range candidates {
		s, ok := stats[e.key]
		w := weightFor(s, ok)
		weights[i] = w
		total += w
	}
	r := rng.Float64() * total
	for i, w := range weights {
		r -= w
		if r <= 0 {
			return candidates[i].note
		}
	}
	// Fallback (floating point edge): last entry.
	return candidates[len(candidates)-1].note
}

// ============================================================================
// HTTP server
// ============================================================================

type server struct {
	db   *sql.DB
	pool []poolEntry
	rng  *rand.Rand
}

func (s *server) handleNext(w http.ResponseWriter, r *http.Request) {
	stats, err := loadStats(s.db)
	if err != nil {
		log.Printf("loadStats: %v", err)
		http.Error(w, "db error", http.StatusInternalServerError)
		return
	}
	// prevClef/prevSpelling identify the note just shown, so we can avoid
	// repeating it. Empty when there is no previous note (first request).
	exclude := ""
	prevClef := r.URL.Query().Get("prevClef")
	prevSpelling := r.URL.Query().Get("prevSpelling")
	if prevClef != "" && prevSpelling != "" {
		exclude = noteKey(prevClef, prevSpelling)
	}
	advanced := r.URL.Query().Get("advanced") == "1"
	n := pickNote(s.pool, stats, s.rng, r.URL.Query().Get("clef"), exclude, advanced)
	writeJSON(w, n)
}

type answerReq struct {
	Clef       string `json:"clef"`
	MIDI       int    `json:"midi"`
	Spelling   string `json:"spelling"`
	AnswerMIDI *int   `json:"answer_midi"` // nil = skipped
	ReplyMS    int    `json:"reply_ms"`
}

type answerResp struct {
	Correct bool        `json:"correct"`
	MIDI    int         `json:"midi"`
	Session sessionStat `json:"session"`
}

func (s *server) handleAnswer(w http.ResponseWriter, r *http.Request) {
	var req answerReq
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		http.Error(w, "bad request", http.StatusBadRequest)
		return
	}

	// Correctness is by pitch: pressed key MIDI must equal shown MIDI.
	correct := false
	var answerMIDI sql.NullInt64
	if req.AnswerMIDI != nil {
		answerMIDI = sql.NullInt64{Int64: int64(*req.AnswerMIDI), Valid: true}
		correct = *req.AnswerMIDI == req.MIDI
	}

	correctInt := 0
	if correct {
		correctInt = 1
	}

	// Normalize reply time. A reply slower than the distraction threshold is
	// treated as a neutral, average reply (the user likely looked away) so it
	// doesn't penalize the note. Negative values (clock skew) floor to 0.
	replyMS := req.ReplyMS
	if replyMS < 0 {
		replyMS = 0
	}
	if replyMS > distractionThresholdMS {
		replyMS = neutralReplyMS
	}

	_, err := s.db.Exec(`
		INSERT INTO attempts
		  (created_at, clef, midi, spelling, answer_midi, correct, reply_ms)
		VALUES (?, ?, ?, ?, ?, ?, ?)
	`,
		time.Now().UnixMilli(), req.Clef, req.MIDI, req.Spelling,
		answerMIDI, correctInt, replyMS,
	)
	if err != nil {
		log.Printf("insert attempt: %v", err)
		http.Error(w, "db error", http.StatusInternalServerError)
		return
	}

	sess, err := loadSessionStat(s.db)
	if err != nil {
		log.Printf("loadSessionStat: %v", err)
		// Non-fatal: still return the answer result with a zero session.
	}
	writeJSON(w, answerResp{Correct: correct, MIDI: req.MIDI, Session: sess})
}

func (s *server) handleSession(w http.ResponseWriter, r *http.Request) {
	sess, err := loadSessionStat(s.db)
	if err != nil {
		log.Printf("handleSession: %v", err)
		http.Error(w, "db error", http.StatusInternalServerError)
		return
	}
	writeJSON(w, sess)
}

func (s *server) handleIndex(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/" {
		http.NotFound(w, r)
		return
	}
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	page := strings.NewReplacer(
		"__LOW_MIDI__", strconv.Itoa(keyboardLowMIDI),
		"__HIGH_MIDI__", strconv.Itoa(keyboardHighMIDI),
	).Replace(pageHTML)
	io.WriteString(w, page)
}

// handleMidi serves the WebMIDI setup page, where the user identifies their
// MIDI device + channel by playing C-E-G (any octave). The detected (port,
// channel) pair is stored client-side in localStorage and used by the practice
// page to accept note-on input alongside the on-screen piano. The page is fully
// static (all logic is client-side WebMIDI).
func (s *server) handleMidi(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	io.WriteString(w, midiPageHTML)
}

func writeJSON(w http.ResponseWriter, v any) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	if err := json.NewEncoder(w).Encode(v); err != nil {
		log.Printf("encode json: %v", err)
	}
}

// ============================================================================
// Stats page: selection probability per note
// ============================================================================

// statRow is one note's selection probability and underlying difficulty data.
type statRow struct {
	Label      string // e.g. "C#4"
	Clef       string // "treble" | "bass"
	MIDI       int    // pitch
	Key        string // VexFlow key, e.g. "c#/4" (for staff rendering)
	Accidental string // "", "#", "b", "##", "bb" (for staff rendering)
	Advanced   bool   // advanced-only enharmonic spelling
	Attempts   int    // recorded attempts
	Correct    int    // recorded correct answers
	AvgReply   float64 // average reply time (ms), 0 if unseen
	Weight     float64 // selection weight
	// Selection probability when playing in this clef's own mode, and in the
	// combined "Both" mode (where treble+bass compete in one pool). For the
	// requested mode (basic vs advanced): in basic mode advanced rows have 0.
	ProbInClef float64
	ProbBoth   float64
}

// computeStatRows builds the per-written-note probability table from recorded
// stats. Each pool entry is one written note (including sharp/flat spelling).
// Probabilities are normalized over the notes available in the given mode
// (advanced=false excludes enharmonic spellings), matching the live picker.
func computeStatRows(pool []poolEntry, stats map[string]keyStat, advanced bool) []statRow {
	inMode := func(e poolEntry) bool { return advanced || !e.advanced }

	// Total weight across the in-mode pool ("Both" mode) and per clef.
	var totalBoth float64
	totalClef := map[string]float64{}
	for _, e := range pool {
		if !inMode(e) {
			continue
		}
		s, ok := stats[e.key]
		w := weightFor(s, ok)
		totalBoth += w
		totalClef[e.note.Clef] += w
	}

	rows := make([]statRow, 0, len(pool))
	for _, e := range pool {
		s, ok := stats[e.key]
		w := weightFor(s, ok)
		// Spelling is like "C#/4", which noteLabel turns into "C#4".
		row := statRow{
			Label:      noteLabel(e.note.Spelling),
			Clef:       e.note.Clef,
			MIDI:       e.note.MIDI,
			Key:        e.note.Key,
			Accidental: e.note.Accidental,
			Advanced:   e.advanced,
			Attempts:   s.attempts,
			Correct:    s.correct,
			Weight:     w,
		}
		if ok {
			row.AvgReply = s.avgReply
		}
		// Probabilities only apply to notes available in the requested mode.
		if inMode(e) {
			if totalClef[e.note.Clef] > 0 {
				row.ProbInClef = w / totalClef[e.note.Clef]
			}
			if totalBoth > 0 {
				row.ProbBoth = w / totalBoth
			}
		}
		rows = append(rows, row)
	}
	return rows
}

// noteLabel turns a VexFlow spelling like "C#/4" into a compact label "C#4".
func noteLabel(spelling string) string {
	return strings.Replace(spelling, "/", "", 1)
}

func (s *server) handleStats(w http.ResponseWriter, r *http.Request) {
	stats, err := loadStats(s.db)
	if err != nil {
		log.Printf("handleStats loadStats: %v", err)
		http.Error(w, "db error", http.StatusInternalServerError)
		return
	}
	advanced := r.URL.Query().Get("advanced") == "1"
	allRows := computeStatRows(s.pool, stats, advanced)

	// In normal mode, hide advanced-only spellings (they aren't in play).
	rows := allRows[:0:0]
	for _, row := range allRows {
		if !advanced && row.Advanced {
			continue
		}
		rows = append(rows, row)
	}

	// Sort by ProbBoth descending (most-likely-next first), then by pitch and
	// label so the two spellings of a black key have a stable order.
	sort.Slice(rows, func(i, j int) bool {
		if rows[i].ProbBoth != rows[j].ProbBoth {
			return rows[i].ProbBoth > rows[j].ProbBoth
		}
		if rows[i].MIDI != rows[j].MIDI {
			return rows[i].MIDI < rows[j].MIDI
		}
		return rows[i].Label < rows[j].Label
	})

	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	var b strings.Builder
	b.WriteString(statsHeaderHTML)

	// Build the staff data: every in-mode note, in ascending pitch order per
	// clef, with its selection probability (ProbBoth). The frontend renders
	// these on a bass and a treble staff, tinting each note head by probability.
	staffNotes := emitStaffNotes(rows)
	if data, err := json.Marshal(staffNotes); err == nil {
		b.WriteString(`<script>window.__STAFF_NOTES__ = `)
		b.Write(data)
		b.WriteString(";</script>\n")
	}

	// Mode switch link.
	if advanced {
		b.WriteString(`<p><strong>Advanced</strong> spellings shown. ` +
			`<a class="navlink" href="/stats">Show normal only</a></p>` + "\n")
	} else {
		b.WriteString(`<p><strong>Normal</strong> spellings shown. ` +
			`<a class="navlink" href="/stats?advanced=1">Include advanced enharmonics</a></p>` + "\n")
	}

	b.WriteString(`<table>
<thead><tr>
  <th>Note</th><th>Clef</th><th>Attempts</th><th>Success</th>
  <th>Avg reply</th><th>Weight</th><th>P (this clef)</th><th>P (both)</th>
</tr></thead>
<tbody>
`)
	for _, row := range rows {
		successCell := "&mdash;"
		if row.Attempts > 0 {
			successCell = fmt.Sprintf("%d/%d (%.0f%%)",
				row.Correct, row.Attempts,
				100*float64(row.Correct)/float64(row.Attempts))
		}
		replyCell := "&mdash;"
		if row.Attempts > 0 {
			replyCell = fmt.Sprintf("%.0f ms", row.AvgReply)
		}
		// Mark advanced spellings so they're distinguishable in the list.
		noteCell := htmlEscape(row.Label)
		if row.Advanced {
			noteCell += ` <span class="adv">adv</span>`
		}
		// Heat the probability cell so harder/more-likely notes stand out.
		fmt.Fprintf(&b,
			`<tr>
  <td class="note">%s</td><td>%s</td><td class="num">%d</td>
  <td class="num">%s</td><td class="num">%s</td><td class="num">%.2f</td>
  <td class="num">%s</td><td class="num">%s</td>
</tr>
`,
			noteCell, row.Clef, row.Attempts,
			successCell, replyCell, row.Weight,
			probCell(row.ProbInClef), probCell(row.ProbBoth),
		)
	}
	b.WriteString("</tbody></table>\n")
	b.WriteString(statsFooterHTML)
	io.WriteString(w, b.String())
}

// staffNote is one note to draw on a staff: its clef, VexFlow key/accidental,
// and selection probability (ProbBoth) used to tint the note head.
type staffNote struct {
	Clef       string  `json:"clef"`
	Key        string  `json:"key"`
	Accidental string  `json:"accidental"`
	Prob       float64 `json:"prob"`
}

// staffLetterOrder maps a natural letter to its diatonic index within an
// octave (C=0 .. B=6). Used to compute a note's vertical position on a staff.
var staffLetterOrder = map[byte]int{
	'c': 0, 'd': 1, 'e': 2, 'f': 3, 'g': 4, 'a': 5, 'b': 6,
}

// staffStep returns a note's diatonic staff position from its VexFlow key
// ("<letter><acc?>/<octave>"), as octave*7 + letterIndex. This is the note
// head's vertical position on the staff, which (unlike MIDI) increases
// monotonically as you move up the lines/spaces. Used as a tiebreak so
// enharmonic spellings of one pitch (e.g. C#/4 on the C line vs Db/4 on the D
// line) order by where they actually sit, keeping note heads visually ascending.
func staffStep(key string) int {
	if key == "" {
		return 0
	}
	letter := key[0]
	slash := strings.IndexByte(key, '/')
	oct := 0
	if slash >= 0 && slash+1 < len(key) {
		if n, err := strconv.Atoi(key[slash+1:]); err == nil {
			oct = n
		}
	}
	return oct*7 + staffLetterOrder[letter]
}

// emitStaffNotes turns the (already in-mode-filtered) stat rows into a single
// run for client-side rendering. The notes form two sequential ascending runs:
// the whole bass clef (low to high) first, then the whole treble clef. Sorting
// by clef first keeps each clef's notes contiguous so the run only switches
// clef once; within a clef we sort by staff position (to keep enharmonic
// spellings ascending), then accidental for a stable order. "bass" < "treble"
// alphabetically, so the bass run comes first.
func emitStaffNotes(rows []statRow) []staffNote {
	ordered := make([]statRow, len(rows))
	copy(ordered, rows)
	sort.Slice(ordered, func(i, j int) bool {
		if ordered[i].Clef != ordered[j].Clef {
			return ordered[i].Clef < ordered[j].Clef
		}
		si, sj := staffStep(ordered[i].Key), staffStep(ordered[j].Key)
		if si != sj {
			return si < sj
		}
		return ordered[i].Accidental < ordered[j].Accidental
	})
	out := make([]staffNote, 0, len(ordered))
	for _, r := range ordered {
		out = append(out, staffNote{
			Clef:       r.Clef,
			Key:        r.Key,
			Accidental: r.Accidental,
			Prob:       r.ProbBoth,
		})
	}
	return out
}

// probCell renders a probability as a percentage with a small inline bar.
func probCell(p float64) string {
	pct := p * 100
	bar := int(p * 200) // bar width factor
	return fmt.Sprintf(
		`<span class="bar" style="--w:%dpx"></span>%.1f%%`, bar, pct)
}

func htmlEscape(s string) string {
	s = strings.ReplaceAll(s, "&", "&amp;")
	s = strings.ReplaceAll(s, "<", "&lt;")
	s = strings.ReplaceAll(s, ">", "&gt;")
	return s
}

func main() {
	home, _ := os.UserHomeDir()
	defaultDB := filepath.Join(home, ".local", "share", "notenlesen", "notenlesen.db")

	dbPath := flag.String("db", defaultDB, "Path to the SQLite database")
	addr := flag.String("addr", "127.0.0.1:8771", "Listen address")
	flag.Parse()

	db, err := initDB(*dbPath)
	if err != nil {
		fmt.Fprintf(os.Stderr, "notenlesen: %v\n", err)
		os.Exit(1)
	}
	defer db.Close()

	s := &server{
		db:   db,
		pool: buildPool(),
		rng:  rand.New(rand.NewSource(time.Now().UnixNano())),
	}

	mux := http.NewServeMux()
	mux.HandleFunc("GET /", s.handleIndex)
	mux.HandleFunc("GET /next", s.handleNext)
	mux.HandleFunc("POST /answer", s.handleAnswer)
	mux.HandleFunc("GET /session", s.handleSession)
	mux.HandleFunc("GET /stats", s.handleStats)
	mux.HandleFunc("GET /midi", s.handleMidi)

	fmt.Fprintf(os.Stderr, "notenlesen: listening on http://%s (db: %s)\n", *addr, *dbPath)
	if err := http.ListenAndServe(*addr, mux); err != nil {
		fmt.Fprintf(os.Stderr, "notenlesen: %v\n", err)
		os.Exit(1)
	}
}

// ============================================================================
// Inline frontend (HTML + CSS + JS)
// ============================================================================
//
// The page is a single template with two placeholders, __LOW_MIDI__ and
// __HIGH_MIDI__: the low and high MIDI numbers of the on-screen piano.
// VexFlow is loaded from a CDN.

const pageHTML = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>notenlesen — note reading trainer</title>
<script src="https://cdn.jsdelivr.net/npm/vexflow@4.2.3/build/cjs/vexflow.js"></script>
<style>
  /* Light theme by default; the whole page follows the OS/browser setting. */
  :root {
    --bg: #f4f4f6;
    --fg: #1b1b1f;
    --stats: #5f6368;
    --accent: #2f6fb0;
    --good: #2e7d32;
    --bad: #c62828;
    --staff-bg: #ffffff;
    --whitekey: #fafafa;
    --whitekey-border: #999;
    --whitekey-active: #cfe4f7;
    --refkey: #dcdce0;
    --blackkey: #222;
    --blackkey-border: #222;
    --blackkey-active: #3a6ea5;
    --keylabel: #888;
  }
  @media (prefers-color-scheme: dark) {
    :root {
      --bg: #1b1b1f;
      --fg: #e8e8ea;
      --stats: #9aa0a6;
      --accent: #5aa9e6;
      --good: #4caf50;
      --bad: #e05260;
      --staff-bg: #15151a;
      --whitekey: #2a2a30;
      --whitekey-border: #888;
      --whitekey-active: #3a6ea5;
      --refkey: #3d3d46;
      --blackkey: #43434d;
      --blackkey-border: #aaa;
      --blackkey-active: #3a6ea5;
      --keylabel: #777;
    }
  }
  * { box-sizing: border-box; }
  body {
    margin: 0;
    font-family: system-ui, sans-serif;
    background: var(--bg);
    color: var(--fg);
    display: flex;
    flex-direction: column;
    align-items: center;
    min-height: 100vh;
  }
  h1 { font-weight: 500; margin: 1rem 0 .25rem; }
  #stats { color: var(--stats); font-size: .9rem; margin-bottom: .5rem; min-height: 1.2em; }
  #staff {
    background: var(--staff-bg);
    border-radius: 8px;
    padding: .5rem;
    margin: 1rem 0;
    width: 360px;
    height: 220px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  /* Dark mode (follows OS/browser setting): invert the leadsheet (staff).
     VexFlow draws in black on white; recolor the SVG strokes/fills to light. */
  @media (prefers-color-scheme: dark) {
    #staff svg path,
    #staff svg rect,
    #staff svg line,
    #staff svg text {
      stroke: var(--fg) !important;
      fill: var(--fg) !important;
    }
  }
  #feedback {
    height: 1.5rem;
    font-size: 1.2rem;
    font-weight: 600;
    margin-bottom: .5rem;
  }
  #feedback.good { color: var(--good); }
  #feedback.bad { color: var(--bad); }

  /* Piano */
  #piano-wrap { width: 100%; overflow-x: auto; padding: 1rem; }
  #piano {
    position: relative;
    height: 140px;
    width: fit-content;
    margin: 0 auto;
    display: flex;
    user-select: none;
  }
  .white {
    position: relative;
    width: 34px;
    height: 140px;
    background: var(--whitekey);
    border: 1px solid var(--whitekey-border);
    border-radius: 0 0 5px 5px;
    cursor: pointer;
  }
  /* C4 (middle C): subtly shaded as a visual reference point. */
  .white.ref { background: var(--refkey); }
  .white:active, .white.active, .white.ref:active, .white.ref.active {
    background: var(--whitekey-active);
  }
  .black {
    position: absolute;
    top: 0;
    width: 22px;
    height: 88px;
    background: var(--blackkey);
    border: 1px solid var(--blackkey-border);
    border-radius: 0 0 4px 4px;
    cursor: pointer;
    z-index: 2;
  }
  .black:active, .black.active { background: var(--blackkey-active); }
  .keylabel {
    position: absolute;
    bottom: 4px;
    width: 100%;
    text-align: center;
    font-size: .6rem;
    color: var(--keylabel);
    pointer-events: none;
  }
  #staff-row {
    display: flex;
    align-items: center;
    gap: .75rem;
  }
  #clef-buttons {
    display: flex;
    flex-direction: column;
    gap: .4rem;
  }
  .clef-btn {
    background: var(--whitekey);
    color: var(--fg);
    border: 1px solid var(--whitekey-border);
    border-radius: 6px;
    padding: .4rem .7rem;
    cursor: pointer;
    font-size: .85rem;
    min-width: 4rem;
  }
  .clef-btn:hover { border-color: var(--accent); }
  .clef-btn.active {
    background: var(--accent);
    border-color: var(--accent);
    color: #fff;
    font-weight: 600;
  }
  .navlink { color: var(--accent); text-decoration: none; font-size: .9rem; }
  .navlink:hover { text-decoration: underline; }
  .midi-status { font-size: .85rem; margin-left: .4rem; }
  .midi-status.on { color: var(--good); }
  .midi-status.off { color: var(--stats); }
  /* Slider switch for the Advanced toggle. */
  .switch {
    display: flex;
    align-items: center;
    gap: .4rem;
    cursor: pointer;
    font-size: .8rem;
    margin-top: .2rem;
    user-select: none;
  }
  .switch input { position: absolute; opacity: 0; width: 0; height: 0; }
  .switch .slider {
    position: relative;
    flex: 0 0 auto;
    width: 2.2rem;
    height: 1.2rem;
    background: var(--whitekey-border);
    border-radius: 1rem;
    transition: background .15s ease;
  }
  .switch .slider::before {
    content: "";
    position: absolute;
    top: 2px;
    left: 2px;
    width: calc(1.2rem - 4px);
    height: calc(1.2rem - 4px);
    background: #fff;
    border-radius: 50%;
    transition: transform .15s ease;
    box-shadow: 0 1px 2px rgba(0,0,0,.3);
  }
  .switch input:checked + .slider { background: var(--accent); }
  .switch input:checked + .slider::before { transform: translateX(1rem); }
  .switch input:focus-visible + .slider { outline: 2px solid var(--accent); outline-offset: 2px; }
  .switch-label { color: var(--fg); }
</style>
</head>
<body>
  <h1>notenlesen</h1>
  <div id="stats"></div>
  <div id="staff-row">
    <div id="clef-buttons">
      <button class="clef-btn" data-clef="">Both</button>
      <button class="clef-btn" data-clef="treble">Treble</button>
      <button class="clef-btn" data-clef="bass">Bass</button>
      <label class="switch" title="Include enharmonic spellings (B#, Cb, double sharps/flats)">
        <input type="checkbox" id="advanced-btn">
        <span class="slider"></span>
        <span class="switch-label">Advanced</span>
      </label>
    </div>
    <div id="staff"></div>
  </div>
  <div id="feedback">&nbsp;</div>
  <div id="piano-wrap"><div id="piano"></div></div>
  <p>
    <a href="/stats" class="navlink">View note statistics &rarr;</a>
    &nbsp;·&nbsp;
    <a href="/midi" class="navlink">MIDI setup &rarr;</a>
    <span id="midi-status" class="midi-status"></span>
  </p>

<script>
(function () {
  "use strict";

  // VexFlow UMD exposes a global named "Vex" (with .Flow) in the CJS build.
  var VF = (window.Vex && window.Vex.Flow) || window.VexFlow;

  var LOW_MIDI = __LOW_MIDI__;
  var HIGH_MIDI = __HIGH_MIDI__;

  var SHARP_PC = [
    {letter:"C", acc:""}, {letter:"C", acc:"#"}, {letter:"D", acc:""},
    {letter:"D", acc:"#"}, {letter:"E", acc:""}, {letter:"F", acc:""},
    {letter:"F", acc:"#"}, {letter:"G", acc:""}, {letter:"G", acc:"#"},
    {letter:"A", acc:""}, {letter:"A", acc:"#"}, {letter:"B", acc:""}
  ];
  function isBlack(midi) { return SHARP_PC[((midi % 12) + 12) % 12].acc === "#"; }
  function labelFor(midi) {
    var pc = SHARP_PC[((midi % 12) + 12) % 12];
    var octave = Math.floor(midi / 12) - 1;
    return pc.letter + pc.acc + octave;
  }

  var staffEl = document.getElementById("staff");
  var feedbackEl = document.getElementById("feedback");
  var statsEl = document.getElementById("stats");

  var current = null;     // current note from /next
  var shownAt = 0;        // performance.now() when note was rendered
  var locked = false;     // ignore input between answer and next note
  var session = { total: 0, correct: 0 };
  var selectedClef = "";  // "" = both, "treble", or "bass"
  var advancedMode = false; // include enharmonic spellings (B#, Cb, ##, bb)

  function renderNote(n) {
    staffEl.innerHTML = "";
    var renderer = new VF.Renderer(staffEl, VF.Renderer.Backends.SVG);
    renderer.resize(340, 200);
    var ctx = renderer.getContext();
    var stave = new VF.Stave(10, 40, 320);
    stave.addClef(n.clef);
    stave.setContext(ctx).draw();

    var staveNote = new VF.StaveNote({
      clef: n.clef,
      keys: [n.key],
      duration: "q"
    });
    if (n.accidental) {
      staveNote.addModifier(new VF.Accidental(n.accidental), 0);
    }
    var voice = new VF.Voice({ num_beats: 1, beat_value: 4 });
    voice.addTickables([staveNote]);
    new VF.Formatter().joinVoices([voice]).format([voice], 240);
    voice.draw(ctx, stave);
  }

  function setFeedback(text, kind) {
    feedbackEl.textContent = text;
    feedbackEl.className = kind || "";
  }

  function updateStats() {
    var pct = session.total ? Math.round(100 * session.correct / session.total) : 0;
    statsEl.textContent = "Session: " + session.correct + " / " + session.total +
      " correct (" + pct + "%)";
  }

  function nextNote() {
    locked = true;
    // Pass the current (about-to-be-previous) note so the server avoids
    // repeating it as the next note.
    var params = [];
    if (selectedClef) params.push("clef=" + encodeURIComponent(selectedClef));
    if (advancedMode) params.push("advanced=1");
    if (current) {
      params.push("prevClef=" + encodeURIComponent(current.clef));
      params.push("prevSpelling=" + encodeURIComponent(current.spelling));
    }
    var url = "/next" + (params.length ? "?" + params.join("&") : "");
    fetch(url).then(function (r) { return r.json(); }).then(function (n) {
      current = n;
      renderNote(n);
      setFeedback("\u00a0", "");
      // Start the reply timer when the note is actually painted, not when the
      // fetch resolved: rendering the SVG happens before the browser paints,
      // so we wait for the next animation frame to avoid counting render lag.
      requestAnimationFrame(function () {
        shownAt = performance.now();
        locked = false;
      });
    }).catch(function (e) {
      setFeedback("error loading note", "bad");
      console.error(e);
    });
  }

  function answer(answerMidi) {
    if (locked || !current) return;
    locked = true;
    var replyMs = Math.round(performance.now() - shownAt);
    var body = {
      clef: current.clef,
      midi: current.midi,
      spelling: current.spelling,
      answer_midi: answerMidi,
      reply_ms: replyMs
    };
    fetch("/answer", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body)
    }).then(function (r) { return r.json(); }).then(function (res) {
      // The session counter is computed server-side from attempt timestamps
      // (a session = answers with no >5min pause between them), so it survives
      // reloads and resets after a long break.
      if (res.session) session = res.session;
      if (res.correct) {
        setFeedback("\u2713 correct", "good");
      } else {
        // Show the spelling that was actually displayed (e.g. "Gb3"), not a
        // sharp spelling derived from the pitch.
        setFeedback("\u2717 was " + current.spelling.replace("/", ""), "bad");
      }
      updateStats();
      // brief pause so the user sees the result, then advance
      setTimeout(nextNote, res.correct ? 350 : 900);
    }).catch(function (e) {
      locked = false;
      console.error(e);
    });
  }

  // Build the piano keyboard from LOW_MIDI..HIGH_MIDI.
  function buildPiano() {
    var piano = document.getElementById("piano");
    var whiteWidth = 34;
    // First pass: place white keys, remember their left offset by midi.
    var whiteLeft = {};
    var x = 0;
    for (var m = LOW_MIDI; m <= HIGH_MIDI; m++) {
      if (isBlack(m)) continue;
      var w = document.createElement("div");
      w.className = "white" + (m === 60 ? " ref" : ""); // 60 = C4 (middle C)
      w.dataset.midi = m;
      var lbl = document.createElement("span");
      lbl.className = "keylabel";
      lbl.textContent = labelFor(m);
      w.appendChild(lbl);
      piano.appendChild(w);
      whiteLeft[m] = x;
      x += whiteWidth;
    }
    // Second pass: place black keys absolutely, straddling the gap to the
    // previous white key.
    for (var b = LOW_MIDI; b <= HIGH_MIDI; b++) {
      if (!isBlack(b)) continue;
      var prevWhite = b - 1; // sharp sits above the white key below it
      if (!(prevWhite in whiteLeft)) continue;
      var k = document.createElement("div");
      k.className = "black";
      k.dataset.midi = b;
      k.style.left = (whiteLeft[prevWhite] + whiteWidth - 11) + "px";
      piano.appendChild(k);
    }

    // Use the click event: a real left click (press + release on the same
    // key). It only fires for the primary button, so right/middle clicks are
    // ignored, and it works for touch/pen too.
    piano.addEventListener("click", function (ev) {
      var t = ev.target.closest(".white, .black");
      if (!t) return;
      var midi = parseInt(t.dataset.midi, 10);
      flashKey(midi);
      answer(midi);
    });
  }

  // flashKey briefly highlights the on-screen key for the given MIDI pitch,
  // mirroring the visual feedback of a click. Used by both click and MIDI input.
  // Notes outside the keyboard range have no key element and are ignored.
  function flashKey(midi) {
    var el = document.querySelector('[data-midi="' + midi + '"]');
    if (!el) return;
    el.classList.add("active");
    setTimeout(function () { el.classList.remove("active"); }, 120);
  }

  // Clef selection: choose which clef the next notes use (persisted).
  // Only buttons with a data-clef attribute are clef buttons (excludes the
  // advanced toggle, which also carries the .clef-btn style).
  var clefBtns = document.querySelectorAll(".clef-btn[data-clef]");
  function applyClef(clef, advance) {
    selectedClef = clef;
    clefBtns.forEach(function (b) {
      b.classList.toggle("active", b.dataset.clef === clef);
    });
    try { localStorage.setItem("notenlesen.clef", clef); } catch (e) {}
    if (advance) nextNote();
  }
  clefBtns.forEach(function (b) {
    b.addEventListener("click", function () { applyClef(b.dataset.clef, true); });
  });
  var savedClef = "";
  try {
    var sc = localStorage.getItem("notenlesen.clef");
    if (sc === "treble" || sc === "bass" || sc === "") savedClef = sc;
  } catch (e) {}

  // Advanced mode toggle (slider switch): include enharmonic spellings.
  var advancedBtn = document.getElementById("advanced-btn");
  function applyAdvanced(on, advance) {
    advancedMode = on;
    advancedBtn.checked = on;
    try { localStorage.setItem("notenlesen.advanced", on ? "1" : "0"); } catch (e) {}
    if (advance) nextNote();
  }
  advancedBtn.addEventListener("change", function () {
    applyAdvanced(advancedBtn.checked, true);
  });
  var savedAdvanced = false;
  try { savedAdvanced = localStorage.getItem("notenlesen.advanced") === "1"; } catch (e) {}

  // MIDI input: read the device + channel locked in on the /midi setup page and
  // accept note-on from exactly that (port, channel) pair, alongside the
  // on-screen piano. Only note-on (status 0x90, velocity > 0) triggers an
  // answer; everything else is ignored. The setup page stores the pair in
  // localStorage["notenlesen.midi"] as {portId, portName, channel}.
  var midiStatusEl = document.getElementById("midi-status");
  function setMidiStatus(text, on) {
    if (!midiStatusEl) return;
    midiStatusEl.textContent = text;
    midiStatusEl.className = "midi-status " + (on ? "on" : "off");
  }
  // Parse a raw MIDI message into a note-on, or null for anything else.
  function parseNoteOn(data) {
    if (!data || data.length < 3) return null;
    if ((data[0] & 0xf0) !== 0x90) return null; // not note-on
    if (data[2] === 0) return null;             // velocity 0 = note-off
    return { channel: data[0] & 0x0f, note: data[1] };
  }
  function initMidi() {
    var saved = null;
    try {
      var raw = localStorage.getItem("notenlesen.midi");
      if (raw) saved = JSON.parse(raw);
    } catch (e) {}
    if (!saved) { setMidiStatus("(no MIDI device — set up)", false); return; }
    if (!navigator.requestMIDIAccess) {
      setMidiStatus("(MIDI unavailable in this browser)", false);
      return;
    }
    navigator.requestMIDIAccess().then(function (access) {
      function bind() {
        var port = access.inputs.get(saved.portId);
        if (!port) {
          setMidiStatus("(MIDI device not connected — reload after plugging in)", false);
          return;
        }
        port.onmidimessage = function (ev) {
          var on = parseNoteOn(ev.data);
          if (!on || on.channel !== saved.channel) return;
          flashKey(on.note);
          answer(on.note);
        };
        setMidiStatus("\u266a " + (saved.portName || "MIDI") +
          " (ch " + (saved.channel + 1) + ")", true);
      }
      bind();
      // Re-bind on plug/unplug so reconnecting just works (Chrome/Edge). Firefox
      // does not fire statechange for hot-plug; there you reload the page.
      access.onstatechange = bind;
    }).catch(function () {
      setMidiStatus("(MIDI access denied)", false);
    });
  }

  if (!VF) {
    setFeedback("VexFlow failed to load (needs network for CDN)", "bad");
    return;
  }
  buildPiano();
  updateStats();
  // Initialize the session counter from the server (continues the current
  // session if you reload within 5 minutes).
  fetch("/session").then(function (r) { return r.json(); }).then(function (s) {
    if (s) { session = s; updateStats(); }
  }).catch(function () {});
  applyClef(savedClef, false);
  applyAdvanced(savedAdvanced, false);
  initMidi();
  nextNote();
})();
</script>
</body>
</html>
`

// statsHeaderHTML opens the /stats page (theme matches the main page, following
// the OS/browser light/dark setting). The table body is written between this
// header and statsFooterHTML.
const statsHeaderHTML = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>notenlesen — note statistics</title>
<script src="https://cdn.jsdelivr.net/npm/vexflow@4.2.3/build/cjs/vexflow.js"></script>
<style>
  :root {
    --bg: #f4f4f6;
    --fg: #1b1b1f;
    --stats: #5f6368;
    --accent: #2f6fb0;
    --good: #2e7d32;
    --bad: #c62828;
    --row-border: #ddd;
    --bar: #9cc4ea;
    --staff-bg: #ffffff;
  }
  @media (prefers-color-scheme: dark) {
    :root {
      --bg: #1b1b1f;
      --fg: #e8e8ea;
      --stats: #9aa0a6;
      --accent: #5aa9e6;
      --good: #4caf50;
      --bad: #e05260;
      --row-border: #333;
      --bar: #3a6ea5;
      --staff-bg: #15151a;
    }
  }
  * { box-sizing: border-box; }
  body {
    margin: 0;
    font-family: system-ui, sans-serif;
    background: var(--bg);
    color: var(--fg);
    padding: 1.5rem;
    max-width: 900px;
    margin: 0 auto;
  }
  h1 { font-weight: 500; }
  .navlink { color: var(--accent); text-decoration: none; font-size: .9rem; }
  .navlink:hover { text-decoration: underline; }
  p.intro { color: var(--stats); font-size: .9rem; max-width: 640px; }
  table { border-collapse: collapse; width: 100%; margin-top: 1rem; }
  th, td {
    text-align: left;
    padding: .35rem .6rem;
    border-bottom: 1px solid var(--row-border);
    font-size: .9rem;
    white-space: nowrap;
  }
  th { color: var(--stats); font-weight: 600; }
  td.note { font-weight: 600; font-variant-numeric: tabular-nums; }
  td.num { text-align: right; font-variant-numeric: tabular-nums; }
  .adv {
    font-size: .7em;
    font-weight: 600;
    color: var(--bg);
    background: var(--accent);
    border-radius: 3px;
    padding: 0 .3em;
    vertical-align: middle;
  }
  .bar {
    display: inline-block;
    height: .6em;
    width: var(--w);
    background: var(--bar);
    border-radius: 2px;
    margin-right: .4rem;
    vertical-align: baseline;
  }
  /* Weight staff: a single SVG with every in-mode note as one continuous run
     (bass then treble), each note head tinted by its selection probability. */
  #staves { margin: 1rem 0 1.5rem; }
  #grand-staff {
    background: var(--staff-bg);
    border-radius: 8px;
    padding: .5rem;
    margin: .5rem 0;
    overflow-x: auto;
  }
  /* Legend: a gradient strip showing the opacity ramp = selection probability,
     from the faint floor (rarely shown) to fully opaque (most likely next).
     The bar sits on the staff background and uses the note color (currentColor)
     so it matches the actual note tint in both light and dark themes. */
  #staff-legend {
    display: flex;
    align-items: center;
    gap: .5rem;
    font-size: .8rem;
    color: var(--stats);
    margin: .25rem 0 0 .25rem;
  }
  .legend-bar {
    display: inline-block;
    width: 140px;
    height: .8em;
    border-radius: 3px;
    background:
      linear-gradient(to right,
        rgba(127,127,127,.12), rgba(127,127,127,1)),
      var(--staff-bg);
    border: 1px solid var(--row-border);
  }
  /* Note: the staff, clef and note glyphs are painted in the theme's
     foreground color directly in JS (via VexFlow setStyle), so they show
     correctly in both light and dark mode without any CSS recolor hack. */
</style>
</head>
<body>
  <h1>Note statistics</h1>
  <p><a href="/" class="navlink">&larr; Back to practice</a></p>
  <div id="staves">
    <div id="grand-staff"></div>
    <div id="staff-legend">
      <span class="legend-label">fast &amp; correct</span>
      <span class="legend-bar"></span>
      <span class="legend-label">to work on</span>
    </div>
  </div>
  <p class="intro">
    Selection probability of each written note, based on your recorded attempts.
    On the staves above, every in-mode note is drawn in pitch order; each note
    head is tinted by how likely it is to come up next (more opaque = more
    likely). Tracking is per <em>thing on the paper</em>: enharmonic spellings
    (e.g. C#4 vs Db4) and the same note in different clefs are counted
    separately. Harder, slower, or never-seen notes get higher weight and so
    appear more often. "P (this clef)" is the probability when practising only
    that clef; "P (both)" is for the combined Both mode.
  </p>
`

// statsFooterHTML closes the /stats page. It renders the weight staff from
// window.__STAFF_NOTES__ (emitted by handleStats): every in-mode note as one
// continuous run on a single staff line — the whole bass clef ascending, then a
// clef change to treble, then the whole treble clef ascending — laid out as
// 8-note bars across full-width system rows, each note head tinted by selection
// probability via the SVG opacity attribute.
const statsFooterHTML = `
<script>
(function () {
  "use strict";
  var VF = (window.Vex && window.Vex.Flow) || window.VexFlow;
  var all = window.__STAFF_NOTES__ || [];
  var root = document.getElementById("grand-staff");
  if (!VF || !root || !all.length) return;

  var MIN_OPACITY = 0.12;     // floor so near-zero notes stay faintly visible
  var NOTES_PER_BAR = 8;      // a barline every 8 notes
  var BEAM_GROUP = 4;         // beam consecutive same-clef notes in groups of 4
  var perNote = 30;           // horizontal slot width per note
  var clefPad = 50;           // room for the clef at a row's left
  var staffY = 30, staffH = 110;

  // Tint is normalized against the most-probable note over the whole run, so a
  // given opacity means the same thing everywhere on the page.
  var maxProb = 0;
  all.forEach(function (n) { if (n.prob > maxProb) maxProb = n.prob; });

  // Split the run into fixed-size bars (used for barlines + beaming).
  var bars = [];
  for (var i = 0; i < all.length; i += NOTES_PER_BAR) {
    bars.push(all.slice(i, i + NOTES_PER_BAR));
  }
  var barWidth = NOTES_PER_BAR * perNote;
  var systemGap = 30; // vertical space between system rows in the single SVG

  // Build an rgba() string from a "rgb(r, g, b)" base color and an alpha.
  function rgba(base, alpha) {
    var m = base.match(/rgba?\(([^)]+)\)/);
    if (m) {
      var p = m[1].split(",");
      return "rgba(" + p[0].trim() + "," + p[1].trim() + "," + p[2].trim() +
             "," + alpha + ")";
    }
    return base;
  }

  // renderStaff draws the whole staff into the single SVG. It reads the current
  // theme colors each time, so calling it again after a light/dark switch
  // repaints everything correctly. VexFlow has no built-in theming, so we paint
  // explicitly: note glyphs in the foreground "ink" (tinted by probability),
  // staff lines / ledger lines in the muted --stats gray (which is close to
  // VexFlow's default soft gray and adapts per theme), clefs in full ink.
  function renderStaff() {
    root.innerHTML = "";

    var cs = getComputedStyle(document.body);
    var noteInk = cs.getPropertyValue("color").trim() || "rgb(27,27,31)";
    var staffInkBase = cs.getPropertyValue("--stats").trim() || "#888";
    // --stats may be a hex value; normalize to a usable stroke/fill color.
    var staffInk = staffInkBase;
    var noteInkSolid = rgba(noteInk, 1);

    var realNotes = []; // {sn} collected for reference (tinted at creation)
    var beamsToDraw = [];

    // Fit as many bars per row as the container width allows (full-width
    // systems wrapping down the page). The first bar of a row also shows the
    // clef, so it is wider. Always at least one bar per row.
    var avail = (root.clientWidth || 800) - 20;
    var barsPerSystem = Math.floor((avail - clefPad) / barWidth);
    if (barsPerSystem < 1) barsPerSystem = 1;

    // Everything is drawn into ONE SVG: each system row is stacked at an
    // increasing y offset rather than living in its own renderer.
    var numSystems = Math.ceil(bars.length / barsPerSystem);
    var firstRowBars = Math.min(barsPerSystem, bars.length);
    var svgWidth = clefPad + firstRowBars * barWidth + 20;
    var svgHeight = numSystems * (staffH + systemGap) + 20;

    var renderer = new VF.Renderer(root, VF.Renderer.Backends.SVG);
    renderer.resize(svgWidth, svgHeight);
    var ctx = renderer.getContext();

    // Track the clef in effect as we walk the run, so each row/bar starts in
    // the correct clef and we only draw a clef-change glyph at the switch.
    var runningClef = bars.length ? bars[0][0].clef : "treble";
    var systemIndex = 0;

    for (var s = 0; s < bars.length; s += barsPerSystem) {
      var systemBars = bars.slice(s, s + barsPerSystem);
      var rowY = staffY + systemIndex * (staffH + systemGap);
      systemIndex++;

      var x = 10;
      systemBars.forEach(function (bar, bi) {
        var w = barWidth + (bi === 0 ? clefPad : 0);
        var stave = new VF.Stave(x, rowY, w);
        // Every row's first bar restates the clef in effect at its start.
        if (bi === 0) stave.addClef(runningClef);
        // Staff lines in the muted staff ink...
        stave.setStyle({ strokeStyle: staffInk, fillStyle: staffInk });
        // ...but the clef and barlines (stave modifiers) in full note ink, so
        // they read as solid foreground (black in light mode, white in dark).
        var mods = stave.getModifiers ? stave.getModifiers() : [];
        mods.forEach(function (m) {
          if (m.setStyle) m.setStyle({ strokeStyle: noteInkSolid, fillStyle: noteInkSolid });
        });
        stave.setContext(ctx).draw();

        var tickables = [];
        var beamGroups = [], curGroup = null, curClef = null;
        bar.forEach(function (n) {
          // Insert a clef-change glyph when the run switches clef mid-line.
          if (n.clef !== runningClef) {
            var cn = new VF.ClefNote(n.clef, "small");
            cn.setStyle({ fillStyle: noteInkSolid, strokeStyle: noteInkSolid });
            tickables.push(cn);
            runningClef = n.clef;
            curGroup = null; curClef = null; // break beam across clef change
          }
          var sn = new VF.StaveNote({ clef: n.clef, keys: [n.key], duration: "8" });
          if (n.accidental) sn.addModifier(new VF.Accidental(n.accidental), 0);
          // Tint by selection probability: note ink with alpha. setStyle covers
          // head + stem + accidental; ledger lines need their own style and use
          // the muted staff ink so they read like the staff, not the data.
          var op = maxProb > 0 ? n.prob / maxProb : 0;
          if (op < MIN_OPACITY) op = MIN_OPACITY;
          var color = rgba(noteInk, op.toFixed(3));
          sn.setStyle({ fillStyle: color, strokeStyle: color });
          if (sn.setLedgerLineStyle) {
            sn.setLedgerLineStyle({ strokeStyle: staffInk, fillStyle: staffInk });
          }
          sn._op = op;
          realNotes.push(sn);
          tickables.push(sn);
          // Beam consecutive same-clef notes in groups of BEAM_GROUP.
          if (n.clef !== curClef || !curGroup || curGroup.length >= BEAM_GROUP) {
            curGroup = []; beamGroups.push(curGroup); curClef = n.clef;
          }
          curGroup.push(sn);
        });

        // Construct the beams BEFORE drawing the voice. A Beam calls setBeam()
        // on its notes when constructed, which suppresses their individual
        // flags; if we drew the voice first, the flags would already be
        // rendered and the beam would sit on top of them (flags AND beams).
        // "true" enables autoStem: each group's stem direction is picked from
        // its own notes.
        beamGroups.forEach(function (g) {
          if (g.length < 2) return;
          var beam = new VF.Beam(g, true);
          // Tint the beam to the group's strongest note so it reads with them.
          var maxOp = 0;
          g.forEach(function (sn) { if (sn._op > maxOp) maxOp = sn._op; });
          var bc = rgba(noteInk, (maxOp || 1).toFixed(3));
          beam.setStyle({ fillStyle: bc, strokeStyle: bc });
          beamsToDraw.push(beam);
        });

        var voice = new VF.Voice({ num_beats: tickables.length, beat_value: 8 })
          .setStrict(false).addTickables(tickables);
        var fmtW = w - (bi === 0 ? clefPad : 0) - 16;
        new VF.Formatter().joinVoices([voice]).format([voice], fmtW);
        voice.draw(ctx, stave);

        x += w;
      });
    }

    beamsToDraw.forEach(function (b) { b.setContext(ctx).draw(); });
  }

  renderStaff();

  // Repaint when the OS/browser light-dark preference changes, so the staff
  // colors follow the theme without a reload.
  var mq = window.matchMedia("(prefers-color-scheme: dark)");
  if (mq.addEventListener) mq.addEventListener("change", renderStaff);
  else if (mq.addListener) mq.addListener(renderStaff); // older browsers
})();
</script>
</body>
</html>
`

// ============================================================================
// MIDI setup page (/midi)
// ============================================================================
//
// A static page that uses the Web MIDI API to identify the user's device and
// channel. It listens on every input port and channel for the pitch-class
// sequence C -> E -> G (any octave), tracked independently per (port, channel),
// and locks onto whichever pair completes the run. The detected pair is stored
// in localStorage["notenlesen.midi"] as {portId, portName, channel}; the
// practice page reads it to accept note-on input from exactly that pair.
//
// Web MIDI requires a secure context (https or localhost); the page surfaces a
// clear message when it is unavailable or denied.

const midiPageHTML = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>notenlesen — MIDI setup</title>
<style>
  :root {
    --bg: #f4f4f6;
    --fg: #1b1b1f;
    --stats: #5f6368;
    --accent: #2f6fb0;
    --good: #2e7d32;
    --bad: #c62828;
    --row-border: #ddd;
    --panel: #ffffff;
    --step: #e6e6ea;
    --step-done: #2e7d32;
    --step-active: #2f6fb0;
  }
  @media (prefers-color-scheme: dark) {
    :root {
      --bg: #1b1b1f;
      --fg: #e8e8ea;
      --stats: #9aa0a6;
      --accent: #5aa9e6;
      --good: #4caf50;
      --bad: #e05260;
      --row-border: #333;
      --panel: #15151a;
      --step: #2a2a30;
      --step-done: #4caf50;
      --step-active: #5aa9e6;
    }
  }
  * { box-sizing: border-box; }
  body {
    margin: 0;
    font-family: system-ui, sans-serif;
    background: var(--bg);
    color: var(--fg);
    padding: 1.5rem;
    max-width: 760px;
    margin: 0 auto;
  }
  h1 { font-weight: 500; }
  h2 { font-weight: 500; font-size: 1.1rem; margin: 1.5rem 0 .5rem; }
  .navlink { color: var(--accent); text-decoration: none; font-size: .9rem; }
  .navlink:hover { text-decoration: underline; }
  p.intro { color: var(--stats); font-size: .9rem; max-width: 640px; }
  .panel {
    background: var(--panel);
    border: 1px solid var(--row-border);
    border-radius: 8px;
    padding: 1rem;
    margin: 1rem 0;
  }
  .msg { font-size: .9rem; }
  .msg.bad { color: var(--bad); }
  .msg.good { color: var(--good); }
  /* C-E-G step pills */
  #steps { display: flex; gap: .6rem; margin: .75rem 0; }
  .step {
    width: 3rem; height: 3rem;
    display: flex; align-items: center; justify-content: center;
    border-radius: 8px;
    background: var(--step);
    font-size: 1.3rem; font-weight: 600;
    border: 2px solid transparent;
  }
  .step.active { border-color: var(--step-active); }
  .step.done { background: var(--step-done); color: #fff; }
  /* device list */
  ul.ports { list-style: none; padding: 0; margin: .5rem 0; }
  ul.ports li {
    padding: .35rem .5rem;
    border-bottom: 1px solid var(--row-border);
    font-size: .9rem;
    font-variant-numeric: tabular-nums;
  }
  ul.ports li .pname { font-weight: 600; }
  ul.ports li .pstate { color: var(--stats); font-size: .8rem; }
  /* live message log */
  #log {
    font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
    font-size: .8rem;
    background: var(--panel);
    border: 1px solid var(--row-border);
    border-radius: 6px;
    padding: .5rem;
    height: 9rem;
    overflow-y: auto;
    white-space: pre-wrap;
  }
  #log .line { color: var(--stats); }
  #log .line.match { color: var(--good); font-weight: 600; }
  button.btn {
    background: var(--accent);
    color: #fff;
    border: none;
    border-radius: 6px;
    padding: .45rem .9rem;
    cursor: pointer;
    font-size: .9rem;
  }
  button.btn.secondary {
    background: transparent;
    color: var(--accent);
    border: 1px solid var(--accent);
  }
  code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
</style>
</head>
<body>
  <h1>MIDI setup</h1>
  <p><a href="/" class="navlink">&larr; Back to practice</a></p>
  <p class="intro">
    Connect a MIDI keyboard, then play <strong>C, then E, then G</strong> (any
    octave). notenlesen listens on every port and channel and locks onto the
    one that played the sequence — that exact device + channel is then used for
    answering, alongside the on-screen piano. Web MIDI needs a secure context
    (use <code>localhost</code> or https). Firefox supports Web MIDI but does
    not detect devices plugged in after the page loads — connect your keyboard
    first, then reload the page.
  </p>

  <div class="panel">
    <h2>Status</h2>
    <div id="status" class="msg">Requesting MIDI access…</div>
    <div id="saved" class="msg"></div>
    <p><button id="forget" class="btn secondary" style="display:none">Forget device</button></p>
  </div>

  <div class="panel">
    <h2>Play C &rarr; E &rarr; G to identify your device</h2>
    <div id="steps">
      <div class="step" data-step="0">C</div>
      <div class="step" data-step="1">E</div>
      <div class="step" data-step="2">G</div>
    </div>
    <div id="detect" class="msg"></div>
  </div>

  <div class="panel">
    <h2>Detected input ports</h2>
    <ul id="ports" class="ports"><li>(none yet)</li></ul>
    <h2>Incoming note-on messages</h2>
    <div id="log"></div>
  </div>

<script>
(function () {
  "use strict";

  var STORE_KEY = "notenlesen.midi";
  // C-E-G as pitch classes (0=C, 4=E, 7=G); octave is ignored.
  var SEQUENCE = [0, 4, 7];
  var SEQ_LABEL = ["C", "E", "G"];

  var statusEl = document.getElementById("status");
  var savedEl = document.getElementById("saved");
  var forgetBtn = document.getElementById("forget");
  var detectEl = document.getElementById("detect");
  var portsEl = document.getElementById("ports");
  var logEl = document.getElementById("log");
  var stepEls = Array.prototype.slice.call(document.querySelectorAll(".step"));

  function noteLabel(midi) {
    var names = ["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];
    var pc = ((midi % 12) + 12) % 12;
    var octave = Math.floor(midi / 12) - 1;
    return names[pc] + octave;
  }

  // Parse a raw MIDI message into a note-on, or null for anything else.
  // We act on note-on only (status 0x90..0x9F, velocity > 0); a note-on with
  // velocity 0 is a note-off by convention and is ignored.
  function parseNoteOn(data) {
    if (!data || data.length < 3) return null;
    var status = data[0] & 0xf0;
    var channel = data[0] & 0x0f; // 0-based; displayed as channel+1
    if (status !== 0x90) return null;
    var velocity = data[2];
    if (velocity === 0) return null;
    return { channel: channel, note: data[1], velocity: velocity };
  }

  function setStatus(text, kind) {
    statusEl.textContent = text;
    statusEl.className = "msg" + (kind ? " " + kind : "");
  }

  function log(text, match) {
    var div = document.createElement("div");
    div.className = "line" + (match ? " match" : "");
    div.textContent = text;
    logEl.appendChild(div);
    // keep the log bounded
    while (logEl.childNodes.length > 200) logEl.removeChild(logEl.firstChild);
    logEl.scrollTop = logEl.scrollHeight;
  }

  function showSaved() {
    var raw = null;
    try { raw = localStorage.getItem(STORE_KEY); } catch (e) {}
    if (!raw) {
      savedEl.textContent = "No device saved yet.";
      savedEl.className = "msg";
      forgetBtn.style.display = "none";
      return null;
    }
    var saved = null;
    try { saved = JSON.parse(raw); } catch (e) {}
    if (!saved) { savedEl.textContent = ""; forgetBtn.style.display = "none"; return null; }
    savedEl.innerHTML = "Saved: <strong>" + escapeHtml(saved.portName || saved.portId) +
      "</strong>, channel " + (saved.channel + 1) + ".";
    savedEl.className = "msg good";
    forgetBtn.style.display = "";
    return saved;
  }

  function escapeHtml(s) {
    return String(s).replace(/[&<>]/g, function (c) {
      return c === "&" ? "&amp;" : c === "<" ? "&lt;" : "&gt;";
    });
  }

  // Per-(port,channel) progress through the C-E-G sequence. Key is
  // portId + "|" + channel; value is the index of the next expected note.
  var progress = {};

  function resetSteps() {
    stepEls.forEach(function (el) { el.className = "step"; });
  }
  function paintSteps(idx) {
    stepEls.forEach(function (el, i) {
      el.className = "step" + (i < idx ? " done" : i === idx ? " active" : "");
    });
  }

  function lockOnto(port, channel) {
    var rec = { portId: port.id, portName: port.name || port.id, channel: channel };
    try { localStorage.setItem(STORE_KEY, JSON.stringify(rec)); } catch (e) {}
    progress = {};
    stepEls.forEach(function (el) { el.className = "step done"; });
    detectEl.textContent = "Locked onto " + (port.name || port.id) +
      ", channel " + (channel + 1) + ". You can go back to practice.";
    detectEl.className = "msg good";
    showSaved();
  }

  function handleSequence(port, channel, note) {
    var key = port.id + "|" + channel;
    var pc = ((note % 12) + 12) % 12;
    var want = progress[key] || 0;
    if (pc === SEQUENCE[want]) {
      want++;
      progress[key] = want;
      paintSteps(want);
      if (want >= SEQUENCE.length) {
        lockOnto(port, channel);
      }
    } else if (pc === SEQUENCE[0]) {
      // Wrong note, but it's a C: restart the run at step 1 for this pair.
      progress[key] = 1;
      paintSteps(1);
    } else {
      // Out-of-sequence note: reset this pair's progress.
      progress[key] = 0;
      paintSteps(0);
    }
  }

  function midiAccess(access) {
    setStatus("MIDI ready.", "good");
    showSaved();

    function refreshPorts() {
      portsEl.innerHTML = "";
      var any = false;
      access.inputs.forEach(function (port) {
        any = true;
        var li = document.createElement("li");
        li.innerHTML = "<span class=\"pname\">" + escapeHtml(port.name || port.id) +
          "</span> <span class=\"pstate\">" +
          escapeHtml((port.manufacturer || "") + " · " + port.state + "/" + port.connection) +
          "</span>";
        portsEl.appendChild(li);
      });
      if (!any) {
        var li = document.createElement("li");
        li.textContent = "(no input ports — connect a MIDI device)";
        portsEl.appendChild(li);
      }
    }

    function attach(port) {
      port.onmidimessage = function (ev) {
        var on = parseNoteOn(ev.data);
        if (!on) return;
        var line = (port.name || port.id) + " — ch " + (on.channel + 1) +
          " — " + noteLabel(on.note) + " (" + on.note + ")";
        var isSeqNote = SEQUENCE.indexOf(((on.note % 12) + 12) % 12) >= 0;
        log(line, isSeqNote);
        handleSequence(port, on.channel, on.note);
      };
    }

    access.inputs.forEach(attach);
    refreshPorts();

    // Hot-plug events: works in Chrome/Edge. Firefox does not fire these, so a
    // device connected after load only shows up after reloading the page.
    access.onstatechange = function (ev) {
      refreshPorts();
      if (ev.port && ev.port.type === "input" && ev.port.state === "connected") {
        attach(ev.port);
      }
    };
  }

  forgetBtn.addEventListener("click", function () {
    try { localStorage.removeItem(STORE_KEY); } catch (e) {}
    progress = {};
    resetSteps();
    detectEl.textContent = "Device forgotten. Play C-E-G to set a new one.";
    detectEl.className = "msg";
    showSaved();
  });

  if (!navigator.requestMIDIAccess) {
    setStatus("Web MIDI is not available in this browser. Use a recent " +
      "Chrome, Edge or Firefox, and make sure you're on localhost or https.", "bad");
    showSaved();
    return;
  }
  navigator.requestMIDIAccess().then(midiAccess).catch(function (e) {
    setStatus("MIDI access denied or failed: " + (e && e.message ? e.message : e) +
      ". Web MIDI needs a secure context (localhost or https).", "bad");
    showSaved();
  });
})();
</script>
</body>
</html>
`