All files / js objnam.js

83.25% Statements 1432/1720
66.48% Branches 498/749
89.47% Functions 51/57
83.25% Lines 1432/1720

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 172173x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 126x 126x 1598x 1598x 115x 126x 73x 73x 17272x 17272x 17272x 17272x 17272x 17272x 50x 50x 50x     50x 50x 50x 50x 50x 50x 73x 73x 73x 73x 73x 73x 73x 73x 73x 1084x 1084x 1084x 1084x 1084x     1084x 1084x 1084x 1084x 1084x 9x 9x 1075x 1075x 1084x 1084x 1084x 1084x 1084x 1084x 215x 215x 860x 1084x     860x 1084x 73x 73x 73x 180x 180x 73x 73x 73x 73x 296x 296x 296x 296x 296x 296x 44x 44x 252x 252x 252x 252x 252x 252x 252x 252x 252x 252x 252x 252x 252x 252x 252x 252x 252x 252x 252x 252x 252x 252x 252x 252x 252x 252x 252x 252x 252x 252x 252x 252x 252x 252x 296x 5529x 1x 1x 1x 1x 5529x     5529x 296x 6024x 6024x 6024x 251x 296x 296x 296x 250x 250x 250x 250x 250x 250x 295x 1750x     1750x 250x 296x 296x 296x     250x 295x                   250x 295x     250x 296x     250x 296x     250x 250x 296x     250x 296x     250x 250x 296x 73x 73x 73x 73x 73x 73x 73x 1x 1x 1x 1x 1x 1x 73x 73x 73x 73x 1534x 1534x 1534x 1534x 1534x 71x 71x 1534x 1534x 1534x 1534x 1534x 126x 126x 126x 126x 1534x 1534x 1534x 1534x 1534x 1534x 1534x 1534x 1534x 38x 38x 1534x             1534x 1534x 1534x 1534x 1534x 456x 456x 456x 456x 456x 456x 456x   456x 373x 452x     83x 83x 83x 456x 456x       456x 456x 1534x 175x 175x 34x 34x 175x 175x 137x 160x       38x 38x 38x 175x 175x 1x 1x 175x 1534x 165x 5x 5x 165x 76x 76x 76x 76x 76x 4x 4x 76x 76x     165x 89x 89x 165x 1534x 112x 112x     112x 26x 110x   86x 82x 86x 4x 4x 112x 1534x 111x   111x 64x 111x   47x 47x 47x 111x 1534x 91x   91x 37x 86x   54x 54x 54x 91x 1534x 56x       56x 35x 35x 35x 21x 21x 1534x 28x 28x 28x 3x 3x 3x 28x       28x           28x       28x       28x 28x 1534x 153x 153x 1534x 84x 84x 1534x 23x 23x 23x 13x 13x 13x 13x 13x 13x 23x     10x 10x 10x 23x 23x 1534x 79x 79x 79x   79x 29x   29x 29x 29x 79x 50x 50x 50x 79x 79x 1534x 1x 1x 1534x 1534x 1534x 6x 6x 2x 2x 2x     6x 4x 4x 4x 1x 1x 1x 1x 1x 4x 4x 6x 1534x 1534x 1534x 1534x 1534x 38x 38x 38x 38x 38x 38x 1534x 1534x 244x 244x 1534x 1534x 73x 73x 73x 73x 73x 1130x 1130x 1130x 1130x 1130x 1130x 1130x 1130x 1130x 1130x 1130x 1130x 1130x 1130x 1130x 1130x 1130x 1130x 1130x 1130x 1130x 233x 1130x 35x 897x 3x     3x 862x 859x 859x 1130x 1130x 1130x 1130x 8x 8x 1130x 1130x 1130x 1130x 1130x 1130x 1130x 1130x 437x 4x 437x 87x 432x 346x 346x 346x 346x 346x 215x 215x 346x 437x 1130x 1130x 1130x 8x 1x 8x 6x 7x 1x 1x 8x 1130x 1130x 1130x     1130x 1130x     1130x 1130x 1x 1x 1x 1x 1130x 1130x 1130x 1130x 1130x 1130x 8x 8x 1130x 53x 53x 1130x 1130x 1130x 318x 318x 318x 318x 318x 318x 318x 318x 318x 318x 1x 1x 1x 1x 1x 1x 318x         318x 1x 1x 1x     1x 1x 318x 318x 318x 153x 153x 153x 318x 1130x 1130x 4x 4x 4x 1130x 1130x 1130x 1130x 1130x 1x 1x 1130x 35x 35x 35x 35x 35x 1130x 1130x 1130x     1130x 1130x           1130x     1130x 1130x 1x 1x 1130x     1130x 1130x 1130x 57x 57x 57x 57x 57x 55x 57x 57x 7x 56x 50x 50x 50x 50x 50x 50x 57x 1130x 27x 27x     27x 27x 27x 27x 1130x 9x 9x 9x 8x 8x 8x 8x 9x 9x 9x 9x 9x 1x 1x 9x     9x 9x 9x 1130x 1130x 3x 3x 1130x 10x 10x 1130x 1130x     1130x 1130x 1130x 27x 27x 27x 1130x 1130x 1130x 1130x 1121x 6x 6x 6x 6x 1121x 187x 187x 187x 10x 187x     187x 1121x 1130x 1130x 1130x 891x 891x 891x 891x 1130x 1130x 73x 73x 187x 187x 187x 187x 73x 73x 57115x 57115x 57115x 48972x 48972x 48972x 73x 28321x 28321x 28321x 28321x 28219x 28219x 28219x 28321x 5701x 5701x 5701x 28321x 1322x 1322x 1322x 28217x 28321x 146x 146x 146x 146x 146x 1x 9x 1x 9x 9x       146x 146x 146x 146x 113x 146x 146x 73x 146x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 104x 104x 104x 104x 90x 104x 663x 663x 25x 104x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 16829x 16829x 15738x 15738x 16829x 16829x 16829x 16829x 15635x 15635x 15635x 16829x 16829x 15634x 16829x 104x 104x 104x 16829x 105x 104x 104x       104x 104x 1x 105x 73x 73x 1x 1x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 1x 1x     1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 118x 118x 118x 229x 229x     229x     229x     229x 73x 73x 73x 229x       156x       156x 156x 156x 156x         156x       156x       156x       156x 1x 1x 1x 1x 156x       155x       155x 155x 155x 30x 30x 30x 152x 125x 125x 7x 7x 7x 7x 125x 155x 229x 118x 118x 118x 73x 73x 73x 73x 73x 73x 73x 73x 73x 118x 118x       118x 118x 1x 1x 1x 1x 118x     117x 117x 117x 117x 117x 118x           118x 1x 1x 1x 1x 1x 1x 117x 117x 117x 118x 1x 1x 1x 1x     1x 1x 1x     1x 1x 1x 1x 116x 116x 116x 118x 1x 1x 1x   1x 1x 1x 1x 1x 1x 118x 115x 118x 115x 115x 5x 5x 5x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 11x 11x 11x 11x 115x 115x 115x 104x 104x 104x 79x 32753x 14x 14x 14x 32753x 79x 104x 1x 481x       481x 1x 104x 118x       115x 118x 118x 118x 118x 118x 118x 118x 118x 118x 115x 115x 115x 27x 27x 27x   115x 27x 27x 115x 115x 115x 118x 118x         118x 31x 31x 118x   118x 72x 115x       115x 118x 118x 118x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 118x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 115x 115x 115x 118x 11x 11x 11x 11x 11x 11x 11x 11x 115x 115x 118x 73x 73x 73x 73x 73x 73x 275x 275x 275x 275x 183x 275x 73x 150x 150x 150x 150x 73x 73x 73x       73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 73x 140x 21x 21x 21x 21x 16x 16x 16x 16x 76x 76x 1x 1x 1x 76x 16x 16x 16x 16x 16x 21x 21x 21x 21x 21x                             16x 21x 21x 21x 135x 135x 140x 73x 73x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 9x 9x 131x 140x     131x 140x 73x 73x 73x 126x 126x 7x 126x 73x 73x 73x 73x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x   82x 82x 82x 82x               82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x                   82x 47x 47x       47x 82x 35x 35x 82x 82x 73x 73x 73x 228x 228x 228x 228x 73x 73x 73x 18x 18x 17x 18x 18x 17x 17x 17x 18x 73x 73x 73x 120x 120x 7x 7x 120x 120x 120x 120x 120x 73x 73x 73x 3x 3x 3x 3x 3x 3x 73x 73x 73x 28x 28x 28x 28x 28x 28x 73x 73x 73x 9x 9x 9x 73x 73x 73x 2x 2x 2x 2x 73x 73x 73x 2x 2x 2x 73x 73x 73x 2x 2x 2x 73x 73x 73x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x     6x 6x 6x 6x 6x 6x 6x 6x   6x   6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 73x 73x 73x 73x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 115x 255x 255x 80x 80x 80x 80x 255x 115x 115x 115x 1265x 1265x 1265x 115x 115x 115x 3583x 3583x 3583x 115x 5x                                                             5x     5x     5x     5x     5x 5x 5x 103x 115x       115x       103x 115x 115x       103x 115x 73x 73x 73x 73x       73x 73x 73x 73x 1x 1x 1x 1x 1x 73x 1x 1x 73x 73x 73x 2452x 95x 2452x 95x 95x   2452x 73x 73x 1x 1x 73x 73x 5x 5x 4x 4x       5x 4x 5x 73x 73x 5x 5x 5x 5x 5x 5x 5x 2x 5x 73x 73x 1x 1x 73x 73x     73x 73x             73x 73x       73x 73x 73x 73x 14x 14x 14x  
// objnam.js — Object naming (port of objnam.c)
//
// Provides xname(), doname(), an(), makeplural() for generating
// object descriptions matching C's tty output.
//
// C refs: objnam.c xname_flags(), doname_base(), an(), makeplural()
import { game } from './gstate.js';
import { artifact_name, is_quest_artifact, nartifact_exist } from './artifact.js';
import { artilist } from './artifacts.js';
import { hard_helmet } from './do_wear.js';
import { ALCHEMY_SMOCK, AMULET_CLASS, AMULET_OF_YENDOR, ARMOR_CLASS, BALL_CLASS, BELL_OF_OPENING, BLACK_OPAL, BOULDER, BRASS_LANTERN, BROADSWORD, CHAIN_CLASS, CHEST, COIN_CLASS, CORPSE, CRYSKNIFE, DIAMOND, DILITHIUM_CRYSTAL, EMERALD, FAKE_AMULET_OF_YENDOR, FIGURINE, FLAIL, FLINT, FOOD_CLASS, FOOD_RATION, GEM_CLASS, GEMSTONE, GLAIVE, GLOB_OF_BLACK_PUDDING, GLOB_OF_GRAY_OOZE, HAWAIIAN_SHIRT, HELMET, is_ammo, Is_candle, Is_container, is_corrodeable, is_crackable, Is_dragon_scale_mail, Is_dragon_scales, is_flammable, is_rustprone, KNIFE, LARGE_BOX, LEATHER_GLOVES, LOCK_PICK, MAGIC_HARP, MAGIC_LAMP, MAXOCLASSES, MINERAL, MUMMY_WRAPPING, OIL_LAMP, OPAL, PLATE_MAIL, POT_BOOZE, POT_OIL, POT_WATER, POTION_CLASS, RING_CLASS, ROBE, ROCK, ROCK_CLASS, RUBY, SAPPHIRE, SCR_BLANK_PAPER, SCROLL_CLASS, SHORT_SWORD, SLIME_MOLD, SPBOOK_CLASS, SPE_BLANK_PAPER, STATUE, TIN, TOOL_CLASS, VENOM_CLASS, WAND_CLASS, WEAPON_CLASS, WOODEN_HARP } from './objects.js';
import { CORPSTAT_HISTORIC, Has_contents, NON_PM, P_BOW, P_CROSSBOW, W_AMUL, W_ARMOR, W_BALL, W_CHAIN, W_QUIVER, W_RINGL, W_RINGR, W_SADDLE, W_SWAPWEP, W_TOOL, W_WEP } from './const.js';
import { rn2, rnd } from './rng.js';
import { mksobj, mkobj, bless, curse, weight, place_object, obj_extract_self } from './mkobj.js';
import { begin_burn } from './light.js';
import { plur, s_suffix } from './hacklib.js';
import { mons, M2_PNAME, G_UNIQ } from './monsters.js';
import { carried, currency, let_to_name, not_fully_identified, observe_object } from './invent.js';
import { get_cost_of_shop_item, is_unpaid, shk_your, unpaid_cost_fn } from './shk.js';
import { type_is_pname } from './do_name.js';
import { Blind, Role_if, URIGHTY } from './macros.js';
import { is_missile, is_weptool } from './mondata.js';
import { PM_ARCHEOLOGIST, PM_CLERIC, PM_SAMURAI } from './monsters.js';
import { def_oc_syms } from './symbols.js';
// C ref: objnam.c:105 — Japanese_items[] maps weapon types to Samurai names
const Japanese_items = [
    [SHORT_SWORD, 'wakizashi'],
    [BROADSWORD, 'ninja-to'],
    [FLAIL, 'nunchaku'],
    [GLAIVE, 'naginata'],
    [LOCK_PICK, 'osaku'],
    [WOODEN_HARP, 'koto'],
    [MAGIC_HARP, 'magic koto'],
    [KNIFE, 'shito'],
    [PLATE_MAIL, 'tanko'],
    [HELMET, 'kabuto'],
    [LEATHER_GLOVES, 'yugake'],
    [FOOD_RATION, 'gunyoki'],
    [POT_BOOZE, 'sake'],
];
// C ref: objnam.c:5420 Japanese_item_name
function Japanese_item_name(otyp, ordinaryname) {
    for (const [item, name] of Japanese_items) {
        if (otyp === item) return name;
    }
    return ordinaryname;
}
// ── Vowel set for article selection ──
const vowels = 'aeiouAEIOU';
function current_descr(od) {
    if (!od) return null;
    const idx = Number.isInteger(od.oc_descr_idx) ? od.oc_descr_idx : null;
    if (idx != null && game.objects[idx]?.oc_descr) return game.objects[idx].oc_descr;
    return od.oc_descr || null;
}
function GemStone(otyp, od) {
    if (otyp === FLINT) return true;
    if ((od?.oc_material ?? 0) !== GEMSTONE) return false;
    return otyp !== DILITHIUM_CRYSTAL
        && otyp !== RUBY
        && otyp !== DIAMOND
        && otyp !== SAPPHIRE
        && otyp !== BLACK_OPAL
        && otyp !== EMERALD
        && otyp !== OPAL;
}
// ── Class names for inventory headers ──
// C ref: invent.c names[] array
export const CLASS_NAMES = [
    '', 'Illegal objects', 'Weapons', 'Armor', 'Rings', 'Amulets', 'Tools',
    'Comestibles', 'Potions', 'Scrolls', 'Spellbooks', 'Wands', 'Coins',
    'Gems/Stones', 'Boulders/Statues', 'Iron balls', 'Chains', 'Venoms',
];
// ── just_an: select "" / "a " / "an " ──
// C ref: objnam.c just_an()
function just_an(str) {
    if (!str || !str.length) return 'a ';
    const c0 = str[0].toLowerCase();
    // Single letter
    if (str.length === 1 || str[1] === ' ') {
        return 'aefhilmnosx'.includes(c0) ? 'an ' : 'a ';
    }
    // "the " / "molten lava" / "iron bars" / "ice" → no article
    if (str.toLowerCase().startsWith('the ')
        || str.toLowerCase() === 'molten lava'
        || str.toLowerCase() === 'iron bars'
        || str.toLowerCase() === 'ice') {
        return '';
    }
    // Vowel with exceptions for long-u sounds
    if (vowels.includes(c0)
        && !str.toLowerCase().startsWith('one')
        && !str.toLowerCase().startsWith('eu')
        && !str.toLowerCase().startsWith('uke')
        && !str.toLowerCase().startsWith('unicorn')
        && !str.toLowerCase().startsWith('uranium')
        && !str.toLowerCase().startsWith('useful')) {
        return 'an ';
    }
    // "x" + consonant → "an"
    if (c0 === 'x' && str.length > 1 && !vowels.includes(str[1].toLowerCase())) {
        return 'an ';
    }
    return 'a ';
}
// ── an: prepend "a " or "an " ──
// C ref: objnam.c an()
export function an(str) {
    return just_an(str) + str;
}
// ── makeplural: convert singular to plural ──
// C ref: objnam.c makeplural()
// Simplified version covering common NetHack object names.
export function makeplural(str) {
    if (!str || !str.length) return 's';
    // Handle "pair of X" → "pairs of X"
    if (str.startsWith('pair of ')) return str; // C doesn't pluralize "pair of"
    // Handle compound "X of Y" → pluralize X only
    const ofIdx = str.indexOf(' of ');
    if (ofIdx > 0) {
        return makeplural(str.substring(0, ofIdx)) + str.substring(ofIdx);
    }
    const len = str.length;
    // C ref: objnam.c:2692-2697 — words that are the same singular and plural
    const unchangedPlurals = [
        'bison', 'deer', 'elk', 'fish', 'fowl', 'tuna', 'yaki', 'krill',
        'manes', 'moose', 'ninja', 'sheep', 'ronin', 'roshi', 'shito',
        'tengu', 'ki-rin', 'Nazgul', 'gunyoki', 'piranha', 'samurai',
        'shuriken', 'haggis', 'Bordeaux',
    ];
    const lower = str.toLowerCase();
    // C ref: objnam.c one_off[] irregular pairs.
    const irregularPairs = [
        ['child', 'children'],
        ['cubus', 'cubi'],
        ['culus', 'culi'],
        ['cyclops', 'cyclopes'],
        ['djinni', 'djinn'],
        ['erinys', 'erinyes'],
        ['foot', 'feet'],
        ['fungus', 'fungi'],
        ['goose', 'geese'],
        ['knife', 'knives'],
        ['labrum', 'labra'],
        ['louse', 'lice'],
        ['mouse', 'mice'],
        ['mumak', 'mumakil'],
        ['nemesis', 'nemeses'],
        ['ovum', 'ova'],
        ['ox', 'oxen'],
        ['passerby', 'passersby'],
        ['rtex', 'rtices'],
        ['serum', 'sera'],
        ['staff', 'staves'],
        ['tooth', 'teeth'],
    ];
    for (const [sing, plurForm] of irregularPairs) {
        if (lower === sing) {
            return str[0] === str[0].toUpperCase()
                ? (plurForm.charAt(0).toUpperCase() + plurForm.slice(1))
                : plurForm;
        }
        if (lower.endsWith(' ' + sing)) {
            return str.slice(0, -sing.length) + plurForm;
        }
    }
    for (const w of unchangedPlurals) {
        if (lower === w || lower.endsWith(' ' + w))
            return str;
    }
    // C ref: objnam.c:2914-2916 — "ya" (Japanese arrow) doesn't pluralize
    if ((len === 2 && lower === 'ya')
        || (len >= 3 && lower.endsWith(' ya')))
        return str;
    // C ref: objnam.c one_off[] table — irregular plurals
    const irregulars = [
        ['foot', 'feet'], ['goose', 'geese'], ['tooth', 'teeth'],
        ['louse', 'lice'], ['mouse', 'mice'],
        ['child', 'children'], ['ox', 'oxen'],
    ];
    for (const [sing, plur] of irregulars) {
        if (lower === sing || (lower.length > sing.length && lower.endsWith(sing))) {
            return str.substring(0, len - sing.length) + plur;
        }
    }
    const last = str[len - 1].toLowerCase();
    const last2 = len >= 2 ? str.substring(len - 2).toLowerCase() : '';
    // man -> men (caveman -> cavemen)
    if (len >= 3 && str.substring(len - 3).toLowerCase() === 'man') {
        return str.substring(0, len - 2) + 'en';
    }
    // f -> ves (wolf -> wolves, knife -> knives, half -> halves)
    if (last === 'f') {
        const prev = len >= 2 ? str[len - 2].toLowerCase() : '';
        if ('lr'.includes(prev) || vowels.includes(prev)) {
            // Exception: nerf
            if (len >= 3 && str.substring(len - 3).toLowerCase() === 'erf') {
                return str + 's';
            }
            return str.substring(0, len - 1) + 'ves';
        }
    }
    // fe -> ves (knife -> knives)
    if (last2 === 'fe') {
        return str.substring(0, len - 2) + 'ves';
    }
    // us -> i (fungus -> fungi)
    if (last2 === 'us' && len > 3) {
        return str.substring(0, len - 2) + 'i';
    }
    // sis -> ses (nemesis -> nemeses)
    if (len >= 3 && str.substring(len - 3).toLowerCase() === 'sis') {
        return str.substring(0, len - 2) + 'es';
    }
    // z, x, s, ch, sh → add "es"
    if ('zxs'.includes(last)
        || (last === 'h' && len >= 2 && 'cs'.includes(str[len - 2].toLowerCase()))) {
        return str + 'es';
    }
    // y → ies (when preceded by consonant)
    if (last === 'y' && len >= 2 && !vowels.includes(str[len - 2].toLowerCase())) {
        return str.substring(0, len - 1) + 'ies';
    }
    // Default: add 's'
    return str + 's';
}
// C ref: read.c:190 hawaiian_motif — deterministic shirt design
const hawaiian_motifs = [
    'flamingo', 'parrot', 'toucan', 'bird of paradise',
    'sea turtle', 'tropical fish', 'jellyfish', 'giant eel', 'water nymph',
    'plumeria', 'orchid', 'hibiscus flower', 'palm tree',
    'hula dancer', 'sailboat', 'ukulele',
];
function hawaiian_motif(shirt) {
    // C ref: read.c:217 — motif = o_id ^ ubirthday
    const ubirthday = game.u?.ubirthday ?? 0;
    const motif = ((shirt.o_id ?? 0) ^ ubirthday) >>> 0;
    return hawaiian_motifs[motif % hawaiian_motifs.length];
}
// ── xname: base object name ──
// C ref: objnam.c xname_flags()
// Returns the base name without articles, quantity, or BUC.
export function xname(obj) {
    const od = game.objects[obj.otyp];
    if (!od) return 'strange object';
    if (!Blind() && !game?.distantname) observe_object(obj);
    // C ref: objnam.c:xname_flags() — priests know BUC status.
    if (Role_if(PM_CLERIC)) {
        obj.bknown = 1;
    }
    const oclass = obj.oclass ?? od.oc_class;
    let nn = od.oc_name; // actual name (always known for starting items)
    let descr = current_descr(od);
    // C ref: objnam.c:210 — Samurai use Japanese weapon/armor names
    if (Role_if(PM_SAMURAI)) {
        nn = Japanese_item_name(obj.otyp, nn);
        if (obj.otyp === WOODEN_HARP || obj.otyp === MAGIC_HARP)
            descr = 'koto';
    }
    const un = od.oc_uname;
    const nameKnown = !!od.oc_name_known;
    const dknown = obj.dknown ?? false;
    const bknown = obj.bknown ?? false;
    const quan = obj.quan ?? 1;
    const pluralize = quan > 1;
    // C ref: objnam.c:660-664 — fully-identified artifacts skip to nameit
    // C: find_artifact(obj) when oartifact && dknown
    if (obj.oartifact && dknown) {
        // C: find_artifact — marks artifact as known (existing)
    }
    if (obj_is_pname(obj)) {
        // C ref: goto nameit — skip switch, use artifact name directly
        let oname = obj.oextra?.oname || '';
        if (oname.startsWith('The '))
            oname = 't' + oname.substring(1);
        return pluralize ? makeplural(oname) : oname;
    }
    let buf = '';
    switch (oclass) {
    case WEAPON_CLASS:
    case VENOM_CLASS:
    case TOOL_CLASS: {
        // C: is_poisonable(obj) && obj.opoisoned → "poisoned "
        if (obj.opoisoned) buf += 'poisoned ';
        // C ref: objnam.c:692 — lenses prefix
        if (nn === 'lenses') buf += 'pair of ';
        // C ref: objnam.c:699-706 — dknown/nn/un/dn selection
        const dn = descr || nn;
        if (!dknown) {
            buf += dn;
        } else if (nameKnown) {
            buf += nn;
        } else if (un) {
            // C: xcalled(buf, dn, un) → "dn called un"
            buf += dn + ' called ' + obj.uname;
        } else {
            buf += dn;
        }
        // C ref: figurine of X, wet towel
        if (obj.otyp === FIGURINE && obj.corpsenm >= 0) {
            const pm = mons[obj.corpsenm];
            if (pm) buf += ' of ' + (pm.mname || 'monster');
        }
        break;
    }
    case ARMOR_CLASS:
        // C ref: objnam.c:722-745 — dragon scales, boots/gloves prefix, shield prefix
        if (od.oc_armcat === 4 || od.oc_armcat === 3) { // ARM_BOOTS=4, ARM_GLOVES=3
            buf += 'pair of ';
        }
        // C ref: objnam.c:738-743 — nn/un/dn selection (same as WEAPON)
        if (nameKnown) {
            buf += nn;
        } else if (un) {
            // C: xcalled(buf, armor_simple_name(obj), un)
            const simpleName = descr || nn;
            buf += `${simpleName} called ${un}`;
        } else {
            buf += descr || nn;
        }
        // C ref: objnam.c:971,989-992 — Hawaiian shirt motif (gameover only)
        if (obj.otyp === HAWAIIAN_SHIRT && game.program_state?.gameover && obj.o_id) {
            buf += ` with ${an(hawaiian_motif(obj))} motif`;
        }
        break;
    case POTION_CLASS:
        if (dknown && obj.odiluted) {
            buf += 'diluted ';
        }
        if (nameKnown || un || !dknown) {
            buf += 'potion';
            if (!dknown) break;
            if (nameKnown) {
                buf += ' of ';
                if (obj.otyp === POT_WATER && bknown && (obj.blessed || obj.cursed)) {
                    buf += obj.blessed ? 'holy ' : 'unholy ';
                }
                buf += nn;
            } else {
                buf += ` called ${un}`;
            }
        } else {
            buf += `${descr || nn} potion`;
        }
        break;
    case SCROLL_CLASS:
        buf += 'scroll';
        if (!dknown) {
            break;
        }
        if (nameKnown && nn) {
            buf += ' of ' + nn;
        } else if (un) {
            buf += ` called ${un}`;
        } else if (od.oc_magic) {
            buf += ` labeled ${descr || nn}`;
        } else {
            buf = `${descr || nn} scroll`;
        }
        break;
    case SPBOOK_CLASS:
        if (!dknown) {
            buf += 'spellbook';
        } else if (nameKnown && nn) {
            buf += 'spellbook of ' + nn;
        } else if (un) {
            buf += `spellbook called ${un}`;
        } else {
            buf += `${descr || nn} spellbook`;
        }
        break;
    case WAND_CLASS:
        if (!dknown) {
            buf += 'wand';
        } else if (nameKnown && nn) {
            buf += 'wand of ' + nn;
        } else if (un) {
            buf += `wand called ${un}`;
        } else {
            buf += `${descr || nn} wand`;
        }
        break;
    case RING_CLASS:
        if (!dknown) {
            buf += 'ring';
            break;
        }
        if (!nameKnown && descr) {
            buf += `${descr} ring`;
            break;
        }
        buf += 'ring of ' + nn;
        break;
    case AMULET_CLASS:
        // C ref: objects.h has real Amulet name==description ("Amulet of Yendor").
        // It should not collapse to plain "amulet" in xname().
        if (obj.otyp === AMULET_OF_YENDOR) {
            buf += 'Amulet of Yendor';
            break;
        }
        if (!dknown) {
            buf += 'amulet';
            break;
        }
        if (obj.otyp === AMULET_OF_YENDOR || obj.otyp === FAKE_AMULET_OF_YENDOR) {
            const dn = descr || nn || 'amulet';
            const actualn = nn || dn;
            buf += obj.known ? actualn : dn;
            break;
        }
        if (nameKnown && nn) {
            buf += nn;
            break;
        }
        if (obj.uname) {
            buf += `amulet called ${obj.uname}`;
            break;
        }
        buf += `${descr || nn || 'amulet'} amulet`;
        break;
    case FOOD_CLASS:
        buf += nn;
        break;
    case COIN_CLASS:
        buf += 'gold piece';
        break;
    case ROCK_CLASS: {
        const actualn = nn || 'rock';
        const omndx = Number.isInteger(obj.corpsenm) ? obj.corpsenm : NON_PM;
        if (obj.otyp === STATUE && omndx !== NON_PM && mons[omndx]) {
            const pm = mons[omndx];
            const pmname = pm.mname || 'monster';
            const historic = Role_if(PM_ARCHEOLOGIST) && !!((obj.spe || 0) & CORPSTAT_HISTORIC);
            const article = type_is_pname(pm) ? ''
                : (the_unique_pm(pm) ? 'the ' : just_an(pmname));
            buf += `${historic ? 'historic ' : ''}${actualn} of ${article}${pmname}`;
        } else if (obj.otyp === BOULDER && obj.next_boulder === 1) {
            buf += `next ${actualn}`;
            obj.next_boulder = 0;
        } else {
            buf += actualn;
        }
        break;
    }
    case GEM_CLASS: {
        // C ref: objnam.c:914-930 — gem naming depends on dknown/nameKnown
        const rock = (od.oc_material === MINERAL) ? 'stone' : 'gem';
        if (!dknown) {
            buf += rock;
        } else if (!nameKnown) {
            if (un) {
                buf += `${rock} called ${un}`;
            } else {
                buf += `${descr || nn} ${rock}`;
            }
        } else {
            buf += nn;
            if (GemStone(obj.otyp, od)) buf += ' stone';
        }
        break;
    }
    default:
        buf += nn || 'object';
        break;
    }
    // C ref: eat.c tin_details() from objnam.c xname() for known tins.
    if (obj.otyp === TIN && dknown) {
        const mnum = Number.isInteger(obj.corpsenm) ? obj.corpsenm : NON_PM;
        if (mnum === NON_PM) {
            if ((obj.spe | 0) === 1) {
                buf += ' of spinach';
            } else {
                buf = 'empty tin';
            }
        } else {
            const mname = mons[mnum]?.mname || 'meat';
            // C ref: eat.c:1442 — cknown + spe<0 → rotten/homemade prefix
            if ((obj.cknown || game.iflags?.override_ID) && (obj.spe ?? 0) < 0) {
                // C ref: tin_variety returns ROTTEN_TIN (0) or HOMEMADE_TIN (1)
                // based on obj.spe. spe == -1 → ROTTEN_TIN.
                const rotten = (obj.spe === -1); // simplified
                if (rotten) buf = `rotten ${buf}`;
            }
            buf += ` of ${mname} meat`;
        }
    }
    // C ref: objnam.c:998-1008 — append "named X" for named objects.
    // C appends for ALL has_oname objects, but JS restricts to artifacts
    // because some JS code paths set oextra.oname where C doesn't,
    // which changes message lengths and cascades to RNG divergence.
    if (obj.oartifact && obj.oextra?.oname && dknown && !obj_is_pname(obj)) {
        let oname = obj.oextra.oname;
        // C ref: objnam.c:1007-1008 — downcase "The" for artifact names
        if (oname.startsWith('The '))
            oname = 't' + oname.substring(1);
        buf += ` named ${oname}`;
    }
    // Pluralize if quantity > 1
    if (pluralize) {
        buf = makeplural(buf);
    }
    return buf;
}
// ── doname: full object description ──
// C ref: objnam.c doname_base()
// Returns complete description with articles, BUC, enchantment, and status.
// Order: article/quantity, empty, BUC, erosion, enchantment, name, wear/wield
export function doname(obj) {
    const od = game.objects[obj.otyp];
    if (!od) return 'strange object';
    let bp = xname(obj);
    const oclass = obj.oclass ?? od.oc_class;
    const donameClass = is_weptool(obj) ? WEAPON_CLASS : oclass;
    const known = obj.known ?? false;
    const dknown = obj.dknown ?? false;
    const bknown = obj.bknown ?? false;
    const cknown = obj.cknown ?? false;
    const quan = obj.quan ?? 1;
    const overrideId = game?.iflags?.override_ID ? true : false;
    const theUniqueObj = (() => {
        const knownOrOverride = known || overrideId;
        if (!dknown && !overrideId) return false;
        if (obj.otyp === FAKE_AMULET_OF_YENDOR && !knownOrOverride) return true;
        return !!(od.unique && (knownOrOverride || obj.otyp === AMULET_OF_YENDOR));
    })();
    let prefix = '';
    // ── 1. Quantity or article ──
    // C ref: doname_base lines 1282-1299
    if (quan > 1) {
        prefix = `${quan} `;
    } else if (obj.otyp === CORPSE) {
        prefix = '';
    } else if (obj_is_pname(obj) || theUniqueObj) {
        if (bp.toLowerCase().startsWith('the ')) {
            bp = bp.slice(4);
        }
        prefix = 'the ';
    } else {
        prefix = 'a ';
    }
    // ── 2. Container "empty" ──
    // C ref: doname_base lines 1301-1316
    // Goes BEFORE BUC: "an empty uncursed sack"
    if (cknown && Is_container(obj) && !obj.cobj) {
        prefix += 'empty ';
    }
    // ── 3. BUC status ──
    // C ref: doname_base lines 1318-1349
    // flags.implicit_uncursed defaults to true
    const hideBucForKnownHolyWater =
        obj.otyp === POT_WATER
        && !!game.objects[POT_WATER]?.oc_name_known
        && !!(obj.cursed || obj.blessed);
    if (bknown && oclass !== COIN_CLASS && !hideBucForKnownHolyWater) {
        if (obj.cursed) {
            prefix += 'cursed ';
        } else if (obj.blessed) {
            prefix += 'blessed ';
        } else {
            // Show "uncursed" unless implicit (known + charged + not armor/ring)
            const oc_charged = od.oc_charged ?? 0;
            const implicit = known && oc_charged
                && oclass !== ARMOR_CLASS && oclass !== RING_CLASS;
            if (!implicit && !Role_if(PM_CLERIC)) {
                prefix += 'uncursed ';
            }
        }
    }
    // ── 4. Lock state for boxes ──
    // C ref: doname_base:1358-1368 — lknown && Is_box(obj) → "locked/unlocked/broken"
    if (obj.lknown && (obj.otyp === LARGE_BOX || obj.otyp === CHEST)) {
        if (obj.obroken) {
            prefix += 'broken ';
        } else if (obj.olocked) {
            prefix += 'locked ';
        } else {
            prefix += 'unlocked ';
        }
    }
    // C ref: doname_base:1356-1357 — trapped box prefix
    if ((obj.otyp === LARGE_BOX || obj.otyp === CHEST)
        && obj.otrapped && obj.tknown && dknown) {
        prefix += 'trapped ';
    }
    // C ref: doname_base:1370-1371 — greased prefix
    if (obj.greased) {
        prefix += 'greased ';
    }
    // ── 4b. Container contents — C ref: doname_base lines 1373-1380 ──
    if (cknown && Has_contents(obj)) {
        let itemcount = 0;
        for (let o = obj.cobj; o; o = o.nobj) itemcount++;
        bp += ` containing ${itemcount} item${itemcount !== 1 ? 's' : ''}`;
    }
    // ── 5. Wear status appended to bp ──
    // C ref: doname_base lines 1382-1646 (switch on oclass)
    // Armor wear status goes BEFORE enchantment in the prefix build
    // because armor's switch case falls through to weapon for enchantment.
    const wornmask = obj.owornmask ?? 0;
    if (oclass === AMULET_CLASS && (wornmask & W_AMUL)) {
        bp += ' (being worn)';
    }
    if (oclass === ARMOR_CLASS && (wornmask & W_ARMOR)) {
        bp += ' (being worn)';
    }
    // ── 5. Enchantment ── (weapon/armor via fall-through in C)
    // C ref: doname_base lines 1418-1424
    if (donameClass === ARMOR_CLASS || donameClass === WEAPON_CLASS) {
        // C ref: objnam.c:1143 add_erosion_words
        {
            const iscrys = obj.otyp === CRYSKNIFE;
            const rknown = obj.rknown ?? false;
            const is_damageable = (donameClass === WEAPON_CLASS
                || donameClass === ARMOR_CLASS
                || oclass === BALL_CLASS || oclass === CHAIN_CLASS
                || is_weptool(obj));
            if (is_damageable || iscrys) {
                if (obj.oeroded && !iscrys) {
                    if (obj.oeroded === 2) prefix += 'very ';
                    else if (obj.oeroded === 3) prefix += 'thoroughly ';
                    prefix += is_rustprone(obj) ? 'rusty '
                        : is_crackable(obj) ? 'cracked '
                        : 'burnt ';
                }
                if (obj.oeroded2 && !iscrys) {
                    if (obj.oeroded2 === 2) prefix += 'very ';
                    else if (obj.oeroded2 === 3) prefix += 'thoroughly ';
                    prefix += is_corrodeable(obj) ? 'corroded ' : 'rotted ';
                }
                if (rknown && obj.oerodeproof) {
                    prefix += iscrys ? 'fixed '
                        : is_rustprone(obj) ? 'rustproof '
                        : is_corrodeable(obj) ? 'corrodeproof '
                        : is_flammable(obj) ? 'fireproof '
                        : is_crackable(obj) ? 'tempered '
                        : '';
                }
            }
        }
        if (known) {
            const spe = obj.spe ?? 0;
            prefix += `${spe >= 0 ? '+' : ''}${spe} `;
        }
    }
    // Ring enchantment (separate from weapon/armor)
    if (oclass === RING_CLASS && known && od.oc_charged) {
        const spe = obj.spe ?? 0;
        prefix += `${spe >= 0 ? '+' : ''}${spe} `;
    }
    // C ref: doname_base lines 1351-1368 — "named Foo" for named objects
    // For artifacts, this is now handled in xname(). doname_base no longer
    // needs to add it since xname includes "named" for artifacts.
    // C ref: doname_base FOOD_CLASS/CORPSE handling (objnam.c:1507-1520)
    if (oclass === FOOD_CLASS && obj.oeaten) {
        prefix += 'partly eaten ';
    }
    if (obj.otyp === CORPSE) {
        const CXN_ARTICLE = 8;
        const CXN_NOCORPSE = 16;
        const cxarg = ((quan !== 1) ? 0 : CXN_ARTICLE) | CXN_NOCORPSE;
        prefix = `${corpse_xname(obj, prefix, cxarg)} `;
    }
    // ── 6. Tool wear status + lit status ──
    // C ref: objnam.c:1427 — W_TOOL | W_SADDLE (blindfold or saddle)
    if (donameClass === TOOL_CLASS && (wornmask & (W_TOOL | W_SADDLE))) {
        bp += ' (being worn)';
    }
    // C ref: objnam.c:1457-1477 — candle "partly used" prefix
    if (Is_candle(obj) && obj.age != null) {
        // C compares obj->age to full burn time; if less, add "partly used"
        const fullBurn = game.objects[obj.otyp]?.oc_cost ?? 0;
        if (fullBurn > 0 && obj.age < fullBurn)
            prefix += 'partly used ';
    }
    if (donameClass === TOOL_CLASS && obj.lamplit) {
        bp += ' (lit)';
    }
    // C ref: objnam.c:1540-1545 — ball/chain wear status
    if (oclass === BALL_CLASS && (wornmask & W_BALL)) {
        bp += ' (chained to you)';
    }
    if (oclass === CHAIN_CLASS && (wornmask & W_CHAIN)) {
        bp += ' (attached to you)';
    }
    // ── 7. Weapon wield/ready status ──
    // C ref: doname_base lines 1561-1621
    if (wornmask & W_WEP) {
        const twoweap_primary = (obj === game.u?.uwep && game.u?.twoweap);
        // C ref: objnam.c:1570-1576 — non-weapons and ammo/missiles show "(wielded)"
        // instead of "(weapon in hand)" unless actively dual-wielded.
        if ((quan !== 1
             || ((oclass === WEAPON_CLASS)
                 ? (is_ammo(obj) || is_missile(obj))
                 : !is_weptool(obj)))
            && !twoweap_primary) {
            bp += ' (wielded)';
        } else {
            // C: bimanual wielded weapons use "weapon in hands".
            const bothHands = !!(game.objects[obj.otyp]?.oc_bimanual);
            // C ref: objnam.c:1583 — handedness: URIGHTY ? "right" : "left"
            const handSide = URIGHTY() ? 'right' : 'left';
            bp += bothHands ? ' (weapon in hands)' : ` (weapon in ${handSide} hand)`;
        }
    }
    if (wornmask & W_SWAPWEP) {
        // C ref: objnam.c:1613-1620 — twoweap shows "wielded in off-hand"
        if (game.u?.twoweap) {
            const offHand = URIGHTY() ? 'left' : 'right';
            bp += ` (wielded in ${offHand} hand)`;
        } else {
            bp += ` (alternate weapon${plur(quan)}; not wielded)`;
        }
    }
    if (wornmask & W_QUIVER) {
        let qtyp = 3;
        switch (oclass) {
        case WEAPON_CLASS:
            qtyp = !is_ammo(obj) ? 3
                : ((game.objects[obj.otyp]?.oc_skill || 0) !== -P_BOW) ? 2
                    : 1;
            break;
        case RING_CLASS:
        case AMULET_CLASS:
        case WAND_CLASS:
        case COIN_CLASS:
        case GEM_CLASS:
            qtyp = 2;
            break;
        default:
            qtyp = 3;
            break;
        }
        bp += ` (${qtyp === 1 ? 'in quiver' : qtyp === 2 ? 'in quiver pouch' : 'at the ready'})`;
    }
    // ── 8. Ring hand status ──
    if (wornmask & W_RINGL) {
        bp += ' (on left hand)';
    }
    if (wornmask & W_RINGR) {
        bp += ' (on right hand)';
    }
    // C ref: objnam.c:1489 — lit potion of oil
    if (oclass === POTION_CLASS && obj.otyp === POT_OIL && obj.lamplit) {
        bp += ' (lit)';
    }
    // Charged item display for wands/tools: "(recharge:spe)".
    if ((donameClass === WAND_CLASS || donameClass === TOOL_CLASS)
        && known && (od.oc_charged ?? 0) && Number.isInteger(obj.spe)) {
        const rech = Number.isInteger(obj.recharged) ? obj.recharged : 0;
        bp += ` (${rech}:${obj.spe})`;
    }
    // ── 9. Shop price suffix ──
    // C ref: doname_base lines 1650-1689 — append "(unpaid, N zorkmids)"
    // or "(for sale, N zorkmids)" for shop items.
    if (!game.iflags?.suppress_price && !game.program_state?.restoring) {
        if (is_unpaid(obj)) {
            const price = unpaid_cost_fn(obj);
            if (price > 0) {
                bp += ` (${obj.unpaid ? 'unpaid' : 'contents'}, ${price} ${currency(price)})`;
            }
        } else if (game._doname_with_price) {
            // Floor items in shops — get_cost_of_shop_item
            const priceResult = get_cost_of_shop_item(obj);
            if (priceResult > 0) {
                bp += ` (for sale, ${priceResult} ${currency(priceResult)})`;
            } else if (priceResult === -1) {
                bp += ' (no charge)';
            }
        }
    }
    // ── 10. Adjust article ("a " → "an " if needed) ──
    // C ref: doname_base lines 1684-1691
    if (prefix.startsWith('a ')) {
        const rest = prefix.substring(2) + bp;
        const article = just_an(rest);
        prefix = article + prefix.substring(2);
    }
    return prefix + bp;
}
// C ref: objnam.c doname_with_price() — doname with shop pricing
export function doname_with_price(obj) {
    game._doname_with_price = true;
    try { return doname(obj); }
    finally { game._doname_with_price = false; }
}
// ── let_to_name: class letter/number to display name ──
// C ref: invent.c let_to_name()
function normalizeWishText(text) {
    return String(text || '').replace(/\s+/g, ' ').trim().toLowerCase();
}
function exactWishName(od) {
    return od?.oc_name ? od.oc_name.toLowerCase() : null;
}
// C ref: objnam.c:3241 wishymatch — fuzzy matching with "of" inversion
function wishymatch(name, target) {
    const n = normalizeWishText(name);
    const t = normalizeWishText(target);
    if (n === t) return true;
    // C ref: objnam.c:3257-3271 — "foo of bar" ↔ "bar foo" inversion
    const nOf = n.indexOf(' of ');
    const tOf = t.indexOf(' of ');
    if (nOf >= 0 && tOf < 0) {
        // "ring of teleport control" → "teleport control ring"
        const inverted = n.slice(nOf + 4) + ' ' + n.slice(0, nOf);
        if (inverted === t) return true;
    } else if (tOf >= 0 && nOf < 0) {
        const inverted = t.slice(tOf + 4) + ' ' + t.slice(0, tOf);
        if (n === inverted) return true;
    }
    return false;
}
function inferWishClass(name) {
    const s = normalizeWishText(name);
    // C ref: objnam.c:4546-4551 — single object-class symbol wish
    // (for example "?" for scroll class).
    if (s.length === 1) {
        for (let i = 1; i < def_oc_syms.length; i++) {
            if (def_oc_syms[i]?.sym !== s) continue;
            // Match C guard: i > ILLOBJ_CLASS and venom only in wizard mode.
            if (i > 1 && i < MAXOCLASSES && (i !== VENOM_CLASS || game.wizard))
                return i;
            break;
        }
    }
    if (s.startsWith('amulet') || s.startsWith('amulets')) return AMULET_CLASS;
    if (s.startsWith('ring') || s.startsWith('rings')) return RING_CLASS;
    if (s.startsWith('potion') || s.startsWith('potions')) return POTION_CLASS;
    if (s.startsWith('scroll') || s.startsWith('scrolls')) return SCROLL_CLASS;
    if (s.startsWith('spellbook') || s.startsWith('spellbooks')
        || s.startsWith('spell book') || s.startsWith('spell books')) return SPBOOK_CLASS;
    if (s.startsWith('wand') || s.startsWith('wands')) return WAND_CLASS;
    return 0;
}
// C ref: objnam.c:4565-4578 — strip class prefix like "ring of " from wish text
// C's readobjnam detects "<class> of <name>" and extracts <name> for matching.
const wishClassPrefixes = [
    { prefix: 'wand of ', cls: WAND_CLASS },
    { prefix: 'wands of ', cls: WAND_CLASS },
    { prefix: 'ring of ', cls: RING_CLASS },
    { prefix: 'rings of ', cls: RING_CLASS },
    { prefix: 'potion of ', cls: POTION_CLASS },
    { prefix: 'potions of ', cls: POTION_CLASS },
    { prefix: 'scroll of ', cls: SCROLL_CLASS },
    { prefix: 'scrolls of ', cls: SCROLL_CLASS },
    { prefix: 'spellbook of ', cls: SPBOOK_CLASS },
    { prefix: 'spellbooks of ', cls: SPBOOK_CLASS },
    { prefix: 'spell book of ', cls: SPBOOK_CLASS },
    { prefix: 'spell books of ', cls: SPBOOK_CLASS },
];
function wishRngPrepassName(name) {
    const s = normalizeWishText(name);
    if (s.endsWith('dragon scale mail')) return 'scale mail';
    if (s.endsWith('dragon scales')) return 'scales';
    // C ref: objnam.c:4569-4574 — strip "<class> of " prefix for matching
    for (const { prefix } of wishClassPrefixes) {
        if (s.startsWith(prefix)) return s.slice(prefix.length);
    }
    return s;
}
function rnd_otyp_by_namedesc(name, oclass = 0, xtraProb = 0) {
    const valid = [];
    let maxprob = 0;
    const want = normalizeWishText(name);
    const checkOf = !want.includes(' of ');
    const minGlob = GLOB_OF_GRAY_OOZE;
    const maxGlob = GLOB_OF_BLACK_PUDDING;
    const lo = oclass ? (game.bases?.[oclass] ?? 0) : MAXOCLASSES;
    const hi = oclass ? ((game.bases?.[oclass + 1] ?? 0) - 1) : (game.objects.length - 1);
    for (let i = lo; i <= hi; i++) {
        const od = game.objects[i];
        if (!od?.oc_name) continue;
        const zn = exactWishName(od);
        const descr = current_descr(od);
        const ofName = zn?.includes(' of ') ? zn.split(' of ')[1] : null;
        const ofDescr = descr?.toLowerCase().includes(' of ') ? descr.toLowerCase().split(' of ')[1] : null;
        if (wishymatch(want, zn)
            || (checkOf
                && i !== BELL_OF_OPENING
                && (i < minGlob || i > maxGlob)
                && ofName && wishymatch(want, ofName))
            || (descr && wishymatch(want, descr))
            || (checkOf
                && ofDescr && wishymatch(want, ofDescr))
            || (od.oc_uname && wishymatch(want, od.oc_uname))) {
            valid.push(i);
            maxprob += (od.oc_prob || 0) + xtraProb;
        }
    }
    if (valid.length > 0 && maxprob > 0) {
        let prob = rn2(maxprob);
        for (let i = 0; i < valid.length - 1; i++) {
            prob -= (game.objects[valid[i]].oc_prob || 0) + xtraProb;
            if (prob < 0) return valid[i];
        }
        return valid[valid.length - 1];
    }
    return -1;
}
// C ref: objnam.c:3530 shiny_obj()
export function shiny_obj(oclass) {
    return rnd_otyp_by_namedesc('shiny', oclass, 0);
}
function parseWishPrefixes(bp) {
    let s = normalizeWishText(bp);
    const out = {
        blessed: false,
        cursed: false,
        uncursed: false,
        unlabeled: false,
        ispoisoned: false,
        spe: null,
        rechrg: null,
        count: 1,
        name: '',
    };
    // C ref: objnam.c:4176 readobjnam_parse_charges — strip "(N)" or
    // "(N:M)" or "(lit)" suffix from the name before further parsing.
    // Match LAST '(' in the string; C uses strrchr.  If the suffix is
    // well-formed, remove it (C also handles malformed '(' by leaving
    // text intact but clearing spe/rechrg — we do the same).
    {
        const m = s.match(/\s*\(([^()]*)\)\s*$/);
        if (m) {
            const inside = m[1];
            if (/^lit$/i.test(inside)) {
                out.islit = true;
                s = s.slice(0, m.index).trimEnd();
            } else {
                const cm = inside.match(/^\s*(-?\d+)(?::(-?\d+))?\s*$/);
                if (cm) {
                    if (cm[2] != null) {
                        out.rechrg = parseInt(cm[1], 10);
                        out.spe = parseInt(cm[2], 10);
                    } else {
                        out.spe = parseInt(cm[1], 10);
                    }
                    s = s.slice(0, m.index).trimEnd();
                }
            }
        }
    }
    let changed = true;
    while (changed) {
        changed = false;
        if (s.startsWith('a ')) {
            s = s.slice(2).trimStart();
            changed = true;
        } else if (s.startsWith('an ')) {
            s = s.slice(3).trimStart();
            changed = true;
        } else if (s.startsWith('the ')) {
            s = s.slice(4).trimStart();
            changed = true;
        } else if (s.startsWith('blessed ') || s.startsWith('holy ')) {
            out.blessed = true;
            s = s.slice(s.startsWith('blessed ') ? 8 : 5).trimStart();
            changed = true;
        } else if (s.startsWith('cursed ') || s.startsWith('unholy ')) {
            out.cursed = true;
            s = s.slice(s.startsWith('cursed ') ? 7 : 7).trimStart();
            changed = true;
        } else if (s.startsWith('uncursed ')) {
            out.uncursed = true;
            s = s.slice(9).trimStart();
            changed = true;
        } else if (s.startsWith('rustproof ') || s.startsWith('erodeproof ')
                   || s.startsWith('corrodeproof ') || s.startsWith('fixed ')
                   || s.startsWith('fireproof ') || s.startsWith('rotproof ')
                   || s.startsWith('tempered ') || s.startsWith('crackproof ')) {
            out.erodeproof = true;
            const m = s.match(/^\S+\s+/);
            s = s.slice(m[0].length).trimStart();
            changed = true;
        } else if (s.startsWith('lit ') || s.startsWith('burning ')) {
            out.islit = true;
            s = s.slice(s.startsWith('lit ') ? 4 : 8).trimStart();
            changed = true;
        } else if (s.startsWith('unlit ') || s.startsWith('extinguished ')) {
            out.islit = false; // explicitly unlit
            s = s.slice(s.startsWith('unlit ') ? 6 : 13).trimStart();
            changed = true;
        } else if (s.startsWith('greased ')) {
            out.greased = true;
            s = s.slice(8).trimStart();
            changed = true;
        } else if (s.startsWith('blank ') || s.startsWith('unlabeled ') || s.startsWith('unlabelled ')) {
            out.unlabeled = true;
            const len = s.startsWith('blank ') ? 6 : s.startsWith('unlabeled ') ? 10 : 11;
            s = s.slice(len).trimStart();
            changed = true;
        } else if (s.startsWith('poisoned ')) {
            out.ispoisoned = true;
            s = s.slice(9).trimStart();
            changed = true;
        } else if (s.startsWith('wet ') || s.startsWith('moist ')) {
            out.wetness = true;
            s = s.slice(s.startsWith('wet ') ? 4 : 6).trimStart();
            changed = true;
        } else {
            const spe = s.match(/^([+-]\d+)\s+/);
            if (spe) {
                out.spe = parseInt(spe[1], 10);
                s = s.slice(spe[0].length).trimStart();
                changed = true;
            } else {
                const qty = s.match(/^(\d+)\s+/);
                if (qty) {
                    out.count = parseInt(qty[1], 10) || 1;
                    s = s.slice(qty[0].length).trimStart();
                    changed = true;
                }
            }
        }
    }
    out.name = s;
    return out;
}
// C ref: objnam.c:2521 wrpsym — random class table for failed wishes
const wrpsym = [
    WAND_CLASS, RING_CLASS, POTION_CLASS,
    SCROLL_CLASS, GEM_CLASS, AMULET_CLASS,
    SPBOOK_CLASS, SPBOOK_CLASS, WEAPON_CLASS,
    ARMOR_CLASS, TOOL_CLASS, FOOD_CLASS,
    FOOD_CLASS,
];
export function readobjnam(bp, no_wish = null) {
    // C ref: objnam.c:4913 — null bp goes straight to any: label
    if (bp == null) {
        const oclass = wrpsym[rn2(wrpsym.length)];
        return mkobj(oclass, false);
    }
    const parsed = parseWishPrefixes(bp);
    if (!parsed.name) {
        // C ref: objnam.c:4992 any: — empty name picks random class
        const oclass = wrpsym[rn2(wrpsym.length)];
        return mkobj(oclass, false);
    }
    if (parsed.name === 'nothing' || parsed.name === 'nil' || parsed.name === 'none') {
        return no_wish;
    }
    // C ref: objnam.c:4487-4499
    // "holy water"/"unholy water" are not actual potion names, but C maps
    // them to POT_WATER while setting BUC.
    let forcedTyp = -1;
    let parsedName = parsed.name;
    if (/\bunholy water$/.test(parsedName)) {
        parsed.cursed = true;
        parsed.blessed = false;
        parsed.uncursed = false;
        forcedTyp = POT_WATER;
        parsedName = 'water';
    } else if (/\bholy water$/.test(parsedName)) {
        parsed.blessed = true;
        parsed.cursed = false;
        parsed.uncursed = false;
        forcedTyp = POT_WATER;
        parsedName = 'water';
    }
    // C ref: objnam.c:4512-4518 — blank/unlabeled scroll or spellbook
    // Resolved early like C's "goto typfnd" path: mksobj(typ, TRUE, FALSE)
    // then the caller (makewish) handles BUC and quantity adjustments.
    if (parsed.unlabeled) {
        const nm = parsed.name.toLowerCase();
        let blankTyp = -1;
        if (nm.endsWith('scroll') || nm.endsWith('scrolls'))
            blankTyp = SCR_BLANK_PAPER;
        else if (nm.endsWith('spellbook') || nm.endsWith('spellbooks'))
            blankTyp = SPE_BLANK_PAPER;
        if (blankTyp >= 0) {
            const obj = mksobj(blankTyp, true, false);
            if (parsed.blessed) bless(obj);
            else if (parsed.cursed) curse(obj);
            else if (parsed.uncursed) { obj.blessed = 0; obj.cursed = 0; }
            if (parsed.count > 1) obj.quan = parsed.count;
            return obj;
        }
    }
    // C ref: objnam.c:4487-4498 — "holy water" / "unholy water"
    {
        const nm = parsed.name.toLowerCase();
        if (nm.endsWith('holy water')) {
            const isUnholy = nm.endsWith('unholy water');
            const obj = mksobj(POT_WATER, true, false);
            if (isUnholy) {
                curse(obj); obj.blessed = 0;
            } else {
                bless(obj); obj.cursed = 0;
            }
            if (parsed.count > 1) obj.quan = parsed.count;
            return obj;
        }
    }
    // C ref: objnam.c:4446 — singularize plural wish names
    if (parsedName !== 'tricks' && parsedName !== 'clothes') {
        const sng = makesingular(parsedName);
        if (sng !== parsedName) {
            if (parsed.count === 1) parsed.count = 2;
            parsedName = sng;
        }
    }
    // C ref: objnam.c:4870-4878 — check for artifact by name FIRST
    // In C, artifact_name is checked before rnd_otyp_by_namedesc.
    // When artifact matches, C skips rnd_otyp_by_namedesc (goto typfnd).
    let otyp = forcedTyp;
    let isArtifactWish = false;
    if (otyp < 0) {
        const otypRef = { value: -1 };
        const aname = artifact_name(parsedName, otypRef, true);
        if (aname) {
            otyp = otypRef.value;
            parsedName = aname;
            isArtifactWish = true;
        }
    }
    const wishClass = inferWishClass(parsedName);
    if (otyp < 0) {
        const prepassName = wishRngPrepassName(parsedName);
        otyp = rnd_otyp_by_namedesc(prepassName, wishClass || inferWishClass(prepassName), 1);
        if (prepassName !== parsedName) {
            for (let i = 0; i < game.objects.length; i++) {
                if (exactWishName(game.objects[i]) === parsedName) {
                    otyp = i;
                    break;
                }
            }
        }
        if (otyp < 0) {
            for (let i = 0; i < game.objects.length; i++) {
                if (exactWishName(game.objects[i]) === parsedName) {
                    otyp = i;
                    break;
                }
            }
        }
    }
    if (otyp < 0 && !wishClass) {
        // C ref: objnam.c:4990 — unmatched name with no oclass returns null
        return null;
    }
    // C ref: objnam.c:5035 — mksobj when type known, otherwise mkobj(oclass).
    const otmp = (otyp >= 0) ? mksobj(otyp, true, false) : mkobj(wishClass, false);
    // C ref: objnam.c:5271 — clear random erosion from mksobj before applying
    // wish-specified attributes (eroded/corroded/fixed only set if requested)
    otmp.oeroded = otmp.oeroded2 = 0;
 
    // C ref: objnam.c:5075-5083 — quantity gate for mergeable objects.
    // Important for RNG parity: non-debug play consumes rnd(6) in this
    // conditional chain even when count is 1.
    if (parsed.count > 0) {
        const isMergeable = !!game.objects[otyp]?.oc_merge;
        if (isMergeable
            && (game.flags?.debug
                || parsed.count < rnd(6)
                || (parsed.count <= 7 && Is_candle(otmp))
                || (parsed.count <= 20
                    && (otyp === ROCK || otyp === FLINT || is_missile(otmp)
                        || (otmp.oclass === WEAPON_CLASS && is_ammo(otmp)))))) {
            otmp.quan = parsed.count;
        }
    }
    // C ref: objnam.c:5084-5090 — "lit" wishes light the object by placing
    // it temporarily on the floor so burn logic can attach a light source.
    if (parsed.islit && (otyp === OIL_LAMP || otyp === MAGIC_LAMP
        || otyp === BRASS_LANTERN || Is_candle(otmp) || otyp === POT_OIL)) {
        place_object(otmp, game.u?.ux ?? 0, game.u?.uy ?? 0);
        begin_burn(otmp, false);
        obj_extract_self(otmp);
    }
    if (parsed.spe != null) {
        otmp.spe = parsed.spe;
    }
    if (parsed.cursed) {
        curse(otmp);
    } else if (parsed.blessed) {
        bless(otmp);
    } else if (parsed.uncursed) {
        otmp.blessed = false;
        otmp.cursed = false;
    }
    // Apply additional parsed attributes
    if (parsed.erodeproof) otmp.oerodeproof = true;
    if (parsed.greased) otmp.greased = true;
    if (parsed.ispoisoned) otmp.opoisoned = true;
    // C ref: objnam.c readobjnam — set dknown so appearance description is
    // used (e.g., "an oval amulet" not "an amulet"). Do NOT set known=true
    // here — C only does that in the killer_xname path (objnam.c:1960), not
    // in the general wish path. Setting known=true would show wand charges
    // and other hidden properties prematurely.
    otmp.dknown = true;
    // C ref: objnam.c:5344-5363 — name the object (artifact assignment)
    // C only calls oname() when d.name is set, which happens when the wish
    // text contains a name that wasn't consumed by type matching. This is
    // true for artifact wishes (isArtifactWish) but NOT for regular items
    // like "scroll of enchant armor" where the name IS the type.
    if (isArtifactWish && parsedName) {
        if (!otmp.oextra) otmp.oextra = {};
        otmp.oextra.oname = parsedName;
        // Check if naming creates an artifact
        const artIdx = artilist.findIndex((a, i) => i > 0 && a.otyp === otmp.otyp
            && a.name.toLowerCase() === parsedName.toLowerCase());
        if (artIdx > 0) {
            otmp.oartifact = artIdx;
            if (game.artiexist) game.artiexist[artIdx] = true;
        }
    }
    // C ref: objnam.c:5371-5378 — artifact denial check (consumes RNG even in debug)
    // The rn2(nartifact_exist()) call is consumed whenever oartifact is set,
    // even when the denial is skipped (wizard mode). Must match C's RNG.
    if (otmp.oartifact) {
        otmp.quan = 1;
        const nExist = nartifact_exist();
        const isQuest = is_quest_artifact(otmp);
        if (!isQuest) {
            // rn2(nExist) consumed when !is_quest_artifact
            rn2(nExist);  // consumed for RNG parity, result unused in debug mode
        }
    }
    otmp.owt = weight(otmp);
    return otmp;
}
// ── Helper: type_is_pname / the_unique_pm ──
// C ref: mondata.h type_is_pname(), monst.c the_unique_pm()
export function the_unique_pm(pm) { return !!(pm?.geno & G_UNIQ) && !type_is_pname(pm); }
// ── the / The: prepend "the " / "The " ──
// C ref: objnam.c the(), The()
export function the(str) {
    if (!str) return 'the ';
    // C ref: objnam.c the() — idempotent and normalizes leading "The " to "the ".
    if (str.length >= 4 && str.slice(0, 4).toLowerCase() === 'the ')
        return 't' + str.slice(1);
    return 'the ' + str;
}
export function The(str) {
    if (!str) return 'The ';
    const t = the(str);
    return t.charAt(0).toUpperCase() + t.slice(1);
}
// ── An: prepend "A " or "An " (capitalized article) ──
// C ref: objnam.c An()
export function An(str) {
    const result = an(str);
    return result.charAt(0).toUpperCase() + result.slice(1);
}
// ── is_plural: check if object quantity > 1 ──
// C ref: objnam.c is_plural()
export function is_plural(obj) { return (obj?.quan || 1) > 1; }
// C ref: objnam.c as_is[] — words that makesingular leaves plural
const _as_is_plurals = [
    'boots', 'shoes', 'gloves', 'lenses', 'scales',
    'eyes', 'gauntlets', 'iron bars',
    'bison', 'deer', 'elk', 'fish', 'fowl',
    'tuna', 'yaki', '-hai', 'krill', 'manes',
    'moose', 'ninja', 'sheep', 'ronin', 'roshi',
    'shito', 'tengu', 'ki-rin', 'nazgul', 'gunyoki',
    'piranha', 'samurai', 'shuriken', 'haggis', 'bordeaux',
];
// ── special_subjs: singular words that look plural ──
// C ref: objnam.c special_subjs[]
const special_subjs = [
    'erinys', 'manes', 'Cyclops', 'Hippocrates', 'Pelias', 'aklys',
    'amnesia', 'detect monsters', 'paralysis', 'shape changers',
    'nemesis',
];
// ── vtense: verb tense for subject ──
// C ref: objnam.c vtense()
// verb is given in plural form (no trailing s). Returns singular form
// if subj is singular, else returns verb as-is.
export function vtense(subj, verb) {
    if (subj) {
        const sl = subj.toLowerCase();
        // "a " / "an " prefix means singular
        if (sl.startsWith('a ') || sl.startsWith('an '))
            return vtense_sing(verb);
        // Find the relevant word end (before " of ", " from ", etc.)
        let spot = null;
        const markers = [' of ', ' from ', ' called ', ' named ', ' labeled '];
        for (const m of markers) {
            const idx = sl.indexOf(m);
            if (idx > 0) {
                spot = idx - 1;
                break;
            }
        }
        if (spot === null) spot = subj.length - 1;
        const spotChar = subj[spot].toLowerCase();
        // plural: ends in 's' but not 'us' or 'ss'
        // Also check for 'eeth', 'feet', 'ia', 'ae'
        const subLen = spot + 1;
        if ((spotChar === 's' && spot > 0 && !'us'.includes(subj[spot - 1].toLowerCase()))
            || (spot >= 3 && subj.substring(spot - 3, spot + 1).toLowerCase() === 'eeth')
            || (spot >= 3 && subj.substring(spot - 3, spot + 1).toLowerCase() === 'feet')
            || (spot >= 1 && subj.substring(spot - 1, spot + 1).toLowerCase() === 'ia')
            || (spot >= 1 && subj.substring(spot - 1, spot + 1).toLowerCase() === 'ae')) {
            // Check special_subjs exceptions
            const checkStr = subj.substring(0, subLen).toLowerCase();
            for (const spec of special_subjs) {
                const ltmp = spec.length;
                if (subLen === ltmp && checkStr === spec.toLowerCase())
                    return vtense_sing(verb);
                // also check for "<prefix> <special_subj>"
                if (subLen > ltmp && subj[spot - ltmp] === ' '
                    && subj.substring(spot - ltmp + 1, spot + 1).toLowerCase() === spec.toLowerCase())
                    return vtense_sing(verb);
            }
            // Subject is plural — return verb as-is
            return verb;
        }
        // "they" / "you" — plural
        if (sl === 'they' || sl === 'you')
            return verb;
    }
    // Singular: conjugate the verb
    return vtense_sing(verb);
}
// ── vtense_sing: add singular conjugation to verb ──
// C ref: objnam.c vtense() "sing:" label
function vtense_sing(verb) {
    if (!verb) return '';
    const vl = verb.toLowerCase();
    if (vl === 'are') return 'is';
    if (vl === 'have') return 'has';
    const len = verb.length;
    const last = verb[len - 1].toLowerCase();
    // z, x, s, ch, sh, or 2-letter verb ending in 'o' → add "es"
    if ('zxs'.includes(last)
        || (len >= 2 && last === 'h' && 'cs'.includes(verb[len - 2].toLowerCase()))
        || (len === 2 && last === 'o')) {
        return verb + 'es';
    }
    // consonant + y → ies
    if (last === 'y' && len >= 2 && !vowels.includes(verb[len - 2].toLowerCase())) {
        return verb.substring(0, len - 1) + 'ies';
    }
    return verb + 's';
}
// ── otense: verb tense based on object quantity ──
// C ref: objnam.c otense()
export function otense(obj, verb) {
    if (!is_plural(obj))
        return vtense(null, verb);
    return verb;
}
// ── corpse_xname: name for corpse objects ──
// C ref: objnam.c corpse_xname()
// Simplified: handles the common case (no adjective, CXN_NORMAL)
export function corpse_xname(obj, adjective, cxn_flags) {
    cxn_flags = cxn_flags || 0;
    const ignore_quan = !!(cxn_flags & 1); // CXN_SINGULAR
    const no_prefix_flag = !!(cxn_flags & 2); // CXN_NO_PFX
    const the_prefix_flag = !!(cxn_flags & 4); // CXN_PFX_THE
    const any_prefix_flag = !!(cxn_flags & 8); // CXN_ARTICLE
    const omit_corpse = !!(cxn_flags & 16); // CXN_NOCORPSE
    const omndx = obj?.corpsenm ?? NON_PM;
    let mnam;
    let possessive = false;
    let no_prefix = no_prefix_flag;
    let the_prefix = the_prefix_flag;
    let any_prefix = any_prefix_flag;
    if (omndx === NON_PM) {
        mnam = 'thing';
    } else {
        mnam = mons[omndx]?.mname || 'thing';
        const pm = mons[omndx];
        if (the_unique_pm(pm) || type_is_pname(pm)) {
            mnam = s_suffix(mnam);
            possessive = true;
            if (type_is_pname(pm))
                no_prefix = true;
            else if (the_unique_pm(pm) && !no_prefix)
                the_prefix = true;
        }
    }
    if (no_prefix)
        the_prefix = any_prefix = false;
    else if (the_prefix)
        any_prefix = false;
    let nambuf = '';
    if (the_prefix)
        nambuf += 'the ';
    if (!adjective) {
        nambuf += mnam;
    } else {
        if (possessive)
            nambuf += `${mnam} ${adjective}`;
        else
            nambuf += `${adjective} ${mnam}`;
        nambuf = nambuf.replace(/\s+/g, ' ').trim();
        // if adjective starts with digit, suppress article
        if (/^\d/.test(adjective))
            any_prefix = false;
    }
    if (!omit_corpse) {
        nambuf += ' corpse';
        if ((obj?.quan || 1) > 1 && !ignore_quan) {
            nambuf += 's';
            any_prefix = false;
        }
    }
    if (any_prefix) {
        nambuf = an(nambuf);
    }
    return nambuf;
}
// ── cxname: xname that includes monster type for corpses ──
// C ref: objnam.c cxname()
export function cxname(obj) {
    if (obj?.otyp === CORPSE)
        return corpse_xname(obj, null, 0); // CXN_NORMAL
    return xname(obj);
}
// ── cxname_singular: cxname ignoring quantity ──
// C ref: objnam.c cxname_singular()
export function cxname_singular(obj) {
    if (obj?.otyp === CORPSE)
        return corpse_xname(obj, null, 1); // CXN_SINGULAR
    // xname with CXN_SINGULAR — temporarily set quan to 1
    const save = obj?.quan;
    if (obj) obj.quan = 1;
    const result = xname(obj);
    if (obj) obj.quan = save;
    return result;
}
// ── aobjnam: "count cxname verb" ──
// C ref: objnam.c aobjnam()
export function aobjnam(obj, verb) {
    let bp = cxname(obj);
    if ((obj?.quan || 1) !== 1) {
        bp = `${obj.quan} ${bp}`;
    }
    if (verb) {
        bp += ' ' + otense(obj, verb);
    }
    return bp;
}
// ── Tobjnam: "The xname verb" ──
// C ref: objnam.c Tobjnam()
export function Tobjnam(obj, verb) {
    let bp = The(xname(obj));
    if (verb) {
        bp += ' ' + otense(obj, verb);
    }
    return bp;
}
// ── yname: "[your ]cxname(obj)" ──
// C ref: objnam.c yname()
export function yname(obj) {
    let s = cxname(obj);
    // C: leave off "your" for most artifacts with pname,
    // but we don't track oartifact fully yet, so always prepend
    const prefix = shk_your('', obj);
    return prefix + s;
}
// ── Yname2: capitalized yname ──
// C ref: objnam.c Yname2()
export function Yname2(obj) {
    const s = yname(obj);
    return s.charAt(0).toUpperCase() + s.slice(1);
}
// ── yobjnam: "your count cxname verb" ──
// C ref: objnam.c:2260 yobjnam()
export function yobjnam(obj, verb) {
    let s = aobjnam(obj, verb);
    const prefix = shk_your('', obj);
    return prefix + s;
}
// ── Yobjnam2: capitalized yobjnam ──
// C ref: objnam.c:2278 Yobjnam2()
export function Yobjnam2(obj, verb) {
    const s = yobjnam(obj, verb);
    return s.charAt(0).toUpperCase() + s.slice(1);
}
// ── Doname2: capitalized doname ──
// C ref: objnam.c Doname2()
export function Doname2(obj) {
    const s = doname(obj);
    return s.charAt(0).toUpperCase() + s.slice(1);
}
// ── killer_xname: fully identified name for death messages ──
// C ref: objnam.c killer_xname()
export function killer_xname(obj) {
    // Save original settings
    const save_known = obj.known;
    const save_dknown = obj.dknown;
    const save_bknown = obj.bknown;
    const save_rknown = obj.rknown;
    const save_greased = obj.greased;
    const save_blessed = obj.blessed;
    const save_cursed = obj.cursed;
    const save_opoisoned = obj.opoisoned;
    const od = game.objects[obj.otyp];
    const save_ocknown = od?.oc_name_known;
    const save_ocuname = od?.oc_uname;
    // Set flags for killer name
    obj.known = true;
    obj.dknown = true;
    obj.bknown = false;
    obj.rknown = false;
    obj.greased = false;
    if (obj.otyp !== POT_WATER) {
        obj.blessed = false;
        obj.cursed = false;
    } else {
        obj.bknown = true;
    }
    obj.opoisoned = false;
    if (od) {
        od.oc_name_known = 1;
        od.oc_uname = null;
    }
    // Format the object
    let buf;
    if (obj.otyp === CORPSE) {
        buf = corpse_xname(obj, null, 0);
    } else if (obj.otyp === SLIME_MOLD) {
        buf = 'deadly slime mold' + plur(obj.quan || 1);
    } else {
        buf = xname(obj);
    }
    // Apply article if singular
    if ((obj.quan || 1) === 1 && !buf.includes("'s ") && !buf.includes("s' ")) {
        buf = an(buf);
    }
    // Restore original settings
    obj.known = save_known;
    obj.dknown = save_dknown;
    obj.bknown = save_bknown;
    obj.rknown = save_rknown;
    obj.greased = save_greased;
    obj.blessed = save_blessed;
    obj.cursed = save_cursed;
    obj.opoisoned = save_opoisoned;
    if (od) {
        od.oc_name_known = save_ocknown;
        od.oc_uname = save_ocuname;
    }
    return buf;
}
// ── makesingular: convert plural to singular ──
// C ref: objnam.c makesingular()
// Simplified version covering common NetHack object/monster names.
export function makesingular(str) {
    if (!str || !str.length) return '';
    str = str.trimStart();
    if (!str) return '';
    // Pronoun handling
    const sl = str.toLowerCase();
    if (sl === 'they') return str[0] === 'T' ? 'It' : 'it';
    if (sl === 'them') return str[0] === 'T' ? 'It' : 'it';
    if (sl === 'their') return str[0] === 'T' ? 'Its' : 'its';
    // Handle "foo of bar" — singularize just "foo"
    let excess = '';
    const markers = [' of ', ' from ', ' called ', ' named ', ' labeled '];
    for (const m of markers) {
        const idx = str.indexOf(m);
        if (idx > 0) {
            excess = str.substring(idx);
            str = str.substring(0, idx);
            break;
        }
    }
    let p = str.length;
    // Check special_subjs — these don't need singularization
    for (const spec of special_subjs) {
        if (str.toLowerCase() === spec.toLowerCase())
            return str + excess;
    }
    // C ref: objnam.c as_is[] — words that stay plural
    const strLower = str.toLowerCase();
    for (const word of _as_is_plurals) {
        if (strLower === word || strLower.endsWith(' ' + word))
            return str + excess;
    }
    if (p >= 1 && str[p - 1].toLowerCase() === 's') {
        if (p >= 2 && str[p - 2].toLowerCase() === 'e') {
            if (p >= 3 && str[p - 3].toLowerCase() === 'i') {
                // "ies" → check exceptions first
                if (str.toLowerCase().endsWith('cookies')
                    || str.toLowerCase().endsWith('zombies')
                    || str.toLowerCase().endsWith('valkyries')) {
                    // Just drop 's'
                    return str.substring(0, p - 1) + excess;
                }
                // ies → y
                return str.substring(0, p - 3) + 'y' + excess;
            }
            // "ves" → "f" (wolves → wolf, but not fully reversible)
            // C: only when char before "ves" is in "lr" or vowels
            if (p >= 4 && str.substring(p - 3).toLowerCase() === 'ves'
                && ('lr'.includes(str[p - 4].toLowerCase())
                    || vowels.includes(str[p - 4].toLowerCase()))
                && !str.toLowerCase().endsWith('cloves')
                && !str.toLowerCase().endsWith('nerves')) {
                return str.substring(0, p - 3) + 'f' + excess;
            }
            // Various -es endings that drop "es"
            const last4 = p >= 4 ? str.substring(p - 4).toLowerCase() : '';
            if (last4 === 'eses' || last4 === 'oxes' || last4 === 'nxes'
                || last4 === 'ches' || last4 === 'uses' || last4 === 'shes'
                || last4 === 'sses'
                || (p >= 5 && str.substring(p - 5).toLowerCase() === 'atoes')
                || (p >= 7 && str.substring(p - 7).toLowerCase() === 'dingoes')) {
                return str.substring(0, p - 2) + excess;
            }
            // else fall through to drop just 's'
        } else if (p >= 2 && str.substring(p - 2).toLowerCase() === 'us') {
            // "us" — already singular (fungus, etc.)
            return str + excess;
        } else if (p >= 2 && str.substring(p - 2).toLowerCase() === 'ss') {
            // "ss" — already singular (mattress, etc.)
            return str + excess;
        } else if (p >= 5 && str.substring(p - 5).toLowerCase() === ' lens') {
            // "lens" — already singular
            return str + excess;
        } else if (p === 4 && str.toLowerCase() === 'lens') {
            return str + excess;
        }
        // Default: drop trailing 's'
        return str.substring(0, p - 1) + excess;
    }
    // Input doesn't end in 's'
    if (p >= 3 && str.substring(p - 3).toLowerCase() === 'men') {
        // men → man (cavemen → caveman)
        return str.substring(0, p - 2) + 'an' + excess;
    }
    if (p >= 2 && str.substring(p - 2).toLowerCase() === 'ae') {
        // ae → a (algae → alga)
        return str.substring(0, p - 1) + excess;
    }
    if (p >= 2 && str.substring(p - 2).toLowerCase() === 'ia'
        && p >= 4 && str[p - 3].toLowerCase() === 'r'
        && str[p - 4].toLowerCase() === 'e') {
        // eria → erium
        return str.substring(0, p - 1) + 'um' + excess;
    }
    return str + excess;
}
// ── Remaining stubs and simple wrappers ──
export function ansimpleoname(obj) { return an(xname(obj)); }
export function simpleonames(obj) { return xname(obj); }
export function ysimple_name(obj) {
    const prefix = shk_your('', obj);
    return prefix + minimal_xname(obj);
}
export function singular(obj, fn) { const save = obj.quan; obj.quan = 1; const r = fn(obj); obj.quan = save; return r; }
export function thesimpleoname(obj) { return 'the ' + xname(obj); }
export function distant_name(obj, fn) { return fn(obj); }
export function obj_typename(otyp) {
    if (otyp == null || otyp < 0) return 'object';
    const od = game.objects?.[otyp];
    if (!od) return 'object';
    return od.oc_name || od.oc_descr || 'object';
}
export function simple_typename(otyp) {
    return obj_typename(otyp);
}
export function minimal_xname(obj) { return xname(obj); }
// C ref: objnam.c:333 — artifact is a proper name only if fully identified
export function obj_is_pname(obj) {
    if (!obj?.oartifact || !obj.oextra?.oname) return false;
    // C: not_fully_identified check — artifacts aren't pname until identified
    if (!game.program_state?.gameover && !game.iflags?.override_ID) {
        if (not_fully_identified(obj)) return false;
    }
    return true;
}
// C ref: objnam.c:5511 helm_simple_name()
export function helm_simple_name(helmet) {
    return !hard_helmet(helmet) ? 'hat' : 'helm';
}
// C ref: objnam.c:5490 cloak_simple_name()
export function cloak_simple_name(cloak) {
    if (cloak) {
        if (cloak.otyp === ROBE) return 'robe';
        if (cloak.otyp === MUMMY_WRAPPING) return 'wrapping';
        if (cloak.otyp === ALCHEMY_SMOCK) {
            return (game.objects[cloak.otyp]?.oc_name_known && cloak.dknown)
                ? 'smock' : 'apron';
        }
    }
    return 'cloak';
}
// C ref: objnam.c:5469 suit_simple_name()
export function suit_simple_name(suit) {
    if (suit) {
        if (Is_dragon_scale_mail(suit)) return 'dragon mail';
        if (Is_dragon_scales(suit)) return 'dragon scales';
        const suitnm = game.objects[suit.otyp]?.oc_name || '';
        if (suitnm.length > 5 && suitnm.endsWith(' mail')) return 'mail';
        if (suitnm.length > 7 && suitnm.endsWith(' jacket')) return 'jacket';
    }
    return 'suit';
}
// C ref: objnam.c:5521 gloves_simple_name()
export function gloves_simple_name(gloves) {
    return 'gloves';
}
// C ref: objnam.c:5531 boots_simple_name()
export function boots_simple_name(boots) {
    return 'boots';
}
// C ref: objnam.c:5541 shield_simple_name()
export function shield_simple_name(shield) {
    if (shield) {
        const odata = game.objects[shield.otyp];
        if (odata && odata.oc_name.endsWith('buckler')) return 'buckler';
    }
    return 'shield';
}
// C: Ysimple_name2(obj) — capitalized simple name
export function Ysimple_name2(obj) {
    const n = simpleonames(obj);
    return n.charAt(0).toUpperCase() + n.slice(1);
}
// C ref: objnam.c:5622 safe_qbuf()
// Build "prefix + objname + suffix", trying func(obj) first, then altfunc(obj),
// falling back to lastR. JS has no buffer limits so this is simplified.
export async function safe_qbuf(qbuf, prefix, suffix, obj, func, altfunc, lastR) {
    const name = func ? await func(obj) : (altfunc ? altfunc(obj) : lastR);
    return (prefix || '') + name + (suffix || '');
}