All files / systems/ai DecisionTree.ts

83.56% Statements 478/572
77.8% Branches 333/428
92.72% Functions 51/55
83.45% Lines 474/568

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 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504                                                                                                                    26x                                       26x                                                             26x                                                     26x                   26x                                                         8120x   8120x     8120x             8120x       8120x       8120x 8120x           8120x 8120x 7833x 55x     8120x       8120x                                               6556x 6556x 6556x 6556x 6556x       6556x 6556x       6556x   6556x                 26x     6556x                                     2941x   2941x                                     1328x   1328x 1328x 1328x                                 844x                                   1328x                                 2097x               328x                             95x     95x 95x                                                               8120x   8120x         8120x   8120x     1988x 1988x     199x 199x     266x 266x     5565x 5565x     102x 102x       8120x                                                             1841x       1841x     1841x     192x 192x 192x 192x 192x       337x 337x 337x   337x       27x 27x 27x   27x       1280x 1280x 1280x 1280x 1280x       5x 5x 5x 5x 5x     1841x                                                                                                                 5619x       5619x     5619x 5619x               5619x 52x 52x 52x 52x 5567x     204x 204x 204x 204x 5363x     78x 78x 78x       5619x 217x 217x       5619x 216x 216x     5619x                                                   5565x 28x 28x 28x             5565x   17x       17x 17x                 4535x       4535x 4535x         380x       380x                                       5619x                                                                           8120x     8120x   8120x                               11374x     11374x         11374x 11374x 3182x                 8192x               8192x 8192x 8192x   8192x 11374x 11374x   11374x     11374x                   72x       72x               8120x     8120x       8120x     8120x         8120x     8120x 8120x     8120x       8120x 18x                     8120x 122x           8120x 772x           8120x     8120x 722x             8120x   1096x     7024x   1864x         5160x       8120x 8068x         8120x 8120x 5565x   22824x               22824x 22824x 136944x     22824x     22824x           22824x                 22824x 17205x       5619x                   22824x             22824x 22824x 117x 5502x 293x 5209x 1x 5208x 53x 5155x 5155x         5619x         8120x   386x         1844x                     1844x 1844x 11049x       1844x     1844x   3x       1841x               1844x             1844x 1844x   1841x 352x 1489x   1489x       1841x       386x 1458x       386x 257x       386x       352x   34x         386x           386x       7734x 24484x       7734x 5308x       7734x       303x   7431x         7734x           7734x                             8120x 8120x     8120x     8120x 8120x   8120x   14x                     14x   14x                   8106x                                               122x 122x     122x                                                                     122x   122x   122x 11x 11x                                       11x             111x                                                                                 18x           18x 18x     18x 13x       18x 2x 16x 15x       18x 18x   1x       18x 18x   2x               16x     16x     18x   18x                                   16x                             16x                       772x                 772x 3x               769x       772x 772x 772x   772x 491x             278x                                                                         1328x 1328x     1328x 399x 929x 49x   880x     1328x     1328x 4383x       1328x     1719x   1328x 674x     654x                                           8120x 192x             7928x           7928x 8120x 8120x           8120x 8120x 5502x                       2426x     2426x                       1154x               1154x 1154x 1098x                 1328x                 1328x             1328x               533x 533x                 795x     795x               674x 674x                 121x   121x             121x 121x                                                                                         722x   722x     722x 188x             534x                                                   1096x 1096x     1096x     1096x         1096x   352x       352x 352x                                             744x 744x 744x   1096x 323x               421x       82x                 339x                                           1096x         1096x 1096x 755x       341x 23870x     341x                 341x               341x   257x 3861x     257x   257x 5527x   257x         84x 1670x     84x   84x 1671x   84x                                                                 7928x 1415x   6513x 2544x   3969x                                     15144x       15144x                                                       1864x 1864x     1864x                 1864x     1864x 30x   16x 16x   8x 8x   5x 5x   1x 1x                   1864x   1249x 615x         18x     597x         1864x     1864x 30x     16x 16x   8x 8x     6x 6x       1864x 1864x 1864x   1864x 1864x 30x   16x 16x   8x 8x   5x 5x   1x 1x             1864x                                           1864x   1864x   1774x   33x   57x                                                 1249x 1249x 1249x     1249x     1249x         1249x     1249x         1249x                                                   18x 18x 18x     18x     18x           18x       18x       18x 18x 18x   18x                                               7038x 7038x     7038x 7038x   7038x                                                 5160x 5160x 5160x 5160x 5160x     5160x     5160x                                 5160x 5160x 5160x                                                                                                                                                                 8068x     8068x 35x             8033x                                                     14x 14x 14x     14x   14x     14x                     14x 14x   14x                               5757x 5757x   5757x                                                                             940x 940x 940x   940x 940x      
/**
 * AI Decision Tree for Korean Martial Arts Combat
 * Strategic decision-making system with multiple tactical options
 *
 * **Korean Philosophy Integration (한국 무술 철학)**:
 * - 지피지기백전불태 (知彼知己百戰不殆) - Know the enemy, know yourself, and victory is certain
 * - 이순응변 (以柔應變) - Adapt with flexibility and flow like water
 * - 급소공격 (急所攻擊) - Strike vital points with precision and timing
 */
 
import { getArchetypePhysicalAttributes } from "@/data/archetypePhysicalAttributes";
import { PlayerState } from "@/systems/player";
import { TrigramSystem } from "@/systems/TrigramSystem";
import {
  KOREAN_VITAL_POINTS,
  getVitalPointById,
} from "@/systems/vitalpoint/KoreanVitalPoints";
import { PlayerArchetype, Position, TrigramStance } from "@/types";
import { AI_MOVEMENT_METERS } from "@/types/physicsConstants";
import type { CounterOpportunity, ExposedLimbType } from "@/types/physics";
import { DifficultyParameters } from "./AdaptiveDifficulty";
import { AIPersonality, getArchetypeBehavior } from "./AIPersonality";
import { enforceArchetypeBehavior } from "./ArchetypeEnforcer";
import { AIComboSystem } from "./ComboSystem";
import {
  AIActionType,
  AIDecision,
  CombatContext,
  VulnerabilityContext,
} from "./types";
 
// Re-export types for backward compatibility
export { AIActionType } from "./types"; // Enum (value + type)
export type { AIDecision, CombatContext, VulnerabilityContext } from "./types"; // Type-only
 
/**
 * Body pivot contributions for reach calculations (meters)
 * 
 * These values represent additional reach gained from body mechanics:
 * - Hip rotation and torso lean for kicks
 * - Shoulder offset and torso rotation for punches
 * 
 * Heuristically aligned with PhysicalReachCalculator.ts but intentionally
 * simplified for AI decision-making (e.g., omits stance/animation modifiers).
 * 
 * **NOTE ON BODY RADIUS**: The body pivot values approximate the body radius
 * effect for AI range calculations. For precise hit detection in CombatSystem,
 * use calculateBodyRadius() which accounts for individual archetype differences.
 * 
 * AI decision-making trade-off:
 * - Punch body pivot (shoulder offset + torso rotation): ~0.3-0.35m
 * - Actual body radius (shoulder width * 0.5 / 100): ~0.215-0.27m
 * - Difference: AI slightly overestimates close-range effectiveness
 * - Impact: AI may attempt attacks at marginally longer range than optimal
 * - Benefit: Simplified calculations, acceptable gameplay behavior
 * 
 * @korean 신체 회전 도달 거리 증가 (AI 의사결정을 위한 근사치)
 */
const BODY_PIVOT_METERS = {
  /** Hip rotation + torso lean for kicks (meters) */
  KICK: 0.25,
  /** Torso rotation for punches (meters) */
  TORSO_ROTATION: 0.1,
} as const;
 
/**
 * Average technique extension multipliers
 * 
 * Based on analysis of technique baseExtension values:
 * - Punches: 0.9-0.95 (average 0.95)
 * - Kicks: 1.0-1.05 (average 1.05)
 * 
 * TODO: Consider implementing technique-specific lookup based on actual
 * technique data for more precise range calculations. Current averages
 * are sufficient for AI decision-making but may need refinement.
 * 
 * @korean 기술 연장 배수
 */
const TECHNIQUE_EXTENSION = {
  /** Average punch baseExtension multiplier */
  PUNCH: 0.95,
  /** Average kick baseExtension multiplier */
  KICK: 1.05,
} as const;
 
/**
 * Distance-based stance preferences for tactical positioning
 *
 * Stances are categorized by optimal combat range based on actual technique
 * reach configurations (baseExtension values from technique definitions):
 *
 * **CLOSE (≤0.6m)** - Grappling/clinch range:
 * - TAE (☱ Lake) - Joint manipulation, grapples (0.9 baseExtension, needs contact)
 * - GAM (☵ Water) - Throws, counters (0.7-0.9 baseExtension)
 * - GON (☷ Earth) - Ground techniques, Ssireum throws (0.9 baseExtension)
 * - GAN (☶ Mountain) - Immovable defense, blocks (0.9 baseExtension)
 *
 * **MID (0.6-1.0m)** - Striking range:
 * - GEON (☰ Heaven) - Direct force, power strikes (0.95-1.05 baseExtension)
 * - LI (☲ Fire) - Precision nerve strikes (0.92-0.95 baseExtension)
 * - SON (☴ Wind) - Continuous pressure, Taekyon (0.95-1.05 baseExtension)
 *
 * **FAR (>1.0m)** - Long range kicks/closing distance:
 * - JIN (☳ Thunder) - Explosive jumping kicks (1.15 baseExtension)
 * - SON (☴ Wind) - Closing footwork pressure
 * - GAN (☶ Mountain) - Patient defensive waiting
 *
 * @korean 거리별 자세 선호도 (기술 도달 거리 기반)
 */
const DISTANCE_BASED_STANCES: Record<string, readonly TrigramStance[]> = {
  CLOSE: [
    TrigramStance.TAE, // ☱ Joint manipulation/grapples
    TrigramStance.GAM, // ☵ Throws/counters
    TrigramStance.GON, // ☷ Ground techniques
    TrigramStance.GAN, // ☶ Blocking defense
  ],
  MID: [
    TrigramStance.GEON, // ☰ Power strikes
    TrigramStance.LI, // ☲ Precision strikes
    TrigramStance.SON, // ☴ Continuous pressure
  ],
  FAR: [
    TrigramStance.JIN, // ☳ Explosive jumping kicks
    TrigramStance.SON, // ☴ Closing pressure
    TrigramStance.GAN, // ☶ Patient defensive waiting
  ],
};
 
/**
 * Hacker observation phase duration in milliseconds
 *
 * Hacker archetype observes opponents for this duration before attacking,
 * collecting combat data for analysis-based tactics.
 *
 * @korean 해커 관찰 단계 지속 시간 (밀리초)
 */
const HACKER_OBSERVATION_DURATION_MS = 10000; // 10 seconds
 
/**
 * Hacker observation phase actions
 *
 * During the observation phase, Hacker only uses non-aggressive
 * positioning actions to collect combat data.
 *
 * @korean 해커 관찰 단계 행동
 */
const HACKER_OBSERVATION_ACTIONS: readonly AIActionType[] = [
  AIActionType.WAIT,
  AIActionType.CIRCLE,
  AIActionType.APPROACH,
] as const;
 
/**
 * Assess opponent vulnerability for exploitation tactics
 *
 * Analyzes multiple vulnerability factors to create comprehensive assessment:
 * - Balance states (HELPLESS/VULNERABLE/SHAKEN)
 * - Stamina depletion (< 20%)
 * - Ki depletion (< 10%)
 * - Composite vulnerability score (weighted average)
 *
 * **Korean Philosophy (취약성 평가)**:
 * Traditional Korean martial arts teach reading opponent's weakness:
 * - 기회 포착 (Gihoei Pochak) - Seizing opportunities
 * - 약점 공격 (Yakjeom Gonggyeok) - Exploiting weaknesses
 * - 결정타 (Gyeoljeongta) - Delivering decisive strikes
 *
 * @korean 상대 취약성 평가
 *
 * @param context - Current combat context with opponent state
 * @returns Vulnerability assessment with boolean flags and composite score
 */
function assessVulnerability(context: CombatContext): VulnerabilityContext {
  // Balance-based vulnerability (Issue #enhance-intelligence-operative-ai)
  // Uses balance state enum from context: HELPLESS, VULNERABLE, SHAKEN, READY
  const isHelpless = context.opponentBalance === "HELPLESS";
  const isVulnerable =
    context.opponentBalance === "VULNERABLE" ||
    context.opponentBalance === "HELPLESS";
  const isShaken =
    context.opponentBalance === "SHAKEN" ||
    context.opponentBalance === "VULNERABLE" ||
    context.opponentBalance === "HELPLESS";
 
  // Resource-based vulnerability (Issue #enhance-intelligence-operative-ai)
  // Stamina and ki depletion indicate defensive weakness
  const staminaPercent =
    context.opponentStamina && context.opponentMaxStamina
      ? context.opponentStamina / context.opponentMaxStamina
      : 1.0;
  const kiPercent =
    context.opponentKi && context.opponentMaxKi
      ? context.opponentKi / context.opponentMaxKi
      : 1.0;
 
  const hasLowStamina = staminaPercent < 0.2; // < 20% stamina
  const hasNoKi = kiPercent < 0.1; // < 10% ki
 
  // Composite vulnerability score (0.0-1.0) with weighted factors:
  // - Balance: 40% weight (most critical - physical vulnerability)
  // - Stamina: 30% weight (affects defensive capability)
  // - Ki: 30% weight (affects technique usage)
  let balanceVulnerability = 0.0;
  if (isHelpless) balanceVulnerability = 1.0;
  else if (isVulnerable) balanceVulnerability = 0.7;
  else if (isShaken) balanceVulnerability = 0.5;
 
  const overallVulnerability =
    balanceVulnerability * 0.4 +
    (1 - staminaPercent) * 0.3 +
    (1 - kiPercent) * 0.3;
 
  return {
    isHelpless,
    isVulnerable,
    isShaken,
    hasLowStamina,
    hasNoKi,
    overallVulnerability,
  };
}
 
/**
 * AI Decision Tree System
 *
 * **Korean Combat Philosophy (한국 무술 철학)**:
 * This system embodies traditional Korean martial arts principles:
 *
 * - **팔괘 응용** (Trigram Application): Uses Eight Trigram system for stance transitions
 * - **급소 타격** (Vital Point Strikes): Targets anatomical weak points with precision
 * - **상황 판단** (Situational Awareness): Adapts tactics based on combat context
 * - **기술 조합** (Technique Combinations): Chains attacks into flowing combos
 * - **방어 우선** (Defense First): Prioritizes survival and tactical retreat when needed
 * - **취약성 공략** (Vulnerability Exploitation): Exploits defenseless states with precision (Issue #enhance-intelligence-operative-ai)
 */
export class AIDecisionTree {
  private lastDecisionTime = 0;
  private decisionCooldown = 50; // 50ms minimum between decisions
  private consecutiveAttacks = 0;
  private lastStanceChange = 0;
  private readonly stanceChangeCooldown = 3000; // 3 seconds
 
  // Psychological warfare tracking (Issue #enhance-intelligence-operative-ai)
  // Tracks cumulative psychological pressure for Intelligence Operative archetype
  private psychologicalPressure = 0; // 0-100: Cumulative psychological pressure
  private lastPressureActionTime = 0; // Timestamp of last pressure-building action
 
  // Systems for advanced decision-making
  private trigramSystem: TrigramSystem;
  private difficultyLevel: number = 0.5; // 0.0-1.0: AI skill level
  private difficultyParams?: DifficultyParameters; // Difficulty parameters for AI behavior
  private currentReactionDelay: number = 50; // Current reaction delay (calculated once per param change)
 
  /**
   * Scaling factor for fatigue override probability calculation.
   * Used to convert fatigue modifier to override chance in non-linear manner.
   * Value of 0.5 provides gradual scaling: 1.2x fatigue → ~10% override, 1.5x → ~25%.
   *
   * @korean 피로도 우선순위 무시 배율
   */
  private static readonly FATIGUE_OVERRIDE_SCALING_FACTOR = 0.5;
 
  constructor() {
    this.trigramSystem = new TrigramSystem();
  }
 
  /**
   * Calculate kick reach for an archetype based on physical attributes.
   * 
   * **Physics-First**: Returns reach in METERS based on leg length.
   * Includes realistic kick reach calculation:
   * - Leg length converted from cm to meters
   * - Body pivot contribution (hip rotation + torso lean)
   * - Average baseExtension for kicks (1.05x multiplier)
   *
   * Formula: (legLength/100 + BODY_PIVOT_METERS.KICK) × TECHNIQUE_EXTENSION.KICK
   *
   * @param archetype - Player archetype to calculate reach for
   * @returns Kick reach in meters
   * @korean 발차기 도달 거리 (미터)
   */
  private getKickReachMeters(archetype: PlayerArchetype): number {
    const physical = getArchetypePhysicalAttributes(archetype);
    // Leg length in cm -> meters + body pivot * average kick baseExtension
    return (physical.legLength / 100 + BODY_PIVOT_METERS.KICK) * TECHNIQUE_EXTENSION.KICK;
  }
 
  /**
   * Calculate punch reach for an archetype based on physical attributes.
   * 
   * **Physics-First**: Returns reach in METERS based on arm length.
   * Includes realistic punch reach calculation:
   * - Arm length converted from cm to meters
   * - Body pivot (shoulder offset + torso rotation)
   * - Average baseExtension for punches (0.95x multiplier)
   *
   * Formula: (armLength/100 + shoulderOffset + torsoRotation) × TECHNIQUE_EXTENSION.PUNCH
   *
   * @param archetype - Player archetype to calculate reach for
   * @returns Punch reach in meters
   * @korean 주먹 도달 거리 (미터)
   */
  private getPunchReachMeters(archetype: PlayerArchetype): number {
    const physical = getArchetypePhysicalAttributes(archetype);
    // Arm length in cm -> meters + body pivot * average punch baseExtension
    const shoulderOffset = physical.shoulderWidth / 2 / 100; // Convert cm to meters
    const bodyPivot = shoulderOffset + BODY_PIVOT_METERS.TORSO_ROTATION;
    return (physical.armLength / 100 + bodyPivot) * TECHNIQUE_EXTENSION.PUNCH;
  }
 
  /**
   * Calculate maximum combat reach for an archetype based on physical attributes.
   *
   * **Physics-First**: Returns reach in METERS based on leg length.
   * Kicks have the longest reach (~1.0-1.3m with body pivot contribution).
   *
   * Note: This is a heuristic approximation. Actual reach also depends on
   * stance modifiers and animation timing not included in AI range calculations.
   *
   * @param archetype - Player archetype to calculate reach for
   * @returns Maximum combat reach in meters
   * @korean 원형별 최대 도달 거리 (미터)
   */
  private getArchetypeMaxReach(archetype: PlayerArchetype): number {
    return this.getKickReachMeters(archetype);
  }
 
  /**
   * Get close range threshold for an archetype (punching/elbow distance).
   * Based on arm length from physical attributes.
   * 
   * Uses the shared punch reach calculation helper for consistency.
   * 
   * TODO: Extract to shared utility function with PhysicalReachCalculator.ts
   * to maintain consistency between AI range calculations and actual hit detection.
   * Consider handling elbow techniques separately with different body pivot values.
   *
   * @param archetype - Player archetype
   * @returns Close range threshold in meters
   * @korean 근접 범위 (미터)
   */
  private getArchetypeCloseRange(archetype: PlayerArchetype): number {
    return this.getPunchReachMeters(archetype);
  }
 
  /**
   * Get medium range threshold for an archetype (kicking distance).
   * Based on leg length from physical attributes.
   * 
   * Includes realistic kick reach calculation:
   * - Leg length converted from cm to meters  
   * - Body pivot contribution (hip rotation + torso lean)
   * - Average baseExtension for kicks
   *
   * @param archetype - Player archetype
   * @returns Medium range threshold in meters
   * @korean 중거리 범위 (미터)
   */
  private getArchetypeMediumRange(archetype: PlayerArchetype): number {
    return this.getKickReachMeters(archetype);
  }
 
  /**
   * Set AI difficulty level for vital point targeting accuracy
   * @param level - 0.0 (beginner) to 1.0 (master)
   */
  setDifficultyLevel(level: number): void {
    this.difficultyLevel = Math.max(0, Math.min(1, level));
  }
 
  /**
   * Set difficulty parameters for AI behavior
   * Affects reaction time, accuracy, decision quality, etc.
   *
   * Calculates a randomized reaction delay (within parameter range) once when
   * parameters change. This provides varied AI timing while maintaining consistent
   * behavior throughout the current parameter set.
   *
   * @korean 난이도 매개변수 설정
   * @param params - Difficulty parameters to apply
   */
  setDifficultyParameters(params: DifficultyParameters): void {
    this.difficultyParams = params;
    // Calculate randomized reaction delay once when params change
    // This provides variety while ensuring consistent timing until next param update
    Eif (params) {
      this.currentReactionDelay =
        params.reactionTimeMs.min +
        Math.random() * (params.reactionTimeMs.max - params.reactionTimeMs.min);
    }
  }
 
  /**
   * Check if kill mode should be activated based on archetype behavior
   *
   * Kill mode activates when:
   * - Opponent health is low (<30%)
   * - Opponent is in vulnerable balance state (HELPLESS/VULNERABLE)
   *
   * **Korean Philosophy (결정타 모드)**:
   * Each archetype activates kill mode differently based on combat philosophy:
   * - **Musa**: Honor demands finishing the fight decisively
   * - **Amsalja**: Opportunity for instant takedown with precision
   * - **Hacker**: Analytical window for calculated strike
   * - **Jeongbo Yowon**: Strategic opportunity for submission
   * - **Jojik Pokryeokbae**: Pragmatic moment to finish brutally
   *
   * @korean 결정타 모드 활성화 확인
   *
   * @param context - Current combat context
   * @param personality - AI personality archetype
   * @returns True if kill mode should be active
   */
  private isKillModeActive(
    context: CombatContext,
    personality: AIPersonality,
  ): boolean {
    const opponentHealthPercent =
      context.opponentHealth / context.playerMaxHealth;
    const isOpponentVulnerable =
      context.opponentBalance != null &&
      (context.opponentBalance === "HELPLESS" ||
        context.opponentBalance === "VULNERABLE");
 
    // Different activation thresholds based on archetype philosophy
    let healthThreshold = 0.3; // Default 30%
 
    switch (personality.archetype) {
      case PlayerArchetype.MUSA:
        // Aggressive: Activate kill mode early (honor code)
        healthThreshold = 0.3;
        break;
      case PlayerArchetype.AMSALJA:
        // Precise: Activate when perfect opportunity presents
        healthThreshold = 0.3;
        break;
      case PlayerArchetype.HACKER:
        // Analytical: Calculate optimal finishing window
        healthThreshold = 0.25; // More conservative, waits for clear advantage
        break;
      case PlayerArchetype.JEONGBO_YOWON:
        // Strategic: Balanced approach
        healthThreshold = 0.28;
        break;
      case PlayerArchetype.JOJIK_POKRYEOKBAE:
        // Pragmatic: Opportunistic finishing
        healthThreshold = 0.35; // Earlier activation, dirty fighter mentality
        break;
    }
 
    // Activate kill mode when opponent is low health OR vulnerable
    return opponentHealthPercent < healthThreshold || isOpponentVulnerable;
  }
 
  /**
   * Apply kill mode modifiers to action weights for finishing behavior
   *
   * **Kill Mode Behavior (결정타 행동)**:
   * Each archetype has unique finishing behavior based on combat philosophy:
   * - **Musa**: All-in overwhelming force (2.5x attack, 0x retreat)
   * - **Amsalja**: Instant takedown focus (3.0x technique, feints disabled)
   * - **Hacker**: Analytical precision (2.0x technique, counter focus)
   * - **Jeongbo Yowon**: Strategic control (1.8x technique, balanced approach)
   * - **Jojik Pokryeokbae**: Brutal pragmatism (2.2x attack, dirty tactics)
   *
   * @korean 결정타 모드 가중치 적용
   *
   * @param baseWeights - Base action weight multipliers
   * @param personality - AI personality archetype
   * @param isKillMode - Whether kill mode is active
   * @returns Modified action weights for kill mode
   */
  private applyKillModeModifiers(
    baseWeights: {
      attack: number;
      technique: number;
      defend: number;
      retreat: number;
    },
    personality: AIPersonality,
    isKillMode: boolean,
  ): { attack: number; technique: number; defend: number; retreat: number } {
    Iif (!isKillMode) {
      return baseWeights;
    }
 
    const modified = { ...baseWeights };
 
    // Apply archetype-specific kill mode behavior
    switch (personality.archetype) {
      case PlayerArchetype.MUSA:
        // Warrior: All-in overwhelming force (honor code)
        modified.attack *= 2.5; // Massive attack priority
        modified.technique *= 2.0; // Prefer powerful techniques
        modified.defend *= 0.2; // Minimal defense
        modified.retreat = 0.0; // No retreat (honor code)
        break;
 
      case PlayerArchetype.AMSALJA:
        // Assassin: Instant takedown focus (precision)
        modified.technique *= 3.0; // Prioritize lethal techniques
        modified.attack *= 1.5; // Quick finishers
        modified.defend *= 0.3; // Reduce defense during kill window
        // Note: retreat remains available for tactical repositioning
        break;
 
      case PlayerArchetype.HACKER:
        // Hacker: Analytical precision (calculated strike)
        modified.technique *= 2.0; // Calculated finishing techniques
        modified.attack *= 1.3; // Measured attacks
        modified.defend *= 0.7; // Maintain defensive awareness
        // Counter-attack focus through higher base defense
        break;
 
      case PlayerArchetype.JEONGBO_YOWON:
        // Intelligence Operative: Strategic control (psychological pressure)
        modified.technique *= 1.8; // Strategic techniques
        modified.attack *= 1.6; // Balanced offensive
        modified.defend *= 0.6; // Moderate defense reduction
        modified.retreat *= 0.5; // Tactical retreat available
        break;
 
      case PlayerArchetype.JOJIK_POKRYEOKBAE:
        // Organized Crime: Brutal pragmatism (dirty fighter)
        modified.attack *= 2.2; // Brutal finishing attacks
        modified.technique *= 1.7; // Dirty techniques
        modified.defend *= 0.4; // Reduced defense (pragmatic risk)
        modified.retreat *= 1.2; // Will retreat if needed (survival instinct)
        break;
    }
 
    return modified;
  }
 
  /**
   * Apply Intelligence Operative (Jeongbo Yowon) vulnerability exploitation
   *
   * Enhances decision weights to exploit opponent's defenseless states with precision:
   * - **HELPLESS (balance === HELPLESS)**: 90% takedown priority - Execute precision takedown
   * - **VULNERABLE (balance === VULNERABLE)**: 70% aggressive attack - Sustained pressure tactics
   * - **SHAKEN (balance === SHAKEN)**: 50% pressure increase - Psychological warfare
   * - **Low Stamina (< 20%)**: 60% exploitation - Force defensive positions
   * - **No Ki (< 10%)**: 50% technique spam - Prevent powerful techniques
   *
   * **Multiplier Stacking Behavior**:
   * When multiple vulnerabilities are present, multipliers stack multiplicatively:
   * - VULNERABLE (2.0x attack) + low stamina (1.5x attack) = 3.0x total attack multiplier
   * - VULNERABLE (1.8x technique) + low ki (1.4x technique) = 2.52x total technique multiplier
   * This creates increasingly aggressive exploitation as opponent becomes more vulnerable.
   * Note: HELPLESS state uses exclusive else-if, so it doesn't stack with VULNERABLE/SHAKEN.
   *
   * **Jeongbo Philosophy (정보요원 전략)**:
   * - Knowledge through observation (관찰을 통한 지식)
   * - Psychological manipulation (심리적 조작)
   * - Precise timing (정확한 타이밍)
   * - Strategic exploitation (전략적 공략)
   *
   * This function provides 3x higher vulnerability exploitation rate than Musa,
   * 2x higher psychological warfare usage than Amsalja, and 5x higher takedown
   * success rate when opponent is HELPLESS.
   *
   * @korean 정보요원 취약성 공략
   *
   * @param weights - Base action weight multipliers
   * @param vulnerability - Vulnerability assessment context
   * @param personality - AI personality archetype
   * @returns Modified action weights for Jeongbo exploitation
   */
  private applyJeongboExploitation(
    weights: {
      attack: number;
      technique: number;
      defend: number;
      feint: number;
      approach: number;
      circle: number;
    },
    vulnerability: VulnerabilityContext,
    personality: AIPersonality,
  ): {
    attack: number;
    technique: number;
    defend: number;
    feint: number;
    approach: number;
    circle: number;
  } {
    // Only Jeongbo gets vulnerability exploitation bonuses
    Iif (personality.archetype !== PlayerArchetype.JEONGBO_YOWON) {
      return weights;
    }
 
    const modified = { ...weights };
 
    // Check for psychological pressure buildup (Issue #enhance-intelligence-operative-ai Phase 3)
    const pressureStrike = this.shouldExecutePressureStrike(vulnerability);
    Iif (pressureStrike) {
      // Psychological pressure ≥ 50 + Opponent VULNERABLE = Decisive Strike
      modified.technique *= 3.0; // Execute decisive psychological technique
      modified.attack *= 0.3; // Reduce basic attacks
      return modified; // Override other modifiers for pressure strike
    }
 
    // HELPLESS: Execute precision takedown (90% priority)
    if (vulnerability.isHelpless) {
      modified.technique *= 5.0; // Massive technique priority for Precision Takedown
      modified.attack *= 0.2; // Reduce basic attacks
      modified.defend *= 0.1; // Minimal defense needed
      modified.feint *= 0.1; // No feinting during execution
    }
    // VULNERABLE: Aggressive pressure (70% priority)
    else if (vulnerability.isVulnerable) {
      modified.attack *= 2.0; // Increased attack frequency
      modified.technique *= 1.8; // Tactical Strike priority
      modified.feint *= 0.5; // Less feinting, more action
      modified.defend *= 0.5; // Reduced defense (maintain offensive)
    }
    // SHAKEN: Psychological warfare (50% priority)
    else if (vulnerability.isShaken) {
      modified.feint *= 2.0; // Increase psychological pressure
      modified.circle *= 1.5; // Intimidation tactics (circling)
      modified.technique *= 1.3; // "Psychological Warfare" technique
    }
 
    // Low stamina: Relentless pressure (60% priority)
    if (vulnerability.hasLowStamina) {
      modified.attack *= 1.5; // Force stamina drain
      modified.approach *= 1.3; // Close distance to pressure
    }
 
    // No ki: Technique spam (50% priority)
    if (vulnerability.hasNoKi) {
      modified.technique *= 1.4; // Opponent can't use powerful techniques
      modified.attack *= 1.3; // Maintain offensive
    }
 
    return modified;
  }
 
  /**
   * Build psychological pressure through intimidation tactics
   *
   * Intelligence Operative uses feints, circling, and approach/retreat patterns
   * to build cumulative psychological pressure on opponent. When pressure reaches
   * 50+ and opponent is VULNERABLE, triggers decisive strike.
   *
   * **Psychological Tactics (심리전 전술)**:
   * - Feints: +10 pressure (fake attacks create hesitation)
   * - Circling: +5 pressure (predator circling prey)
   * - Approach: +3 pressure (aggressive positioning)
   * - Decay: -3 pressure per second (pressure fades without action)
   *
   * @korean 심리적 압박 증가
   *
   * @param actionType - Type of action taken (FEINT, CIRCLE, APPROACH, etc.)
   * @param now - Current timestamp for decay calculation
   */
  private buildPsychologicalPressure(
    actionType: AIActionType,
    now: number,
  ): void {
    // Apply pressure decay (3 points per second since last pressure action)
    if (this.lastPressureActionTime > 0) {
      const timeSinceLastAction = now - this.lastPressureActionTime;
      const decayAmount = (timeSinceLastAction / 1000) * 3; // 3 points per second
      this.psychologicalPressure = Math.max(
        0,
        this.psychologicalPressure - decayAmount,
      );
    }
 
    // Build pressure based on action type
    switch (actionType) {
      case AIActionType.FEINT:
        this.psychologicalPressure = Math.min(
          100,
          this.psychologicalPressure + 10,
        );
        this.lastPressureActionTime = now;
        break;
      case AIActionType.CIRCLE:
        this.psychologicalPressure = Math.min(
          100,
          this.psychologicalPressure + 5,
        );
        this.lastPressureActionTime = now;
        break;
      case AIActionType.APPROACH:
        this.psychologicalPressure = Math.min(
          100,
          this.psychologicalPressure + 3,
        );
        this.lastPressureActionTime = now;
        break;
      // Attacks and techniques release pressure (execution phase)
      case AIActionType.ATTACK:
      case AIActionType.TECHNIQUE:
        // Pressure resets after decisive action
        this.psychologicalPressure = Math.max(
          0,
          this.psychologicalPressure * 0.5,
        );
        break;
    }
  }
 
  /**
   * Check if psychological pressure should trigger decisive strike
   *
   * Jeongbo executes decisive technique when:
   * - Psychological pressure ≥ 50 (sustained intimidation)
   * - Opponent is VULNERABLE or worse (balance < 30)
   * - Returns true to boost technique priority
   *
   * @korean 심리적 압박 결정타 확인
   *
   * @param vulnerability - Vulnerability assessment context
   * @returns True if pressure warrants decisive strike
   */
  private shouldExecutePressureStrike(
    vulnerability: VulnerabilityContext,
  ): boolean {
    return (
      this.psychologicalPressure >= 50 &&
      (vulnerability.isVulnerable || vulnerability.isHelpless)
    );
  }
 
  /**
   * Analyze counter-attack opportunity from opponent's limb exposure.
   *
   * **Korean**: 반격 기회 분석 (Counter Opportunity Analysis)
   *
   * Detects when the opponent has exposed limbs during technique execution,
   * enabling defensive counter-attacks and breaking techniques.
   *
   * This integrates the LimbExposureSystem with AI decision-making by:
   * 1. Detecting exposed limbs from opponent's current technique
   * 2. Calculating vulnerability windows and multipliers
   * 3. Providing counter opportunity data for decision prioritization
   *
   * @param context - Combat context with opponent technique data
   * @returns Enhanced context with counter opportunity analysis, or undefined if no opportunity
   *
   * @remarks
   * Returns undefined if:
   * - Opponent is not executing a technique
   * - Technique has no exposure window defined
   * - Current time is outside the exposure window
   *
   * @korean 반격기회분석
   */
  private analyzeCounterOpportunity(
    context: CombatContext,
  ): {
    readonly counterOpportunity?: CounterOpportunity;
    readonly opponentVulnerability: number;
  } {
    // Use pre-calculated counter opportunity from context
    // (CombatSystem calculates this based on opponent's technique state)
    const counterOpportunity = context.counterOpportunity;
    
    // Calculate vulnerability multiplier from opportunity if present
    const opponentVulnerability = counterOpportunity?.vulnerabilityMultiplier ?? 1.0;
 
    return {
      counterOpportunity,
      opponentVulnerability,
    };
  }
 
  /**
   * Make strategic decision based on combat context
   *
   * Applies difficulty-based reaction time delays if difficulty parameters are set
   */
  makeDecision(
    context: CombatContext,
    personality: AIPersonality,
    comboSystem: AIComboSystem,
  ): AIDecision {
    const now = Date.now();
 
    // Apply difficulty-based reaction time delay (calculated once per param change)
    const reactionDelay = this.difficultyParams
      ? this.currentReactionDelay
      : this.decisionCooldown;
 
    // Respect decision cooldown (use reaction delay if difficulty params available)
    const effectiveCooldown = Math.max(this.decisionCooldown, reactionDelay);
    if (now - this.lastDecisionTime < effectiveCooldown) {
      return {
        action: AIActionType.WAIT,
        priority: 0,
        reason: this.difficultyParams
          ? `Reaction time delay: ${effectiveCooldown.toFixed(0)}ms`
          : "Decision cooldown active",
      };
    }
 
    this.lastDecisionTime = now;
 
    // Hacker observation phase (Issue #enforce-distinct-combat-philosophies)
    // Hacker archetype observes for first 10 seconds before attacking (data collection)
    // Skip observation phase during critical situations:
    // - Low health (below tactical retreat threshold)
    // - Kill mode opportunity (opponent < 30% health)
    // - Opponent vulnerable or helpless (exploitable state)
    const healthPercent = context.playerHealth / context.playerMaxHealth;
    const tacticalRetreatThreshold = personality.tacticalRetreatThreshold;
    const isBelowRetreatThreshold = healthPercent < tacticalRetreatThreshold; // Need to retreat
    const opponentMaxHealth =
      context.opponentMaxHealth ?? context.playerMaxHealth; // Use opponent max health if available, fallback to symmetric assumption
    const opponentHealthPercent = context.opponentHealth / opponentMaxHealth;
    const isKillOpportunity = opponentHealthPercent < 0.3; // Kill mode opportunity
    const isOpponentVulnerable =
      context.opponentBalance === "VULNERABLE" ||
      context.opponentBalance === "HELPLESS"; // Exploitable state
 
    if (
      personality.archetype === PlayerArchetype.HACKER &&
      context.timeInMatch < HACKER_OBSERVATION_DURATION_MS &&
      !isBelowRetreatThreshold && // Skip observation if need to retreat
      !isKillOpportunity && // Skip observation if kill opportunity
      !isOpponentVulnerable // Skip observation if opponent is vulnerable
    ) {
      // During observation phase, Hacker only circles and waits
      // No attacks or techniques until data collection is complete
      const randomObservationAction =
        HACKER_OBSERVATION_ACTIONS[
          Math.floor(Math.random() * HACKER_OBSERVATION_ACTIONS.length)
        ];
 
      return {
        action: randomObservationAction,
        priority: 10, // High priority to ensure observation phase is respected
        reason: `Hacker observation phase: collecting data (${(context.timeInMatch / 1000).toFixed(1)}s / ${HACKER_OBSERVATION_DURATION_MS / 1000}s) (해커 관찰 단계)`,
      };
    }
 
    // Check for kill mode activation (Issue #enhance-ai-aggression)
    const killModeActive = this.isKillModeActive(context, personality);
 
    // Assess opponent vulnerability for exploitation (Issue #enhance-intelligence-operative-ai)
    const vulnerability = assessVulnerability(context);
 
    // Analyze counter-attack opportunities from limb exposure (Limb Exposure System Integration)
    // This detects when opponent's technique execution exposes vulnerable limbs
    const counterAnalysis = this.analyzeCounterOpportunity(context);
 
    // Check for active combo first
    Iif (comboSystem.isComboActive()) {
      return this.decideComboAction(context, personality);
    }
 
    // Evaluate tactical options in priority order
    const decisions: AIDecision[] = [];
 
    // Get optimal range for this archetype (using context for meters conversion)
    const optimalRange = this.getOptimalRange(personality, context);
    const distance = context.distanceToOpponent;
 
    // 1. Critical health - survival priority
    decisions.push(this.evaluateSurvival(context, personality));
 
    // 2. Limb exposure counter-attack opportunity (highest tactical priority after survival)
    // Evaluates opportunities to exploit opponent's exposed limbs during technique execution
    if (counterAnalysis.counterOpportunity) {
      decisions.push(
        this.evaluateLimbExposureCounter(
          context,
          personality,
          counterAnalysis.counterOpportunity,
          counterAnalysis.opponentVulnerability,
        ),
      );
    }
 
    // 3. Standard counter-attack opportunity (opponent attacking)
    if (context.isOpponentAttacking) {
      decisions.push(
        this.evaluateCounter(context, personality, killModeActive),
      );
    }
 
    // 4. Combo initiation (only if at reasonable distance)
    if (distance < optimalRange * 1.5) {
      decisions.push(
        this.evaluateComboStart(context, personality, comboSystem),
      );
    }
 
    // 5. Stance transition
    decisions.push(this.evaluateStanceChange(context, personality, now));
 
    // 6. Feint attack (only at mid-close range) - reduced priority in kill mode
    if (distance < optimalRange * 1.8 && !killModeActive) {
      decisions.push(this.evaluateFeint(context, personality));
    }
 
    // 7. Distance-based tactics (archetype-aware ranges)
    // Increased multiplier from 1.2 to 2.0 to allow attacks at greater distances
    // Players start at ~1.6m apart, so this ensures AI can attack immediately
    // Using <= to include exact boundary cases (e.g., Jeongbo at 1.6m = 0.8m * 2.0)
    if (distance <= optimalRange * 2.0) {
      // Close to optimal range - use close-range tactics including vital point targeting
      decisions.push(
        this.evaluateCloseRange(context, personality, killModeActive),
      );
    } else if (distance > optimalRange * 2.5) {
      // Too far - need to approach
      decisions.push(
        this.evaluateApproach(context, personality, killModeActive),
      );
    } else {
      // Mid-range (>2.0x && <=2.5x optimal range) - good tactical position
      decisions.push(this.evaluateMidRange(context, personality));
    }
 
    // 8. Defensive positioning (reduced in kill mode)
    if (!killModeActive || personality.archetype !== PlayerArchetype.MUSA) {
      decisions.push(this.evaluateDefense(context, personality));
    }
 
    // Apply Jeongbo vulnerability exploitation (Issue #enhance-intelligence-operative-ai)
    // This provides 3x higher exploitation rate than other archetypes
    let modifiedDecisions = decisions;
    if (personality.archetype === PlayerArchetype.JEONGBO_YOWON) {
      modifiedDecisions = decisions.map((decision) => {
        // Skip survival decisions (preserve self-preservation)
        const SURVIVAL_REASON_KEYWORDS = [
          "critical health",
          "high pain",
          "survival retreat",
          "emergency retreat",
          "위급 상황",
          "고통 회피",
        ];
        const reasonLower = decision.reason.toLowerCase();
        const hasSurvivalKeyword = SURVIVAL_REASON_KEYWORDS.some((keyword) =>
          reasonLower.includes(keyword),
        );
        const isSurvivalRetreat =
          decision.action === AIActionType.RETREAT &&
          (decision.priority === 20 || hasSurvivalKeyword);
 
        Iif (isSurvivalRetreat) {
          return decision;
        }
 
        // Only apply exploitation to relevant action types
        // Other actions (COUNTER, RETREAT, WAIT, STANCE_CHANGE, COMBO) maintain original priority
        const exploitableActions = [
          AIActionType.ATTACK,
          AIActionType.TECHNIQUE,
          AIActionType.DEFEND,
          AIActionType.FEINT,
          AIActionType.APPROACH,
          AIActionType.CIRCLE,
        ];
 
        if (!exploitableActions.includes(decision.action)) {
          return decision; // Preserve priority for non-exploitable actions
        }
 
        // Calculate base action weights including feint, approach, circle
        const weights = {
          attack: decision.action === AIActionType.ATTACK ? 1.0 : 0.0,
          technique: decision.action === AIActionType.TECHNIQUE ? 1.0 : 0.0,
          defend: decision.action === AIActionType.DEFEND ? 1.0 : 0.0,
          feint: decision.action === AIActionType.FEINT ? 1.0 : 0.0,
          approach: decision.action === AIActionType.APPROACH ? 1.0 : 0.0,
          circle: decision.action === AIActionType.CIRCLE ? 1.0 : 0.0,
        };
 
        // Apply Jeongbo exploitation modifiers
        const modifiedWeights = this.applyJeongboExploitation(
          weights,
          vulnerability,
          personality,
        );
 
        // Adjust priority based on modified weights
        let newPriority = decision.priority;
        if (decision.action === AIActionType.ATTACK) {
          newPriority = decision.priority * modifiedWeights.attack;
        } else if (decision.action === AIActionType.TECHNIQUE) {
          newPriority = decision.priority * modifiedWeights.technique;
        } else if (decision.action === AIActionType.DEFEND) {
          newPriority = decision.priority * modifiedWeights.defend;
        } else if (decision.action === AIActionType.FEINT) {
          newPriority = decision.priority * modifiedWeights.feint;
        } else if (decision.action === AIActionType.APPROACH) {
          newPriority = decision.priority * modifiedWeights.approach;
        E} else if (decision.action === AIActionType.CIRCLE) {
          newPriority = decision.priority * modifiedWeights.circle;
        }
 
        return { ...decision, priority: newPriority };
      });
    }
 
    // Apply kill mode modifiers to boost aggression (Issue #enhance-ai-aggression)
    if (killModeActive) {
      // Map decisions to new array with modified priorities
      modifiedDecisions = modifiedDecisions.map((decision) => {
        // CRITICAL: Survival decisions (retreat for self-preservation) should NOT be affected by kill mode
        // Kill mode is about finishing the opponent, not about ignoring the AI's own safety
        // Survival retreats are identified by priority 20 OR reason containing survival keywords
        // Survival retreat detection with English and Korean keywords
        const SURVIVAL_REASON_KEYWORDS = [
          // English survival indicators (lowercase)
          "critical health",
          "high pain",
          "survival retreat",
          "emergency retreat",
          // Korean survival indicators
          "위급 상황",
          "고통 회피",
        ];
 
        const reasonLower = decision.reason.toLowerCase();
        const hasSurvivalKeyword = SURVIVAL_REASON_KEYWORDS.some((keyword) =>
          reasonLower.includes(keyword),
        );
 
        const isSurvivalRetreat =
          decision.action === AIActionType.RETREAT &&
          (decision.priority === 20 || hasSurvivalKeyword);
 
        if (isSurvivalRetreat) {
          // This is a survival retreat decision - preserve its priority
          return decision;
        }
 
        // Calculate base action weights for non-survival decisions
        const weights = {
          attack: decision.action === AIActionType.ATTACK ? 1.0 : 0.0,
          technique: decision.action === AIActionType.TECHNIQUE ? 1.0 : 0.0,
          defend: decision.action === AIActionType.DEFEND ? 1.0 : 0.0,
          retreat: decision.action === AIActionType.RETREAT ? 1.0 : 0.0,
        };
 
        // Apply kill mode modifiers
        const modifiedWeights = this.applyKillModeModifiers(
          weights,
          personality,
          true,
        );
 
        // Adjust priority based on modified weights
        let newPriority = decision.priority;
        Iif (decision.action === AIActionType.ATTACK) {
          newPriority = decision.priority * modifiedWeights.attack;
        } else if (decision.action === AIActionType.TECHNIQUE) {
          newPriority = decision.priority * modifiedWeights.technique;
        I} else if (decision.action === AIActionType.DEFEND) {
          newPriority = decision.priority * modifiedWeights.defend;
        I} else if (decision.action === AIActionType.RETREAT) {
          newPriority = decision.priority * modifiedWeights.retreat;
        }
 
        return { ...decision, priority: newPriority };
      });
 
      // Select highest priority decision from modified array
      const bestDecision = modifiedDecisions.reduce((best, current) =>
        current.priority > best.priority ? current : best,
      );
 
      // Build psychological pressure for Jeongbo (Issue #enhance-intelligence-operative-ai Phase 3)
      if (personality.archetype === PlayerArchetype.JEONGBO_YOWON) {
        this.buildPsychologicalPressure(bestDecision.action, now);
      }
 
      // Track consecutive attacks
      if (
        bestDecision.action === AIActionType.ATTACK ||
        bestDecision.action === AIActionType.TECHNIQUE
      ) {
        this.consecutiveAttacks++;
      } else {
        this.consecutiveAttacks = 0;
      }
 
      // Apply archetype behavior enforcement (Issue #enforce-distinct-combat-philosophies)
      // This ensures each archetype has immediately recognizable combat patterns in kill mode
      const enforcedDecision = enforceArchetypeBehavior(
        bestDecision,
        personality.archetype,
        context,
      );
 
      return enforcedDecision;
    }
 
    // Normal mode: Select highest priority decision (may have Jeongbo exploitation applied)
    const bestDecision = modifiedDecisions.reduce((best, current) =>
      current.priority > best.priority ? current : best,
    );
 
    // Build psychological pressure for Jeongbo (Issue #enhance-intelligence-operative-ai Phase 3)
    if (personality.archetype === PlayerArchetype.JEONGBO_YOWON) {
      this.buildPsychologicalPressure(bestDecision.action, now);
    }
 
    // Track consecutive attacks
    if (
      bestDecision.action === AIActionType.ATTACK ||
      bestDecision.action === AIActionType.TECHNIQUE
    ) {
      this.consecutiveAttacks++;
    } else {
      this.consecutiveAttacks = 0;
    }
 
    // Apply archetype behavior enforcement (Issue #enforce-distinct-combat-philosophies)
    // This ensures each archetype has immediately recognizable combat patterns
    const enforcedDecision = enforceArchetypeBehavior(
      bestDecision,
      personality.archetype,
      context,
    );
 
    return enforcedDecision;
  }
 
  /**
   * Evaluate survival tactics when critically low health
   *
   * **Korean Philosophy (생존 전략)**:
   * - Consider both health and pain levels
   * - Archetype affects retreat threshold and behavior
   * - Honor code (Musa) prevents retreat above threshold
   */
  private evaluateSurvival(
    context: CombatContext,
    personality: AIPersonality,
  ): AIDecision {
    const healthPercent = context.playerHealth / context.playerMaxHealth;
    const painLevel = context.recentDamageTaken;
 
    // Get archetype behavior profile
    const behavior = getArchetypeBehavior(personality.archetype);
 
    // Check critical survival condition: low health OR (moderate health + high pain)
    const isCritical = healthPercent < personality.tacticalRetreatThreshold;
    const isHighPain = healthPercent < 0.5 && painLevel > 50;
 
    if (isCritical || isHighPain) {
      // Honor code: Musa never retreats above their threshold (30%)
      Iif (
        behavior.honorCode &&
        healthPercent > behavior.retreatThreshold / 100
      ) {
        return {
          action: AIActionType.WAIT,
          priority: 0,
          reason: `Honor code prevents retreat: ${(healthPercent * 100).toFixed(1)}% (명예 규범)`,
        };
      }
 
      const retreatVector = this.calculateRetreatPosition(context);
 
      return {
        action: AIActionType.RETREAT,
        targetPosition: retreatVector,
        priority: 20, // Highest priority - must always override kill mode aggression
        reason: isCritical
          ? `Critical health: ${(healthPercent * 100).toFixed(1)}% (위급 상황)`
          : `High pain: ${painLevel.toFixed(0)} (고통 회피)`,
      };
    }
 
    return { action: AIActionType.WAIT, priority: 0, reason: "Health stable" };
  }
 
  /**
   * Evaluate counter-attack opportunity
   *
   * **Kill Mode Enhancement (결정타 반격)**:
   * All archetypes enhance counter behavior during kill mode based on philosophy:
   * - **Musa**: Increased counter frequency (honor demands swift response)
   * - **Amsalja**: Enhanced counter timing with precision strikes
   * - **Hacker**: Calculated counter-attacks (analytical opportunity)
   * - **Jeongbo Yowon**: Strategic counters (psychological advantage)
   * - **Jojik Pokryeokbae**: Opportunistic counters (dirty tactics)
   *
   * @param context - Combat context
   * @param personality - AI personality
   * @param killModeActive - Whether kill mode is active
   */
  private evaluateCounter(
    context: CombatContext,
    personality: AIPersonality,
    killModeActive: boolean = false,
  ): AIDecision {
    // Base counter chance affected by defense preference
    let counterChance = personality.defensePreference * 0.8;
    let counterPriority = 8;
 
    // Kill mode: Archetype-specific counter behavior enhancements
    Iif (killModeActive) {
      switch (personality.archetype) {
        case PlayerArchetype.MUSA:
          // Musa: Honor code demands swift aggressive counter
          counterChance = Math.min(0.95, counterChance + 0.3); // +30% counter chance
          counterPriority = 9; // Highest priority counter
          break;
 
        case PlayerArchetype.AMSALJA:
          // Amsalja: Precision counter-strikes for instant takedown
          counterChance = Math.min(0.9, counterChance + 0.25); // +25% counter chance
          counterPriority = 9; // Highest priority counter
          break;
 
        case PlayerArchetype.HACKER:
          // Hacker: Calculated counter with analytical precision
          counterChance = Math.min(0.85, counterChance + 0.15); // +15% counter chance
          counterPriority = 9; // Enhanced priority for analytical strike
          break;
 
        case PlayerArchetype.JEONGBO_YOWON:
          // Jeongbo Yowon: Strategic counter with psychological pressure
          counterChance = Math.min(0.8, counterChance + 0.2); // +20% counter chance
          counterPriority = 8; // Moderate priority increase
          break;
 
        case PlayerArchetype.JOJIK_POKRYEOKBAE:
          // Jojik: Opportunistic dirty counter
          counterChance = Math.min(0.85, counterChance + 0.25); // +25% counter chance
          counterPriority = 8; // Pragmatic priority
          break;
      }
    }
 
    // Use archetype-based max reach for counter distance check
    const maxReach = this.getArchetypeMaxReach(personality.archetype);
    const shouldCounter =
      Math.random() < counterChance && context.distanceToOpponent < maxReach;
 
    if (shouldCounter) {
      let killModeReason = "";
      Iif (killModeActive) {
        switch (personality.archetype) {
          case PlayerArchetype.MUSA:
            killModeReason = " - 명예 반격 (honor counter)";
            break;
          case PlayerArchetype.AMSALJA:
            killModeReason = " - 정밀 반격 (precision counter)";
            break;
          case PlayerArchetype.HACKER:
            killModeReason = " - 분석 반격 (analytical counter)";
            break;
          case PlayerArchetype.JEONGBO_YOWON:
            killModeReason = " - 전략 반격 (strategic counter)";
            break;
          case PlayerArchetype.JOJIK_POKRYEOKBAE:
            killModeReason = " - 기습 반격 (opportunistic counter)";
            break;
        }
      }
 
      return {
        action: AIActionType.COUNTER,
        priority: counterPriority,
        reason: `Opponent attacking - counter opportunity${killModeReason}`,
      };
    }
 
    return {
      action: AIActionType.DEFEND,
      priority: 6,
      reason: "Opponent attacking - defensive stance",
    };
  }
 
  /**
   * Evaluate counter-attack opportunity from limb exposure.
   *
   * **Korean**: 사지 노출 반격 평가 (Limb Exposure Counter Evaluation)
   *
   * Analyzes opportunities to exploit opponent's exposed limbs during technique
   * execution. This is higher priority than standard counters because it targets
   * specific anatomical vulnerabilities.
   *
   * **Defensive Archetype Priority**:
   * Defensive archetypes (high defensiveness) strongly favor counter-attacks:
   * - **Musa**: Honorable defense with precise counters (defensiveness ~0.7)
   * - **Amsalja**: Patient assassin waiting for openings (defensiveness ~0.6)
   * - **Jeongbo Yowon**: Analytical exploitation of weaknesses (defensiveness ~0.5)
   *
   * **Breaking Techniques**:
   * When allowsBreaking is true, AI can execute joint locks and limb breaks
   * for severe damage and mobility reduction.
   *
   * @param context - Combat context with positioning
   * @param personality - AI personality with archetype and defensiveness
   * @param counterOpportunity - Detected limb exposure opportunity
   * @param opponentVulnerability - Opponent's vulnerability multiplier
   * @returns Counter-attack decision with priority based on archetype
   *
   * @korean 사지노출반격평가
   */
  private evaluateLimbExposureCounter(
    context: CombatContext,
    personality: AIPersonality,
    counterOpportunity: CounterOpportunity,
    opponentVulnerability: number,
  ): AIDecision {
    // Base counter priority starts high (limb exposure is a prime opportunity)
    let counterPriority = 9;
 
    // Defensive archetypes prioritize counter-attacks significantly
    // Musa (defensiveness ~0.7): +2.1 bonus → priority 11+
    // Amsalja (defensiveness ~0.6): +1.8 bonus → priority 10+
    // Jeongbo (defensiveness ~0.5): +1.5 bonus → priority 10+
    const defensivenessBonus = personality.defensePreference * 3;
    counterPriority += defensivenessBonus;
 
    // Breaking opportunities are extremely high value
    if (counterOpportunity.allowsBreaking) {
      counterPriority += 2;
    }
 
    // High vulnerability multipliers increase priority
    if (opponentVulnerability > 2.0) {
      counterPriority += 1; // Severely overextended
    } else if (opponentVulnerability > 1.5) {
      counterPriority += 0.5; // Moderately vulnerable
    }
 
    // Check if AI has sufficient resources to execute counter
    const hasStamina = context.playerStamina > context.playerMaxStamina * 0.2;
    if (!hasStamina) {
      // Low stamina reduces priority but doesn't eliminate opportunity
      counterPriority -= 3;
    }
 
    // Distance check - counter must be executable at current range
    const maxCounterRange = 1.0; // 1 meter max for counter-attacks
    if (context.distanceToOpponent > maxCounterRange) {
      // Too far to execute counter
      return {
        action: AIActionType.WAIT,
        priority: 0,
        reason: `Limb exposed but too far: ${context.distanceToOpponent.toFixed(2)}m > ${maxCounterRange}m`,
      };
    }
 
    // Build descriptive reason with Korean translation
    const exposedLimbKorean = this.translateExposedLimb(
      counterOpportunity.exposedLimb,
    );
    const breakingNote = counterOpportunity.allowsBreaking
      ? " - 파쇄 가능 (breaking possible)"
      : "";
    const vulnerabilityNote = ` (취약성: ${opponentVulnerability.toFixed(1)}x)`;
 
    return {
      action: AIActionType.COUNTER,
      priority: counterPriority,
      reason: `Exposed limb counter: ${counterOpportunity.exposedLimb} (${exposedLimbKorean})${breakingNote}${vulnerabilityNote}`,
    };
  }
 
  /**
   * Translate exposed limb type to Korean.
   *
   * **Korean**: 노출 사지 번역 (Exposed Limb Translation)
   *
   * @param exposedLimb - English limb type identifier
   * @returns Korean translation
   *
   * @korean 노출사지번역
   */
  private translateExposedLimb(exposedLimb: ExposedLimbType): string {
    const translations: Record<ExposedLimbType, string> = {
      left_arm: "왼팔",
      right_arm: "오른팔",
      left_elbow: "왼팔꿈치",
      right_elbow: "오른팔꿈치",
      left_wrist: "왼손목",
      right_wrist: "오른손목",
      left_leg: "왼다리",
      right_leg: "오른다리",
      left_knee: "왼무릎",
      right_knee: "오른무릎",
      left_ankle: "왼발목",
      right_ankle: "오른발목",
    };
 
    return translations[exposedLimb];
  }
 
  /**
   * Evaluate combo initiation (fix for issue #2529467014)
   */
  private evaluateComboStart(
    context: CombatContext,
    personality: AIPersonality,
    comboSystem: AIComboSystem,
  ): AIDecision {
    // Check if combo system is already active
    Iif (comboSystem.isComboActive()) {
      return {
        action: AIActionType.WAIT,
        priority: 0,
        reason: "Combo already active",
      };
    }
 
    // Don't start combo if already in consecutive attacks
    if (this.consecutiveAttacks > 0) {
      return {
        action: AIActionType.WAIT,
        priority: 0,
        reason: "Combo cooldown",
      };
    }
 
    const hasResources =
      context.playerKi > context.playerMaxKi * 0.3 &&
      context.playerStamina > context.playerMaxStamina * 0.3;
 
    // Use archetype-based medium range (leg length) for combo distance check
    const mediumRange = this.getArchetypeMediumRange(personality.archetype);
    const goodDistance = context.distanceToOpponent < mediumRange;
    const comboChance = Math.random() < personality.comboTendency;
 
    if (hasResources && goodDistance && comboChance) {
      return {
        action: AIActionType.COMBO,
        priority: 7,
        reason: "Initiating combo sequence",
      };
    }
 
    return {
      action: AIActionType.WAIT,
      priority: 0,
      reason: "Combo conditions not met",
    };
  }
 
  /**
   * Select stance based on distance to opponent
   *
   * Chooses optimal stance for current combat range, prioritizing:
   * 1. Overlap between distance-optimal stances and archetype preferred stances
   * 2. Any distance-optimal stance if no overlap exists (expands tactical repertoire)
   * 3. Avoids switching to current stance
   *
   * **Distance Categories**:
   * - CLOSE (≤2 cells / 80px): GEON, JIN, LI, SON - Aggressive close-quarters stances
   * - MID (3-4 cells / 120-160px): GAM, TAE, GAN - Adaptive mid-range stances
   * - FAR (≥5 cells / 200px+): GAN, GON - Defensive distance stances
   *
   * @korean 거리별 자세 선택
   *
   * **Physics-First**: Distance parameter is in METERS.
   *
   * @param distance - Distance to opponent in meters
   * @param preferredStances - Archetype's preferred stances
   * @param currentStance - Current stance (to avoid redundant switches)
   * @returns Optimal stance for distance, or undefined if no valid options
   */
  private selectStanceForDistance(
    distance: number,
    preferredStances: readonly TrigramStance[],
    currentStance: TrigramStance,
    archetype: PlayerArchetype,
  ): TrigramStance | undefined {
    // Determine distance category using archetype-based physical attributes
    // Close = arm length (punching range), Medium = leg length (kicking range)
    const closeRange = this.getArchetypeCloseRange(archetype);
    const mediumRange = this.getArchetypeMediumRange(archetype);
 
    let distanceCategory: string;
    if (distance <= closeRange) {
      distanceCategory = "CLOSE";
    } else if (distance <= mediumRange) {
      distanceCategory = "MID";
    } else {
      distanceCategory = "FAR";
    }
 
    const optimalStances = DISTANCE_BASED_STANCES[distanceCategory];
 
    // Find overlap between optimal stances and preferred stances
    const candidates = optimalStances.filter((s) =>
      preferredStances.includes(s),
    );
 
    // If no overlap, use any optimal stance (expand tactical repertoire)
    const finalCandidates = candidates.length > 0 ? candidates : optimalStances;
 
    // Don't switch to current stance
    const filtered = finalCandidates.filter((s) => s !== currentStance);
 
    if (filtered.length === 0) {
      return undefined;
    }
 
    return filtered[Math.floor(Math.random() * filtered.length)];
  }
 
  /**
   * Evaluate stance change using TrigramSystem and distance-based selection
   *
   * **Korean Philosophy (자세 전환)**:
   * Uses I Ching-based trigram system to find optimal stance transitions.
   * Considers resource costs, counter-stance effectiveness, archetype preferences,
   * and distance-based tactical positioning.
   *
   * **Dynamic Stance Rotation (Issue #dynamic-ai-stance-rotation)**:
   * - Integrates distance-based stance selection for tactical variety
   * - Prioritizes counter-stances for opponent matchup advantage
   * - Expands tactical repertoire beyond archetype preferences when needed
   */
  private evaluateStanceChange(
    context: CombatContext,
    personality: AIPersonality,
    now: number,
  ): AIDecision {
    // Respect stance change cooldown
    if (now - this.lastStanceChange < this.stanceChangeCooldown) {
      return {
        action: AIActionType.WAIT,
        priority: 0,
        reason: "Stance change on cooldown",
      };
    }
 
    const behavior = getArchetypeBehavior(personality.archetype);
 
    // Apply stance fatigue modifier (Issue #dynamic-ai-stance-rotation Phase 4)
    // Increases stance switch probability based on time in current stance:
    // - After 10 seconds: +20% increase (1.2x multiplier)
    // - After 20 seconds: +50% increase (1.5x multiplier)
    const timeInStance = Math.max(0, context.stanceFatigue?.timeInStance ?? 0);
    const fatigueModifier = this.getStanceFatigueModifier(timeInStance);
    const adjustedSwitchFrequency = Math.min(
      0.95,
      personality.stanceSwitchFrequency * fatigueModifier,
    );
 
    // Single random check using fatigue-adjusted frequency to avoid compounding probability
    const shouldChange = Math.random() < adjustedSwitchFrequency;
    if (!shouldChange) {
      return {
        action: AIActionType.WAIT,
        priority: 0,
        reason:
          fatigueModifier > 1.0
            ? `Stance change deferred (fatigue: ${fatigueModifier.toFixed(2)}x, probability: ${(adjustedSwitchFrequency * 100).toFixed(1)}%)`
            : "No stance change needed",
      };
    }
 
    // Check if already in a preferred stance - if so, reduce change chance (but not completely)
    // This check only applies outside combat to avoid stance lock during active fighting
    const inPreferredStance = behavior.preferredStances.includes(
      context.playerStance,
    );
    if (
      inPreferredStance &&
      !context.isOpponentAttacking &&
      Math.random() < 0.6
    ) {
      // 60% chance to stay in preferred stance when not under immediate pressure
      // However, fatigue can override this (higher fatigue = more likely to switch anyway)
      // Use non-linear scaling for gradual, predictable override behavior:
      // - At 1.2x fatigue (10s): ~10% override chance
      // - At 1.5x fatigue (20s): ~25% override chance
      // - Caps at 80% to preserve some tactical consideration
      const fatigueOverrideProbability =
        fatigueModifier > 1.0
          ? Math.min(
              0.8,
              (fatigueModifier - 1.0) *
                AIDecisionTree.FATIGUE_OVERRIDE_SCALING_FACTOR,
            )
          : 0;
      const fatigueOverride =
        fatigueModifier > 1.2 && Math.random() < fatigueOverrideProbability;
      if (!fatigueOverride) {
        return {
          action: AIActionType.WAIT,
          priority: 0,
          reason: "Already in preferred stance (선호 자세 유지)",
        };
      }
    }
 
    // Create a minimal PlayerState object with only the properties actually used
    const playerState = {
      currentStance: context.playerStance,
      ki: context.playerKi,
      stamina: context.playerStamina,
      archetype: personality.archetype,
    } as unknown as PlayerState;
 
    // Priority 1: Try distance-based stance selection for tactical variety
    // Lower priority than attacks but competitive with approach/defense
    const distanceStance = this.selectStanceForDistance(
      context.distanceToOpponent,
      behavior.preferredStances,
      context.playerStance,
      personality.archetype,
    );
 
    if (
      distanceStance &&
      this.trigramSystem.canTransitionTo(
        context.playerStance,
        distanceStance,
        playerState,
      )
    ) {
      this.lastStanceChange = now;
      return {
        action: AIActionType.STANCE_CHANGE,
        targetStance: distanceStance,
        priority: 5, // Competitive with approach (4-6) but below attacks (7-10)
        reason: `Distance-optimal stance (거리 최적 자세: ${distanceStance})`,
      };
    }
 
    // Priority 2: Try counter-stance for opponent matchup
    const counterStance = this.trigramSystem.getCounterStance(
      context.opponentStance,
    );
    if (
      counterStance !== context.playerStance &&
      this.trigramSystem.canTransitionTo(
        context.playerStance,
        counterStance,
        playerState,
      )
    ) {
      this.lastStanceChange = now;
      return {
        action: AIActionType.STANCE_CHANGE,
        targetStance: counterStance,
        priority: 5, // Competitive with approach (4-6) but below attacks (7-10)
        reason: `Counter stance to ${context.opponentStance} (상극 대응)`,
      };
    }
 
    // Priority 3: Use TrigramSystem to recommend optimal stance
    const recommendedStance = this.trigramSystem.recommendStance(playerState);
 
    Eif (
      this.trigramSystem.canTransitionTo(
        context.playerStance,
        recommendedStance,
        playerState,
      )
    ) {
      this.lastStanceChange = now;
      return {
        action: AIActionType.STANCE_CHANGE,
        targetStance: recommendedStance,
        priority: 4, // Lower priority for general optimization
        reason: `Optimal stance transition via TrigramSystem (팔괘 전환)`,
      };
    }
 
    // Priority 4: Try archetype-preferred stance
    const preferredAvailable = behavior.preferredStances.find(
      (stance) =>
        stance !== context.playerStance &&
        this.trigramSystem.canTransitionTo(
          context.playerStance,
          stance,
          playerState,
        ),
    );
 
    if (preferredAvailable) {
      this.lastStanceChange = now;
      return {
        action: AIActionType.STANCE_CHANGE,
        targetStance: preferredAvailable,
        priority: 4, // Lower priority for preferred stance switch
        reason: `Switching to preferred stance (선호 자세 전환: ${preferredAvailable})`,
      };
    }
 
    // No viable stance change available
    return {
      action: AIActionType.WAIT,
      priority: 0,
      reason: "No viable stance transition",
    };
  }
 
  /**
   * Evaluate feint attack
   */
  private evaluateFeint(
    context: CombatContext,
    personality: AIPersonality,
  ): AIDecision {
    // Use archetype-based max reach for feint distance check
    const maxReach = this.getArchetypeMaxReach(personality.archetype);
    const shouldFeint =
      Math.random() < personality.feintChance &&
      context.distanceToOpponent < maxReach;
 
    if (shouldFeint) {
      return {
        action: AIActionType.FEINT,
        priority: 4,
        reason: "Feinting to bait opponent",
      };
    }
 
    return {
      action: AIActionType.WAIT,
      priority: 0,
      reason: "No feint opportunity",
    };
  }
 
  /**
   * Evaluate close range tactics with vital point targeting
   *
   * **Korean Philosophy (급소 공격)**:
   * At close range, AI targets specific vital points based on difficulty level.
   * Higher difficulty = more precise targeting of critical points.
   *
   * **Kill Mode Enhancement (결정타)**:
   * When kill mode is active, AI prioritizes finishing techniques with boosted priority.
   *
   * @param context - Combat context
   * @param personality - AI personality
   * @param killModeActive - Whether kill mode is active (opponent <30% health or vulnerable)
   */
  private evaluateCloseRange(
    context: CombatContext,
    personality: AIPersonality,
    killModeActive: boolean = false,
  ): AIDecision {
    const hasResources = context.playerKi > 10 && context.playerStamina > 15;
    const aggression = personality.aggressionLevel;
 
    // Select vital point target based on difficulty
    const targetVitalPoint = this.selectVitalPointTarget(context, personality);
 
    // Get Korean name for logging if vital point is selected
    const vitalPointName = targetVitalPoint
      ? (getVitalPointById(targetVitalPoint)?.names.korean ?? targetVitalPoint)
      : undefined;
 
    // Kill mode: Prioritize finishing attacks with maximum aggression
    if (killModeActive) {
      const killModeSuffix =
        personality.archetype === PlayerArchetype.MUSA
          ? " (결정타 - 압도적 공격)"
          : " (결정타 - 즉사 기술)";
 
      if (hasResources) {
        return {
          action: AIActionType.TECHNIQUE,
          targetVitalPoint,
          priority: targetVitalPoint ? 10 : 9, // Maximum priority - finish the fight
          reason: targetVitalPoint
            ? `Kill mode - finishing technique on vital point (급소 결정타: ${vitalPointName})${killModeSuffix}`
            : `Kill mode - finishing technique${killModeSuffix}`,
        };
      } else E{
        return {
          action: AIActionType.ATTACK,
          targetVitalPoint,
          priority: targetVitalPoint ? 9 : 8, // Very high priority
          reason: targetVitalPoint
            ? `Kill mode - finishing attack (결정타 급소: ${vitalPointName})${killModeSuffix}`
            : `Kill mode - finishing attack${killModeSuffix}`,
        };
      }
    }
 
    // Normal close range behavior - expert fighters attack aggressively
    // Higher base attack chance for aggressive AI (aggression * 0.95 instead of 0.8)
    // Use single random value to determine action type fairly
    const actionRoll = Math.random();
    const attackThreshold = aggression * 0.95;
    const techniqueThreshold = hasResources ? aggression * 0.5 : 0; // Additional threshold for techniques
 
    if (actionRoll < attackThreshold) {
      return {
        action: AIActionType.ATTACK,
        targetVitalPoint,
        priority: targetVitalPoint ? 8 : 7, // High priority - attacks win over stance changes
        reason: targetVitalPoint
          ? `Close range - vital point attack (급소 타격: ${vitalPointName})`
          : "Close range - aggressive strike",
      };
    } else if (
      actionRoll < attackThreshold + techniqueThreshold &&
      hasResources
    ) {
      return {
        action: AIActionType.TECHNIQUE,
        targetVitalPoint,
        priority: targetVitalPoint ? 8 : 7, // High priority for techniques too
        reason: targetVitalPoint
          ? `Close range - technique on vital point (급소 기술: ${vitalPointName})`
          : "Close range - technique execution",
      };
    } else {
      return {
        action: AIActionType.DEFEND,
        priority: 4,
        reason: "Close range - defensive posture (방어 자세)",
      };
    }
  }
 
  /**
   * Select vital point to target based on difficulty and stance
   *
   * **Korean Philosophy (급소 선택)**:
   * - Beginner AI: Random targeting or no specific target
   * - Intermediate AI: Favors easier vital points
   * - Advanced AI: Targets appropriate points for current stance
   * - Master AI: Targets critical points with high precision
   */
  private selectVitalPointTarget(
    context: CombatContext,
    personality: AIPersonality,
  ): string | undefined {
    // Guard: Ensure vital points are available
    Iif (KOREAN_VITAL_POINTS.length === 0) {
      return undefined;
    }
 
    // Check if AI attempts vital point targeting based on difficulty
    const targetChance = this.difficultyLevel * personality.aggressionLevel;
    if (Math.random() > targetChance) {
      return undefined; // No specific vital point target
    }
 
    // Filter vital points by effective stance
    const effectivePoints = KOREAN_VITAL_POINTS.filter((point) =>
      point.effectiveStances?.includes(context.playerStance),
    );
 
    Iif (effectivePoints.length === 0) {
      // Fallback to any vital point
      const randomIndex = Math.floor(
        Math.random() * KOREAN_VITAL_POINTS.length,
      );
      return KOREAN_VITAL_POINTS[randomIndex].id;
    }
 
    // Select based on difficulty level
    Iif (this.difficultyLevel < 0.3) {
      // Beginner: Random selection from effective points.
      // NOTE: This uses Math.random(), which is not seeded and thus not deterministic.
      // For reproducible AI behavior (e.g., in testing or balancing), consider using a seeded RNG.
      // Also, this "beginner" AI still filters by effective points (stance-appropriate), which may be more sophisticated than a true novice.
      // If true beginner behavior is desired, select from all KOREAN_VITAL_POINTS instead.
      const randomIndex = Math.floor(Math.random() * effectivePoints.length);
      return effectivePoints[randomIndex].id;
    } else if (this.difficultyLevel < 0.6) {
      // Intermediate: Prefer easier targets (lower difficulty)
      const easierPoints = effectivePoints.filter(
        (p) => p.targetingDifficulty < 0.7,
      );
 
      Eif (easierPoints.length > 0) {
        // Sort without mutating original array
        const sortedEasierPoints = [...easierPoints].sort(
          (a, b) => a.targetingDifficulty - b.targetingDifficulty,
        );
        return sortedEasierPoints[0].id;
      }
      return effectivePoints[0].id;
    } else {
      // Advanced/Master: Target high-value critical points
      const criticalPoints = effectivePoints.filter(
        (p) => p.severity === "critical" || p.severity === "major",
      );
 
      Eif (criticalPoints.length > 0) {
        // Sort without mutating original array
        const sortedCritical = [...criticalPoints].sort(
          (a, b) => (b.baseDamage ?? 0) - (a.baseDamage ?? 0),
        );
        return sortedCritical[0].id;
      }
 
      // Fallback to highest damage point (guaranteed to exist due to check at line 456)
      const sortedByDamage = [...effectivePoints].sort(
        (a, b) => (b.baseDamage ?? 0) - (a.baseDamage ?? 0),
      );
      return sortedByDamage[0]?.id ?? effectivePoints[0].id;
    }
  }
 
  /**
   * Calculate stance fatigue modifier for increased switching probability
   *
   * Applies time-based modifiers to encourage dynamic stance rotation:
   * - 0-10 seconds: No modifier (1.0x)
   * - 10-20 seconds: +20% increase (1.2x multiplier)
   * - 20+ seconds: +50% increase (1.5x multiplier)
   *
   * This ensures AI doesn't stay locked in one stance for extended periods,
   * promoting the use of all 8 trigram stances throughout combat.
   *
   * **Korean Philosophy (자세 피로도)**:
   * Remaining in one stance too long reduces tactical flexibility and
   * makes the fighter predictable. The Eight Trigram system requires
   * constant adaptation and flow between stances.
   *
   * @korean 자세 피로도 배율 계산
   *
   * @param timeInStance - Time in current stance in milliseconds
   * @returns Stance switch frequency multiplier (1.0 = no change, >1.0 = increased probability)
   */
  private getStanceFatigueModifier(timeInStance: number): number {
    if (timeInStance > 20000) {
      return 1.5; // 50% increase after 20 seconds
    }
    if (timeInStance > 10000) {
      return 1.2; // 20% increase after 10 seconds
    }
    return 1.0; // No modifier for first 10 seconds
  }
 
  /**
   * Get optimal combat range based on AI personality archetype
   *
   * Uses archetype behavior profiles to determine preferred combat distance.
   * **Physics-First**: Returns distance in METERS directly.
   *
   * @param personality - AI personality with archetype behavior
   * @param _context - Combat context (unused, kept for API compatibility)
   * @returns Optimal range in meters
   * @korean 최적 전투 거리 - 원형별 선호 거리 (미터)
   */
  private getOptimalRange(
    personality: AIPersonality,
    _context?: CombatContext,
  ): number {
    // Get archetype behavior profile
    const behavior = getArchetypeBehavior(personality.archetype);
 
    // Convert optimal range from grid cells to meters (1 cell ≈ 0.4m)
    // Physics-first: return directly in meters
    return behavior.optimalRange * 0.4;
  }
 
  /**
   * Evaluate approach tactics with archetype-specific behavior
   *
   * **Korean Philosophy (접근 전략)**:
   * - Musa charges directly (70% direct path)
   * - Amsalja uses flanking movements (40% diagonal approach)
   * - Hacker maintains optimal distance (prefers not to close too much)
   *
   * **Kill Mode Enhancement (결정타 접근)**:
   * All archetypes enhance movement speed in kill mode based on combat philosophy:
   * - **Musa**: Direct charging with leg shifts for maximum speed (40% faster)
   * - **Amsalja**: Swift stepping patterns for rapid positioning (30% faster)
   * - **Hacker**: Calculated approach for optimal strike position (20% faster)
   * - **Jeongbo Yowon**: Strategic positioning for control (25% faster)
   * - **Jojik Pokryeokbae**: Unpredictable rush for brutal finish (35% faster)
   *
   * @param context - Combat context
   * @param personality - AI personality
   * @param killModeActive - Whether kill mode is active
   */
  private evaluateApproach(
    context: CombatContext,
    personality: AIPersonality,
    killModeActive: boolean = false,
  ): AIDecision {
    const optimalRange = this.getOptimalRange(personality, context);
    const distance = context.distanceToOpponent;
 
    // If already at optimal range or closer, lower priority
    Iif (distance <= optimalRange * 1.2) {
      return {
        action: AIActionType.WAIT,
        priority: 0,
        reason: "Already at optimal range",
      };
    }
 
    // Apply archetype-specific movement bias
    let movementBias = this.getArchetypeMovementBias(personality.archetype);
 
    // Kill mode: Enhance movement speed for all archetypes based on philosophy
    if (killModeActive) {
      switch (personality.archetype) {
        case PlayerArchetype.MUSA:
          movementBias *= 1.4; // 40% faster closing speed with leg shifts
          break;
        case PlayerArchetype.AMSALJA:
          movementBias *= 1.3; // 30% faster with stepping patterns
          break;
        case PlayerArchetype.HACKER:
          movementBias *= 1.2; // 20% faster for calculated approach
          break;
        case PlayerArchetype.JEONGBO_YOWON:
          movementBias *= 1.25; // 25% faster for strategic positioning
          break;
        case PlayerArchetype.JOJIK_POKRYEOKBAE:
          movementBias *= 1.35; // 35% faster for unpredictable rush
          break;
      }
    }
 
    let approachPos: Position;
 
    // Archetype-specific approach patterns
    if (personality.archetype === PlayerArchetype.MUSA && Math.random() < 0.7) {
      // Musa: Direct charge 70% of the time (enhanced in kill mode)
      approachPos = this.calculateDirectApproach(context, killModeActive);
    } else if (
      personality.archetype === PlayerArchetype.AMSALJA &&
      Math.random() < 0.4
    ) {
      // Amsalja: Flanking approach 40% of the time (enhanced in kill mode)
      approachPos = this.calculateFlankingApproach(context, killModeActive);
    } else {
      // Default approach with slight randomization
      approachPos = this.calculateApproachPosition(context);
    }
 
    // Calculate priority based on distance from optimal range
    // Very far: priority ~6-7, moderate distance: priority ~5
    let basePriority = 4;
 
    // Kill mode: Increase approach priority for closing distance (archetype-dependent)
    if (killModeActive && distance > optimalRange * 1.5) {
      switch (personality.archetype) {
        case PlayerArchetype.MUSA:
        case PlayerArchetype.JOJIK_POKRYEOKBAE:
          basePriority = 6; // Aggressive approach
          break;
        case PlayerArchetype.AMSALJA:
          basePriority = 6; // Swift approach for takedown
          break;
        case PlayerArchetype.HACKER:
        case PlayerArchetype.JEONGBO_YOWON:
          basePriority = 5; // Calculated/strategic approach
          break;
      }
    }
 
    const distanceRatio = Math.min(2, (distance - optimalRange) / optimalRange);
    const priorityBoost = distanceRatio * movementBias * 0.8;
    const finalPriority = basePriority + priorityBoost;
 
    let killModeReason = "";
    if (killModeActive) {
      switch (personality.archetype) {
        case PlayerArchetype.MUSA:
          killModeReason = " - 돌격 (charging)";
          break;
        case PlayerArchetype.AMSALJA:
          killModeReason = " - 신속 접근 (swift approach)";
          break;
        case PlayerArchetype.HACKER:
          killModeReason = " - 분석 접근 (calculated approach)";
          break;
        case PlayerArchetype.JEONGBO_YOWON:
          killModeReason = " - 전략 접근 (strategic approach)";
          break;
        case PlayerArchetype.JOJIK_POKRYEOKBAE:
          killModeReason = " - 돌진 (rush)";
          break;
      }
    }
 
    return {
      action: AIActionType.APPROACH,
      targetPosition: approachPos,
      priority: Math.min(9, finalPriority), // Allow higher cap in kill mode
      reason: `Moving closer (distance: ${Math.round(
        distance,
      )}, optimal: ${optimalRange})${killModeReason}`,
    };
  }
 
  /**
   * Get archetype-specific movement bias multipliers
   *
   * Applies movement pattern modifiers based on archetype behavior profiles:
   * - Aggressive: High forward pressure (2.0x)
   * - Evasive: Moderate mobility (1.5x)
   * - Analytical: Conservative approach (0.8x-1.0x)
   * - Unpredictable: Variable movement (1.3x)
   *
   * @korean 원형별 이동 성향
   */
  private getArchetypeMovementBias(archetype: PlayerArchetype): number {
    const behavior = getArchetypeBehavior(archetype);
 
    switch (behavior.movementPattern) {
      case "aggressive": // Musa - aggressive forward movement
        return 2.0;
      case "evasive": // Amsalja - high mobility, flanking preference
        return 1.5;
      case "analytical": // Hacker, Jeongbo - calculated approach
        return archetype === PlayerArchetype.HACKER ? 0.8 : 1.0;
      case "unpredictable": // Jojik - variable patterns
        return 1.3;
      default:
        return 1.0;
    }
  }
 
  /**
   * Calculate direct approach position (straight line to opponent)
   * Used primarily by Musa archetype for charging attacks
   *
   * **Kill Mode Enhancement (결정타 돌격)**:
   * - Larger step size for faster closing with leg shifts
   * - Aggressive stride pattern for maximum forward momentum
   *
   * **Physics-First**: All calculations in METERS.
   *
   * @param context - Combat context
   * @param killModeActive - Whether kill mode is active
   */
  private calculateDirectApproach(
    context: CombatContext,
    killModeActive: boolean = false,
  ): Position {
    const dx = context.opponentPosition.x - context.playerPosition.x;
    const dy = context.opponentPosition.y - context.playerPosition.y;
    const distance = Math.sqrt(dx * dx + dy * dy);
 
    // All thresholds in meters
    const minDistance = AI_MOVEMENT_METERS.MIN_DISTANCE_THRESHOLD;
 
    // If already very close to the opponent, hold position (avoid erratic movement)
    Iif (distance < minDistance) {
      return this.clampToArenaBoundsMeters(context.playerPosition, context);
    }
 
    // Step size in meters
    const baseStepSize = AI_MOVEMENT_METERS.STEP_SIZE;
 
    // Kill mode: Enhanced step size for faster charging with leg shifts
    const stepSize = killModeActive
      ? Math.min(baseStepSize * 1.5, distance) // 50% larger steps (leg shift technique)
      : Math.min(baseStepSize, distance);
 
    // Move straight toward opponent with enhanced step size in kill mode
    return this.clampToArenaBoundsMeters(
      {
        x: context.playerPosition.x + (dx / distance) * stepSize,
        y: context.playerPosition.y + (dy / distance) * stepSize,
      },
      context,
    );
  }
 
  /**
   * Calculate flanking approach position (diagonal/side approach)
   * Used primarily by Amsalja archetype for stealth positioning
   *
   * **Kill Mode Enhancement (결정타 측면 공격)**:
   * - Tighter flanking angle for more aggressive positioning
   * - Swift stepping pattern for rapid side movement
   *
   * **Physics-First**: All calculations in METERS.
   *
   * @param context - Combat context
   * @param killModeActive - Whether kill mode is active
   */
  private calculateFlankingApproach(
    context: CombatContext,
    killModeActive: boolean = false,
  ): Position {
    const dx = context.opponentPosition.x - context.playerPosition.x;
    const dy = context.opponentPosition.y - context.playerPosition.y;
    const distance = Math.sqrt(dx * dx + dy * dy);
 
    // All thresholds in meters
    const minDistance = AI_MOVEMENT_METERS.MIN_DISTANCE_THRESHOLD;
 
    // If distance is too small, return player's current position (avoid erratic movement)
    Iif (distance < minDistance) {
      return this.clampToArenaBoundsMeters(context.playerPosition, context);
    }
 
    // Flank offset in meters
    const baseFlankOffset =
      AI_MOVEMENT_METERS.FLANK_OFFSET_BASE +
      Math.random() * AI_MOVEMENT_METERS.FLANK_OFFSET_RANDOM;
 
    // Kill mode: Tighter flanking for more aggressive positioning
    const flankOffset = killModeActive
      ? baseFlankOffset * 0.7 // 30% closer flank (swift stepping)
      : baseFlankOffset;
 
    const perpX = -dy / distance; // Perpendicular vector
    const perpY = dx / distance;
    const flankSide = Math.random() < 0.5 ? 1 : -1; // Random side
 
    return this.clampToArenaBoundsMeters(
      {
        x: context.opponentPosition.x + perpX * flankOffset * flankSide,
        y: context.opponentPosition.y + perpY * flankOffset * flankSide,
      },
      context,
    );
  }
 
  /**
   * Clamp position to arena boundaries with proper margins
   * Centralizes boundary validation logic for all movement calculations
   *
   * **Physics-First**: Works entirely in METERS using worldWidthMeters/worldDepthMeters.
   * Arena is centered at origin (0,0), so bounds are -halfWidth to +halfWidth.
   *
   * @param position - Position to clamp (in meters)
   * @param context - Combat context with arena dimensions in meters
   */
  private clampToArenaBoundsMeters(
    position: Position,
    context: CombatContext,
  ): Position {
    // Arena is centered at origin, half dimensions define bounds
    const halfWidth = context.arenaBounds.worldWidthMeters / 2;
    const halfDepth = context.arenaBounds.worldDepthMeters / 2;
 
    // Margins in meters for character collision
    const marginX = AI_MOVEMENT_METERS.ARENA_MARGIN_X;
    const marginY = AI_MOVEMENT_METERS.ARENA_MARGIN_Y;
 
    return {
      x: Math.max(
        -halfWidth + marginX,
        Math.min(halfWidth - marginX, position.x),
      ),
      y: Math.max(
        -halfDepth + marginY,
        Math.min(halfDepth - marginY, position.y),
      ),
    };
  }
 
  /**
   * Evaluate mid-range tactics with distance awareness
   *
   * **Korean Philosophy (중거리 전술)**:
   * - Considers optimal range for archetype
   * - Hacker prefers to maintain this range (analytical pattern)
   * - Jeongbo uses strategic timing and analysis
   * - Others may close or open distance based on situation
   */
  private evaluateMidRange(
    context: CombatContext,
    personality: AIPersonality,
  ): AIDecision {
    const hasResources = context.playerKi > context.playerMaxKi * 0.3;
    const optimalRange = this.getOptimalRange(personality, context);
    const distance = context.distanceToOpponent;
    const tacticRoll = Math.random();
    const behavior = getArchetypeBehavior(personality.archetype);
 
    // Threshold for being "at optimal range" - 0.5 meters tolerance
    const optimalRangeThreshold = 0.5; // meters
 
    // Archetype-specific mid-range behavior based on movement pattern
    Iif (
      behavior.movementPattern === "analytical" &&
      Math.abs(distance - optimalRange) < optimalRangeThreshold
    ) {
      // Analytical archetypes (Hacker, Jeongbo) at ideal range - maintain position
      const circlePos = this.calculateCirclePosition(context);
      const archetypeName =
        personality.archetype === PlayerArchetype.HACKER ? "사이버" : "정보";
      return {
        action: AIActionType.CIRCLE,
        targetPosition: circlePos,
        priority: 6,
        reason: `${archetypeName} maintaining optimal mid-range (${archetypeName} 위치 유지)`,
      };
    }
 
    // Too far from optimal range - approach
    Eif (distance > optimalRange * 1.5) {
      const approachPos = this.calculateApproachPosition(context);
      return {
        action: AIActionType.APPROACH,
        targetPosition: approachPos,
        priority: 5,
        reason: "Moving to optimal range (최적 거리로 이동)",
      };
    }
 
    // Too close to optimal range - analytical archetypes create space
    if (
      distance < optimalRange * 0.7 &&
      behavior.movementPattern === "analytical"
    ) {
      const retreatPos = this.calculateRetreatPosition(context);
      return {
        action: AIActionType.RETREAT,
        targetPosition: retreatPos,
        priority: 5,
        reason: "Creating tactical space (거리 확보)",
      };
    }
 
    // Unpredictable archetype (Jojik) - randomize tactics
    if (behavior.movementPattern === "unpredictable") {
      const randomAction =
        tacticRoll < 0.33
          ? "attack"
          : tacticRoll < 0.66
            ? "circle"
            : "approach";
      if (randomAction === "attack" && hasResources) {
        return {
          action: AIActionType.TECHNIQUE,
          priority: 5,
          reason: "Unpredictable attack (예측불가 공격)",
        };
      } else if (randomAction === "circle") {
        const circlePos = this.calculateCirclePosition(context);
        return {
          action: AIActionType.CIRCLE,
          targetPosition: circlePos,
          priority: 4,
          reason: "Unpredictable movement (예측불가 이동)",
        };
      }
    }
 
    // At good range - mix of techniques and repositioning
    if (tacticRoll < 0.3 && hasResources) {
      return {
        action: AIActionType.TECHNIQUE,
        priority: 5,
        reason: "Mid-range technique (중거리 기술)",
      };
    } else if (tacticRoll < 0.6) {
      const circlePos = this.calculateCirclePosition(context);
      return {
        action: AIActionType.CIRCLE,
        targetPosition: circlePos,
        priority: 4,
        reason: "Tactical repositioning (전술적 이동)",
      };
    } else {
      const approachPos = this.calculateApproachPosition(context);
      return {
        action: AIActionType.APPROACH,
        targetPosition: approachPos,
        priority: 4,
        reason: "Moving to optimal range (최적 거리로 이동)",
      };
    }
  }
 
  /**
   * Evaluate defensive tactics
   */
  private evaluateDefense(
    context: CombatContext,
    personality: AIPersonality,
  ): AIDecision {
    const shouldDefend =
      Math.random() < personality.defensePreference &&
      context.recentDamageTaken > 20;
 
    if (shouldDefend) {
      return {
        action: AIActionType.DEFEND,
        priority: 6,
        reason: "Defensive response to damage",
      };
    }
 
    return {
      action: AIActionType.WAIT,
      priority: 0,
      reason: "No defensive need",
    };
  }
 
  /**
   * Decide combo action
   */
  private decideComboAction(
    _context: CombatContext,
    _personality: AIPersonality,
  ): AIDecision {
    return {
      action: AIActionType.COMBO,
      priority: 9,
      reason: "Continuing active combo",
    };
  }
 
  /**
   * Calculate retreat position
   *
   * **Physics-First**: All calculations in METERS.
   */
  private calculateRetreatPosition(context: CombatContext): Position {
    const dx = context.playerPosition.x - context.opponentPosition.x;
    const dy = context.playerPosition.y - context.opponentPosition.y;
    const distance = Math.sqrt(dx * dx + dy * dy);
 
    // All thresholds in meters
    const minDistance = AI_MOVEMENT_METERS.MIN_DISTANCE_THRESHOLD;
    // Retreat distance in meters (1.5m)
    const retreatDistance = 1.5;
 
    // If distance is too small, retreat in a default direction (away from center)
    Iif (distance < minDistance) {
      return this.clampToArenaBoundsMeters(
        {
          x: context.playerPosition.x + retreatDistance,
          y: context.playerPosition.y,
        },
        context,
      );
    }
 
    // Normalize and retreat
    const nx = dx / distance;
    const ny = dy / distance;
 
    return this.clampToArenaBoundsMeters(
      {
        x: context.playerPosition.x + nx * retreatDistance,
        y: context.playerPosition.y + ny * retreatDistance,
      },
      context,
    );
  }
 
  /**
   * Calculate approach position
   *
   * **Physics-First**: All calculations in METERS.
   */
  private calculateApproachPosition(context: CombatContext): Position {
    // Offset in meters (0.8m max horizontal, 0.6m max vertical)
    const offsetX = (Math.random() - 0.5) * 0.8;
    const offsetY = (Math.random() - 0.5) * 0.6;
 
    return this.clampToArenaBoundsMeters(
      {
        x: context.opponentPosition.x + offsetX,
        y: context.opponentPosition.y + offsetY,
      },
      context,
    );
  }
 
  /**
   * Calculate circle position
   *
   * **Physics-First**: All calculations in METERS.
   */
  private calculateCirclePosition(context: CombatContext): Position {
    const angle = Math.atan2(
      context.opponentPosition.y - context.playerPosition.y,
      context.opponentPosition.x - context.playerPosition.x,
    );
    // Circle radius in meters (1.5m base + 0.5m random)
    const circleRadius = 1.5 + Math.random() * 0.5;
 
    return this.clampToArenaBoundsMeters(
      {
        x:
          context.opponentPosition.x +
          Math.cos(angle + Math.PI / 2) * circleRadius,
        y:
          context.opponentPosition.y +
          Math.sin(angle + Math.PI / 2) * circleRadius,
      },
      context,
    );
  }
 
  /**
   * Reset decision state
   */
  reset(): void {
    this.lastDecisionTime = 0;
    this.consecutiveAttacks = 0;
    this.lastStanceChange = 0;
    // Reset psychological pressure tracking (Issue #enhance-intelligence-operative-ai Phase 3)
    this.psychologicalPressure = 0;
    this.lastPressureActionTime = 0;
  }
}