import 'dart:math' as math;

import 'package:test/test.dart';
import 'package:wolf_3d_dart/wolf_3d_entities.dart';

void main() {
  group('Enemy Sprite Range Validation', () {
    test('No enemy animations should have overlapping sprite indices', () {
      final allEnemies = EnemyType.values;
      final overlaps = <String>[];

      for (int i = 0; i < allEnemies.length; i++) {
        final enemyA = allEnemies[i];
        final animationsA = enemyA.animations.allRanges;

        for (int j = i; j < allEnemies.length; j++) {
          final enemyB = allEnemies[j];
          final animationsB = enemyB.animations.allRanges;

          animationsA.forEach((animA, rangeA) {
            animationsB.forEach((animB, rangeB) {
              // Skip if we are comparing the exact same animation on the same enemy
              if (enemyA == enemyB && animA == animB) return;

              // Dogs intentionally reuse some standing frames as walking frames.
              final isDogIdleWalkReuse =
                  enemyA == EnemyType.dog &&
                  enemyB == EnemyType.dog &&
                  ((animA == EnemyAnimation.idle &&
                          animB == EnemyAnimation.walking) ||
                      (animA == EnemyAnimation.walking &&
                          animB == EnemyAnimation.idle));
              if (isDogIdleWalkReuse) return;

              if (rangeA.overlaps(rangeB)) {
                // Determine the specific frames that are clashing
                final start = math.max(rangeA.start, rangeB.start);
                final end = math.min(rangeA.end, rangeB.end);
                final clashingFrames = <int>[];

                for (int f = start; f <= end; f++) {
                  if (rangeA.contains(f) && rangeB.contains(f)) {
                    clashingFrames.add(f);
                  }
                }

                if (clashingFrames.isNotEmpty) {
                  overlaps.add(
                    '${enemyA.name}.${animA.name} overlaps ${enemyB.name}.${animB.name} on frames: $clashingFrames',
                  );
                }
              }
            });
          });
        }
      }

      // Assert that the list of overlaps is empty
      expect(
        overlaps,
        isEmpty,
        reason: 'Detected sprite index collisions:\n${overlaps.join('\n')}',
      );
    });
  });
}
