All files / systems/ai DecisionTree.ts

80.6% Statements 212/263
72.19% Branches 135/187
83.33% Functions 30/36
80.84% Lines 211/261

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                                                24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x                                                                                                             157x 157x 157x 157x 157x       157x   157x     24x 24x           24x 24x     157x               239x                             95x     95x 95x                               2459x     2459x         2459x 2459x 1384x                 1075x     1075x         1075x     1075x 1075x     1075x     1075x 1x       1075x 286x       1075x     1075x 304x       1075x   216x 859x   771x     88x       1075x     1075x 3816x       1075x       44x   1031x     1075x                             1075x 1075x     1075x     1075x 1075x   1075x   11x               11x   11x                   1064x                     1x     1x               1x                               286x                 286x                 286x     286x 286x   286x 141x             145x                                         1075x 127x             948x 948x 646x             302x       302x 302x   115x                 187x             187x     187x           187x                                                             187x   187x                               304x     304x 87x             217x                                   216x 216x     216x     216x       216x 135x               81x 43x                 38x                                           216x         216x 216x 114x       102x 7140x     102x                 102x           1x 1x 101x   24x 267x     24x   24x 255x   24x         77x 1557x     77x   77x 1588x   77x                                       1934x     1934x     1934x                             771x 771x     771x                 771x       771x   500x 271x   15x     256x         771x 771x 771x 771x   771x                                           771x   771x   683x   36x   51x   1x                     500x 500x 500x     500x         500x 500x                           15x 15x 15x     15x         15x 15x 15x 15x   15x                                 869x                                                             88x 88x 88x 88x 88x     88x   59x 59x   59x                 29x 18x 18x                 11x                     11x                                       11x 1x         10x 5x 5x             5x 5x                                 1075x     1075x 44x             1031x                                                 11x 11x 11x     11x                       11x 11x 11x   11x                         279x 279x   279x                         64x       64x   64x                                                                                                                                     448x 448x 448x      
/**
 * 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 { PlayerState } from "@/systems/player";
import { TrigramSystem } from "@/systems/TrigramSystem";
import {
  KOREAN_VITAL_POINTS,
  getVitalPointById,
} from "@/systems/vitalpoint/KoreanVitalPoints";
import { Position, TrigramStance, PlayerArchetype } from "@/types";
import { DifficultyParameters } from "./AdaptiveDifficulty";
import { AIPersonality, getArchetypeBehavior } from "./AIPersonality";
import { AIComboSystem } from "./ComboSystem";
 
/**
 * AI action types
 */
export enum AIActionType {
  ATTACK = "attack",
  TECHNIQUE = "technique",
  DEFEND = "defend",
  COUNTER = "counter",
  RETREAT = "retreat",
  APPROACH = "approach",
  CIRCLE = "circle",
  STANCE_CHANGE = "stance_change",
  FEINT = "feint",
  WAIT = "wait",
  COMBO = "combo",
}
 
/**
 * AI decision result
 */
export interface AIDecision {
  readonly action: AIActionType;
  readonly targetPosition?: Position;
  readonly targetStance?: TrigramStance;
  readonly targetVitalPoint?: string; // ID of vital point to target
  readonly priority: number; // 0-10: Decision confidence
  readonly reason: string; // For debugging/analysis
}
 
/**
 * Combat context for decision making
 */
export interface CombatContext {
  readonly playerPosition: Position;
  readonly opponentPosition: Position;
  readonly playerHealth: number;
  readonly playerMaxHealth: number;
  readonly playerKi: number;
  readonly playerMaxKi: number;
  readonly playerStamina: number;
  readonly playerMaxStamina: number;
  readonly opponentHealth: number;
  readonly opponentStance: TrigramStance;
  readonly playerStance: TrigramStance;
  readonly distanceToOpponent: number;
  readonly timeInMatch: number;
  readonly isOpponentAttacking: boolean;
  readonly recentDamageTaken: number;
  readonly arenaBounds: {
    readonly x: number;
    readonly y: number;
    readonly width: number;
    readonly height: number;
  };
}
 
/**
 * 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
 */
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
 
  // 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)
 
  // Movement constants
  private static readonly MOVE_STEP_SIZE = 50; // Fixed movement step size in pixels
  private static readonly MIN_DISTANCE_THRESHOLD = 5; // Minimum distance to avoid division by zero
  
  /**
   * Arena boundary margins - exported for test validation
   * These values represent the player character size/collision margins
   */
  public static readonly ARENA_MARGIN_X = 60; // Horizontal boundary margin
  public static readonly ARENA_MARGIN_Y = 180; // Vertical boundary margin
 
  constructor() {
    this.trigramSystem = new TrigramSystem();
  }
 
  /**
   * 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);
    }
  }
 
  /**
   * 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;
 
    // 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
    const optimalRange = this.getOptimalRange(personality);
    const distance = context.distanceToOpponent;
 
    // 1. Critical health - survival priority
    decisions.push(this.evaluateSurvival(context, personality));
 
    // 2. Counter-attack opportunity
    if (context.isOpponentAttacking) {
      decisions.push(this.evaluateCounter(context, personality));
    }
 
    // 3. Combo initiation (only if at reasonable distance)
    if (distance < optimalRange * 1.5) {
      decisions.push(this.evaluateComboStart(context, personality, comboSystem));
    }
 
    // 4. Stance transition
    decisions.push(this.evaluateStanceChange(context, personality, now));
 
    // 5. Feint attack (only at mid-close range)
    if (distance < optimalRange * 1.8) {
      decisions.push(this.evaluateFeint(context, personality));
    }
 
    // 6. Distance-based tactics (archetype-aware ranges)
    if (distance < optimalRange * 1.2) {
      // Close to optimal range - use close-range tactics including vital point targeting
      decisions.push(this.evaluateCloseRange(context, personality));
    } else if (distance > optimalRange * 1.8) {
      // Too far - need to approach
      decisions.push(this.evaluateApproach(context, personality));
    } else {
      // Mid-range - good tactical position
      decisions.push(this.evaluateMidRange(context, personality));
    }
 
    // 7. Defensive positioning
    decisions.push(this.evaluateDefense(context, personality));
 
    // Select highest priority decision
    const bestDecision = decisions.reduce((best, current) =>
      current.priority > best.priority ? current : best
    );
 
    // Track consecutive attacks
    if (
      bestDecision.action === AIActionType.ATTACK ||
      bestDecision.action === AIActionType.TECHNIQUE
    ) {
      this.consecutiveAttacks++;
    } else {
      this.consecutiveAttacks = 0;
    }
 
    return bestDecision;
  }
 
  /**
   * 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: 10, // Highest priority
        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
   */
  private evaluateCounter(
    context: CombatContext,
    personality: AIPersonality
  ): AIDecision {
    const shouldCounter =
      Math.random() < personality.defensePreference * 0.8 &&
      context.distanceToOpponent < 150;
 
    Iif (shouldCounter) {
      return {
        action: AIActionType.COUNTER,
        priority: 8,
        reason: "Opponent attacking - counter opportunity",
      };
    }
 
    return {
      action: AIActionType.DEFEND,
      priority: 6,
      reason: "Opponent attacking - defensive stance",
    };
  }
 
  /**
   * 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
    Iif (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;
 
    const goodDistance = context.distanceToOpponent < 130;
    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",
    };
  }
 
  /**
   * Evaluate stance change using TrigramSystem
   *
   * **Korean Philosophy (자세 전환)**:
   * Uses I Ching-based trigram system to find optimal stance transitions.
   * Considers resource costs, counter-stance effectiveness, and archetype preferences.
   * Each archetype has favored stances that they switch to more frequently.
   */
  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 shouldChange = Math.random() < personality.stanceSwitchFrequency;
    if (!shouldChange) {
      return {
        action: AIActionType.WAIT,
        priority: 0,
        reason: "No stance change needed",
      };
    }
 
    const behavior = getArchetypeBehavior(personality.archetype);
    
    // 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
      return {
        action: AIActionType.WAIT,
        priority: 0,
        reason: "Already in preferred stance (선호 자세 유지)",
      };
    }
 
    // Use TrigramSystem to recommend optimal stance
    // Create a minimal PlayerState object with only the properties actually used by recommendStance
    const playerState = {
      currentStance: context.playerStance,
      ki: context.playerKi,
      stamina: context.playerStamina,
      archetype: personality.archetype,
    } as unknown as PlayerState;
 
    const recommendedStance = this.trigramSystem.recommendStance(playerState);
 
    // Check if we can afford the transition
    const canTransition = this.trigramSystem.canTransitionTo(
      context.playerStance,
      recommendedStance,
      playerState
    );
 
    Iif (!canTransition) {
      // Try archetype-preferred stance or counter-stance
      const preferredAvailable = behavior.preferredStances.find(
        (stance) => this.trigramSystem.canTransitionTo(context.playerStance, stance, playerState)
      );
      
      if (preferredAvailable) {
        this.lastStanceChange = now;
        return {
          action: AIActionType.STANCE_CHANGE,
          targetStance: preferredAvailable,
          priority: 6,
          reason: `Switching to preferred stance (선호 자세 전환: ${preferredAvailable})`,
        };
      }
      
      // Fallback to counter-stance
      const counterStance = this.selectCounterStance(
        context.opponentStance,
        personality
      );
 
      this.lastStanceChange = now;
      return {
        action: AIActionType.STANCE_CHANGE,
        targetStance: counterStance,
        priority: 5,
        reason: `Counter stance to ${context.opponentStance} (급소 대응)`,
      };
    }
 
    this.lastStanceChange = now;
 
    return {
      action: AIActionType.STANCE_CHANGE,
      targetStance: recommendedStance,
      priority: 6,
      reason: `Optimal stance transition via TrigramSystem (팔괘 전환)`,
    };
  }
 
  /**
   * Evaluate feint attack
   */
  private evaluateFeint(
    context: CombatContext,
    personality: AIPersonality
  ): AIDecision {
    const shouldFeint =
      Math.random() < personality.feintChance &&
      context.distanceToOpponent < 180;
 
    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.
   */
  private evaluateCloseRange(
    context: CombatContext,
    personality: AIPersonality
  ): 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;
 
    if (Math.random() < aggression * 0.8) {
      return {
        action: AIActionType.ATTACK,
        targetVitalPoint,
        priority: targetVitalPoint ? 7 : 6,
        reason: targetVitalPoint
          ? `Close range - vital point attack (급소 타격: ${vitalPointName})`
          : "Close range - aggressive strike",
      };
    } else if (Math.random() < aggression * 0.9 && hasResources) {
      return {
        action: AIActionType.TECHNIQUE,
        targetVitalPoint,
        priority: targetVitalPoint ? 6 : 5,
        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
    if (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;
    }
  }
 
  /**
   * Get optimal combat range based on AI personality archetype
   * 
   * Uses archetype behavior profiles to determine preferred combat distance.
   * Range is converted from cell units to pixels (1 cell = ~40px).
   * 
   * @korean 최적 전투 거리 - 원형별 선호 거리
   */
  private getOptimalRange(personality: AIPersonality): number {
    const CELL_SIZE = 40; // Size of one grid cell in pixels
    
    // Get archetype behavior profile
    const behavior = getArchetypeBehavior(personality.archetype);
    
    // Convert cell units to pixels
    return behavior.optimalRange * CELL_SIZE;
  }
 
  /**
   * 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)
   */
  private evaluateApproach(
    context: CombatContext,
    personality: AIPersonality
  ): AIDecision {
    const optimalRange = this.getOptimalRange(personality);
    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
    const movementBias = this.getArchetypeMovementBias(personality.archetype);
    let approachPos: Position;
 
    // Archetype-specific approach patterns
    if (personality.archetype === PlayerArchetype.MUSA && Math.random() < 0.7) {
      // Musa: Direct charge 70% of the time
      approachPos = this.calculateDirectApproach(context);
    } else if (personality.archetype === PlayerArchetype.AMSALJA && Math.random() < 0.4) {
      // Amsalja: Flanking approach 40% of the time
      approachPos = this.calculateFlankingApproach(context);
    } 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
    const basePriority = 4;
    const distanceRatio = Math.min(2, (distance - optimalRange) / optimalRange);
    const priorityBoost = distanceRatio * movementBias * 0.8;
    const finalPriority = basePriority + priorityBoost;
 
    return {
      action: AIActionType.APPROACH,
      targetPosition: approachPos,
      priority: Math.min(8, finalPriority), // Cap at 8 to allow survival/critical actions to override
      reason: `Moving closer (distance: ${Math.round(
        distance
      )}, optimal: ${optimalRange})`,
    };
  }
 
  /**
   * 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
   */
  private calculateDirectApproach(context: CombatContext): 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);
 
    // If already very close to the opponent, hold position (avoid erratic movement)
    Iif (distance < AIDecisionTree.MIN_DISTANCE_THRESHOLD) {
      return this.clampToArenaBounds(context.playerPosition, context.arenaBounds);
    }
 
    // Move straight toward opponent with fixed step size for consistent movement speed
    const step = Math.min(AIDecisionTree.MOVE_STEP_SIZE, distance);
    return this.clampToArenaBounds(
      {
        x: context.playerPosition.x + (dx / distance) * step,
        y: context.playerPosition.y + (dy / distance) * step,
      },
      context.arenaBounds
    );
  }
 
  /**
   * Calculate flanking approach position (diagonal/side approach)
   * Used primarily by Amsalja archetype for stealth positioning
   */
  private calculateFlankingApproach(context: CombatContext): 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);
 
    // If distance is too small, return player's current position (avoid erratic movement)
    Iif (distance < AIDecisionTree.MIN_DISTANCE_THRESHOLD) {
      return this.clampToArenaBounds(context.playerPosition, context.arenaBounds);
    }
 
    // Add perpendicular offset for flanking (40-60 pixels to the side)
    const flankOffset = 40 + Math.random() * 20;
    const perpX = -dy / distance; // Perpendicular vector
    const perpY = dx / distance;
    const flankSide = Math.random() < 0.5 ? 1 : -1; // Random side
 
    return this.clampToArenaBounds(
      {
        x: context.opponentPosition.x + perpX * flankOffset * flankSide,
        y: context.opponentPosition.y + perpY * flankOffset * flankSide,
      },
      context.arenaBounds
    );
  }
 
  /**
   * Clamp position to arena boundaries with proper margins
   * Centralizes boundary validation logic for all movement calculations
   */
  private clampToArenaBounds(
    position: Position,
    arenaBounds: { readonly x: number; readonly y: number; readonly width: number; readonly height: number }
  ): Position {
    return {
      x: Math.max(
        arenaBounds.x,
        Math.min(
          arenaBounds.x + arenaBounds.width - AIDecisionTree.ARENA_MARGIN_X,
          position.x
        )
      ),
      y: Math.max(
        arenaBounds.y,
        Math.min(
          arenaBounds.y + arenaBounds.height - AIDecisionTree.ARENA_MARGIN_Y,
          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);
    const distance = context.distanceToOpponent;
    const tacticRoll = Math.random();
    const behavior = getArchetypeBehavior(personality.archetype);
 
    // Archetype-specific mid-range behavior based on movement pattern
    if (behavior.movementPattern === "analytical" && Math.abs(distance - optimalRange) < 50) {
      // 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
    if (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
    Iif (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
    Iif (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
   */
  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);
 
    // If distance is too small, retreat in a default direction (away from center)
    Iif (distance < AIDecisionTree.MIN_DISTANCE_THRESHOLD) {
      const retreatDistance = 150;
      return this.clampToArenaBounds(
        {
          x: context.playerPosition.x + retreatDistance,
          y: context.playerPosition.y,
        },
        context.arenaBounds
      );
    }
 
    // Normalize and retreat
    const retreatDistance = 150;
    const nx = dx / distance;
    const ny = dy / distance;
 
    return this.clampToArenaBounds(
      {
        x: context.playerPosition.x + nx * retreatDistance,
        y: context.playerPosition.y + ny * retreatDistance,
      },
      context.arenaBounds
    );
  }
 
  /**
   * Calculate approach position
   */
  private calculateApproachPosition(context: CombatContext): Position {
    const offsetX = (Math.random() - 0.5) * 80;
    const offsetY = (Math.random() - 0.5) * 60;
 
    return this.clampToArenaBounds(
      {
        x: context.opponentPosition.x + offsetX,
        y: context.opponentPosition.y + offsetY,
      },
      context.arenaBounds
    );
  }
 
  /**
   * Calculate circle position
   */
  private calculateCirclePosition(context: CombatContext): Position {
    const angle = Math.atan2(
      context.opponentPosition.y - context.playerPosition.y,
      context.opponentPosition.x - context.playerPosition.x
    );
    const circleRadius = 150 + Math.random() * 50;
 
    return this.clampToArenaBounds(
      {
        x: context.opponentPosition.x + Math.cos(angle + Math.PI / 2) * circleRadius,
        y: context.opponentPosition.y + Math.sin(angle + Math.PI / 2) * circleRadius,
      },
      context.arenaBounds
    );
  }
 
  /**
   * Select counter-stance to opponent's stance (fix for issue #2529466994)
   * Implements actual counter logic based on Korean martial arts philosophy
   */
  private selectCounterStance(
    opponentStance: TrigramStance,
    personality: AIPersonality
  ): TrigramStance {
    // Define counter relationships based on trigram philosophy
    const stanceCounters: Record<TrigramStance, TrigramStance[]> = {
      [TrigramStance.GEON]: [TrigramStance.GAM, TrigramStance.GON], // Heaven countered by Water, Earth
      [TrigramStance.TAE]: [TrigramStance.LI, TrigramStance.GEON], // Lake countered by Fire, Heaven
      [TrigramStance.LI]: [TrigramStance.GAM, TrigramStance.SON], // Fire countered by Water, Wind
      [TrigramStance.JIN]: [TrigramStance.GAN, TrigramStance.GON], // Thunder countered by Mountain, Earth
      [TrigramStance.SON]: [TrigramStance.GAN, TrigramStance.GEON], // Wind countered by Mountain, Heaven
      [TrigramStance.GAM]: [TrigramStance.GON, TrigramStance.GAN], // Water countered by Earth, Mountain
      [TrigramStance.GAN]: [TrigramStance.JIN, TrigramStance.TAE], // Mountain countered by Thunder, Lake
      [TrigramStance.GON]: [TrigramStance.SON, TrigramStance.LI], // Earth countered by Wind, Fire
    };
 
    const counters = stanceCounters[opponentStance] ?? [];
 
    // Try to find a counter that's also in favored stances
    const favoredCounters = counters.filter((s) =>
      personality.favoredStances.includes(s)
    );
 
    if (favoredCounters.length > 0) {
      return favoredCounters[
        Math.floor(Math.random() * favoredCounters.length)
      ];
    }
 
    // Fallback to any counter stance
    if (counters.length > 0) {
      return counters[Math.floor(Math.random() * counters.length)];
    }
 
    // Last resort: use favored stance
    if (personality.favoredStances.length > 0) {
      return personality.favoredStances[
        Math.floor(Math.random() * personality.favoredStances.length)
      ];
    }
 
    // Ultimate fallback: different stance (issue #2529728009)
    const allStances = Object.values(TrigramStance);
    const filtered = allStances.filter((s) => s !== opponentStance);
    if (filtered.length === 0) {
      return opponentStance; // Edge case: same stance
    }
    return filtered[Math.floor(Math.random() * filtered.length)];
  }
 
  /**
   * Reset decision state
   */
  reset(): void {
    this.lastDecisionTime = 0;
    this.consecutiveAttacks = 0;
    this.lastStanceChange = 0;
  }
}